forked from chriswritescode-dev/opencode-forge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch.ts
More file actions
167 lines (149 loc) · 6.94 KB
/
patch.ts
File metadata and controls
167 lines (149 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { tool } from '@opencode-ai/plugin'
import { readFile, writeFile, rename, mkdir } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { randomBytes } from 'node:crypto'
import type { ToolContext } from './types'
import { hashLine, parseAnchor } from '../utils/line-hash'
const z = tool.schema
/**
* Hard limit on the total bytes of `newContent` across all patches in a single
* call. Large tool-call payloads trigger provider stream timeouts ("Tool
* execution aborted" / "The operation timed out") — the TUI shows this as
* "~ Preparing patch..." followed by an abort, because the provider kills the
* SSE stream before the tool-call arguments finish streaming.
*
* 8 KB is comfortably below the threshold where popular providers start
* timing out mid-stream for typical model throughput, and still leaves room
* for multi-line refactors. For larger rewrites the model should split into
* multiple successive `patch` calls or use `ast-rewrite` for structural changes.
*/
const MAX_PATCH_PAYLOAD_BYTES = 8_000
/** Per-patch cap: any single `newContent` larger than this should be split
* into multiple `patch` calls or handled via `ast-rewrite`. */
const MAX_SINGLE_PATCH_BYTES = 4_000
export function createPatchTools(ctx: ToolContext): Record<string, ReturnType<typeof tool>> {
const { directory, logger, config } = ctx
if (config.harness?.hashAnchoredPatch === false) {
return {}
}
return {
patch: tool({
description:
'Apply small, hash-anchored line or range replacements atomically. Use ONLY for targeted edits where `newContent` is SHORT (≤ a few lines, ≤ ~4 KB per patch, ≤ ~8 KB total). For rewriting a function body, moving large blocks, inserting many lines, or any refactor beyond a handful of lines, split into multiple successive `patch` calls or use `ast-rewrite` for structural changes — otherwise the provider will time out mid-stream and the tool call will abort with "The operation timed out". Fails if any anchor hash does not match the current file.',
args: {
file: z.string().describe('Absolute or workspace-relative path to the file to patch.'),
patches: z
.array(
z.object({
anchor: z.string().optional(),
anchorStart: z.string().optional(),
anchorEnd: z.string().optional(),
newContent: z.string(),
}),
)
.min(1)
.describe('Ordered list of anchored replacements to apply. Keep each newContent small (≤ ~4 KB).'),
},
execute: async args => {
// Reject oversized payloads up-front to steer the model toward splitting
// into multiple calls or using `ast-rewrite` for structural changes.
let totalBytes = 0
for (let i = 0; i < args.patches.length; i++) {
const bytes = Buffer.byteLength(args.patches[i].newContent, 'utf8')
if (bytes > MAX_SINGLE_PATCH_BYTES) {
return `ERROR: patch ${i + 1}/${args.patches.length} newContent too large (${bytes} bytes > ${MAX_SINGLE_PATCH_BYTES}). Split into multiple \`patch\` calls targeting smaller ranges, or use \`ast-rewrite\` for structural changes.`
}
totalBytes += bytes
}
if (totalBytes > MAX_PATCH_PAYLOAD_BYTES) {
return `ERROR: patch payload too large (${totalBytes} bytes > ${MAX_PATCH_PAYLOAD_BYTES}). Split into multiple \`patch\` calls targeting smaller ranges, or use \`ast-rewrite\` for structural changes.`
}
const absPath = args.file.startsWith('/') ? args.file : join(directory, args.file)
let originalContent: string
try {
originalContent = await readFile(absPath, 'utf8')
} catch (err) {
return `ERROR: cannot read ${absPath}: ${(err as Error).message}`
}
const state = toMutableFileState(originalContent)
const report: string[] = []
for (let i = 0; i < args.patches.length; i++) {
const patch = args.patches[i]
try {
if (patch.anchorStart || patch.anchorEnd) {
if (!patch.anchorStart || !patch.anchorEnd) {
return `ERROR: patch ${i + 1}/${args.patches.length} — anchorStart and anchorEnd must both be provided`
}
const start = parseAnchor(patch.anchorStart)
const end = parseAnchor(patch.anchorEnd)
verifyLineAnchor(state.lines, start)
verifyLineAnchor(state.lines, end)
if (end.line < start.line) {
return `ERROR: patch ${i + 1}/${args.patches.length} — anchorEnd must be on or after anchorStart`
}
replaceRange(state.lines, start.line, end.line, patch.newContent)
report.push(`patch ${i + 1}: lines ${start.line}-${end.line}`)
continue
}
if (!patch.anchor) {
return `ERROR: patch ${i + 1}/${args.patches.length} — anchor required for single-line patch`
}
const anchor = parseAnchor(patch.anchor)
verifyLineAnchor(state.lines, anchor)
replaceRange(state.lines, anchor.line, anchor.line, patch.newContent)
report.push(`patch ${i + 1}: line ${anchor.line}`)
} catch (err) {
return `ERROR: patch ${i + 1}/${args.patches.length} — ${(err as Error).message}`
}
}
const latestContent = await readFile(absPath, 'utf8')
if (latestContent !== originalContent) {
return `ERROR: concurrent modification detected for ${absPath}`
}
const nextContent = fromMutableFileState(state)
const tmp = `${absPath}.${randomBytes(6).toString('hex')}.tmp`
try {
await mkdir(dirname(absPath), { recursive: true })
await writeFile(tmp, nextContent, 'utf8')
await rename(tmp, absPath)
} catch (err) {
return `ERROR: atomic write failed: ${(err as Error).message}`
}
logger.log(`patch: ${absPath} (${report.length} patches)`)
return `OK — ${absPath}\n${report.join('\n')}`
},
}),
}
}
function verifyLineAnchor(lines: string[], anchor: { line: number; hash: string }): void {
const current = lines[anchor.line - 1]
if (current === undefined) {
throw new Error(`anchor line ${anchor.line} is out of range`)
}
const currentAnchor = buildInlineAnchor(anchor.line, current)
if (hashLine(current) !== anchor.hash) {
throw new Error(`hash mismatch at ${anchor.line}; current is ${currentAnchor}`)
}
}
function buildInlineAnchor(line: number, content: string): string {
return `${line}#${hashLine(content)}: ${content}`
}
function replaceRange(lines: string[], startLine: number, endLine: number, newContent: string): void {
const replacement = newContent === '' ? [] : newContent.split('\n')
lines.splice(startLine - 1, endLine - startLine + 1, ...replacement)
}
function toMutableFileState(content: string): { lines: string[]; trailingNewline: boolean } {
if (content === '') {
return { lines: [], trailingNewline: false }
}
const trailingNewline = content.endsWith('\n')
const lines = trailingNewline ? content.slice(0, -1).split('\n') : content.split('\n')
return { lines, trailingNewline }
}
function fromMutableFileState(state: { lines: string[]; trailingNewline: boolean }): string {
const content = state.lines.join('\n')
if (state.trailingNewline && content !== '') {
return `${content}\n`
}
return content
}