Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

patch.ts

513 lines18.2 KB

1import { toolDefinition } from '@tanstack/ai'
2import { beforeWrite, readText, stringArg } from './backend'
3import { afterWriteSeen, findMatches, toEndingsOf } from './edit'
4import { readForDiff, reportChange } from './file-change'
5import type { ToolEnv } from './backend'
6import type { FileVersions } from './edit'
7import type { DiffText } from './file-change'
8​
9const BOM = ''
10​
11/** One chunk of an `*** Update File:` section. */
12export interface PatchChunk {
13 /** The text after `@@`: a line above the change, to find the place. */
14 context?: string
15 /** The lines that the chunk replaces: the context and `-` lines. */
16 oldLines: Array<string>
17 /** The lines that replace them: the context and `+` lines. */
18 newLines: Array<string>
19 /** True after `*** End of File`: the old lines end the file. */
20 endOfFile: boolean
22​
23/** One file change of a patch. The paths are as the patch gives them. */
24export type PatchOperation =
25 | { type: 'add'; path: string; content: string }
26 | { type: 'delete'; path: string }
27 | {
28 type: 'update'
29 path: string
30 movePath?: string
31 chunks: Array<PatchChunk>
32 }
33​
34/** The file changes of a patch, in order. */
35export type ParsedPatch = Array<PatchOperation>
36​
37const DESCRIPTION = `Change files with a patch:
38​
39*** Begin Patch
40*** Add File: src/new.ts
41+each line of a new file starts with +
42*** Update File: src/app.ts
43@@ function main() {
44 a context line starts with a space
45-a removed line starts with -
46+an added line starts with +
47*** Delete File: src/old.ts
48*** End Patch
49​
50In an update, each chunk starts with @@. The text after @@ is optional. It is a line above the change, to find the place. Give 3 context lines above and below each change, so the old lines are unique. Chunks apply in order. "*** Move to: <path>" right after "*** Update File:" renames the file. "*** End of File" after a chunk means that the chunk ends the file.`
51​
52function lineError(index: number, message: string) {
53 return new Error(`Patch line ${index + 1}: ${message}`)
55​
56/** The path after a header. Throws when it is empty. */
57function pathAt(index: number, rest = '') {
58 const path = rest.trim()
59 if (path === '') throw lineError(index, 'the path is missing.')
60 return path
62​
63/** Throws when `operation` is an update with no lines and no move. */
64function checkNotEmpty(operation: PatchOperation | undefined, index: number) {
65 if (operation?.type !== 'update' || operation.movePath !== undefined) return
66 const hasLines = operation.chunks.some(
67 (chunk) => chunk.oldLines.length + chunk.newLines.length > 0,
68 )
69 if (!hasLines) {
70 throw lineError(
71 index,
72 `"*** Update File: ${operation.path}" has no changes.`,
73 )
74 }
76​
77function newChunk(context: string) {
78 const chunk: PatchChunk = {
79 context: context || undefined,
80 oldLines: [],
81 newLines: [],
82 endOfFile: false,
83 }
84 return chunk
86​
87const isFilled = (line: string) => line.trim() !== ''
88​
89/**
90 * Read a patch in the `*** Begin Patch` format into its file changes. Throws
91 * an error with the line number when the text does not follow the format.
92 *
93 * @example
94 * ```ts
95 * parsePatch('*** Begin Patch\n*** Delete File: old.txt\n*** End Patch')
96 * // [{ type: 'delete', path: 'old.txt' }]
97 * ```
98 */
99export function parsePatch(text: string) {
100 const lines = text.split(/\r?\n/)
101 const first = Math.max(lines.findIndex(isFilled), 0)
102 const last = lines.findLastIndex(isFilled)
103 if (lines[first]?.trim() !== '*** Begin Patch') {
104 throw lineError(first, 'the patch must start with "*** Begin Patch".')
105 }
106 if (last === first || lines[last]?.trim() !== '*** End Patch') {
107 throw lineError(last, 'the patch must end with "*** End Patch".')
108 }
109 const operations: ParsedPatch = []
110 let current: PatchOperation | undefined
111 let currentLine = first
112 // The chunk that new lines go to.
113 let chunk: PatchChunk | undefined
114 for (let index = first + 1; index < last; index++) {
115 const line = lines[index] ?? ''
116 const head = line.trimEnd()
117 const header = /^\*\*\* (Add|Delete|Update) File:(.*)$/.exec(head)
118 if (header) {
119 checkNotEmpty(current, currentLine)
120 const [, kind, rest] = header
121 const path = pathAt(index, rest)
122 if (kind === 'Add') current = { type: 'add', path, content: '' }
123 else if (kind === 'Delete') current = { type: 'delete', path }
124 else current = { type: 'update', path, chunks: [] }
125 operations.push(current)
126 currentLine = index
127 chunk = undefined
128 continue
129 }
130 const move = /^\*\*\* Move to:(.*)$/.exec(head)
131 if (move) {
132 if (
133 current?.type !== 'update' ||
134 current.chunks.length > 0 ||
135 current.movePath !== undefined
136 ) {
137 throw lineError(
138 index,
139 '"*** Move to:" must come right after "*** Update File:".',
140 )
141 }
142 current.movePath = pathAt(index, move[1])
143 continue
144 }
145 if (head === '*** End of File') {
146 if (!chunk) {
147 throw lineError(index, '"*** End of File" must come after a chunk.')
148 }
149 chunk.endOfFile = true
150 chunk = undefined
151 continue
152 }
153 switch (current?.type) {
154 case undefined:
155 case 'delete':
156 if (head !== '') {
157 throw lineError(
158 index,
159 'expected "*** Add File:", "*** Delete File:", or "*** Update File:".',
160 )
161 }
162 break
163 case 'add':
164 if (!line.startsWith('+')) {
165 throw lineError(
166 index,
167 'each line of an added file must start with "+".',
168 )
169 }
170 current.content += `${line.slice(1)}\n`
171 break
172 case 'update': {
173 if (line.startsWith('@@')) {
174 chunk = newChunk(line.slice(2).trim())
175 current.chunks.push(chunk)
176 break
177 }
178 // An empty line is an empty context line. Editors often drop the
179 // space at the end of a line.
180 const sign = line.charAt(0) || ' '
181 if (sign !== ' ' && sign !== '-' && sign !== '+') {
182 throw lineError(
183 index,
184 'each chunk line must start with " ", "-", or "+".',
185 )
186 }
187 // The first chunk can start without `@@`.
188 if (!chunk) {
189 chunk = newChunk('')
190 current.chunks.push(chunk)
191 }
192 const body = line.slice(1)
193 if (sign !== '+') chunk.oldLines.push(body)
194 if (sign !== '-') chunk.newLines.push(body)
195 break
196 }
197 }
198 }
199 checkNotEmpty(current, currentLine)
200 if (operations.length === 0) {
201 throw lineError(first, 'the patch has no file changes.')
202 }
203 return operations
205​
206/**
207 * Every path that a patch changes, also the targets of `*** Move to:`, as
208 * the patch gives them. The permission rules check them. Throws when the
209 * patch does not parse.
210 *
211 * @example
212 * ```ts
213 * patchPaths(text) // ['src/a.ts', 'src/old.ts', 'src/new.ts']
214 * ```
215 */
216export function patchPaths(text: string) {
217 const operations = parsePatch(text)
218 return operations.flatMap((operation) =>
219 operation.type === 'update' && operation.movePath !== undefined
220 ? [operation.path, operation.movePath]
221 : [operation.path],
222 )
224​
225/** The lines as text, each with a line ending. */
226const asText = (lines: ReadonlyArray<string>) =>
227 lines.map((line) => `${line}\n`).join('')
228​
229/**
230 * `content` with `chunks` applied in order. A chunk is searched after the
231 * chunk before it, and from the line of its `@@` text. The old lines must be
232 * whole lines, and must be there once. Keeps a byte order mark, the line
233 * endings, and a missing line ending at the end. `name` is the file, for the
234 * errors.
235 */
236function applyChunks(
237 content: string,
238 chunks: ReadonlyArray<PatchChunk>,
239 name: string,
240) {
241 const hasBom = content.startsWith(BOM)
242 const body = hasBom ? content.slice(1) : content
243 const eol = toEndingsOf('\n', body)
244 // Work on text that ends with a line ending, so the last line is like the
245 // others.
246 const ended = body === '' || body.endsWith('\n')
247 let text = ended ? body : body + eol
248 // Where the next chunk starts to search.
249 let from = 0
250 const entries = chunks.entries()
251 for (const [index, chunk] of entries) {
252 const label = `Chunk ${index + 1} of ${name}`
253 const newText = toEndingsOf(asText(chunk.newLines), text)
254 // With `@@` text, search from its line. Only added lines go below it.
255 let searchFrom = from
256 let below = text.length
257 if (chunk.context !== undefined) {
258 const [found] = findMatches(text.slice(from), chunk.context)
259 if (!found) {
260 throw new Error(`${label}: "@@ ${chunk.context}" is not in the file.`)
261 }
262 searchFrom = text.lastIndexOf('\n', from + found.start - 1) + 1
263 below = text.indexOf('\n', from + found.end) + 1
264 }
265 if (chunk.oldLines.length === 0) {
266 const spot = chunk.endOfFile ? text.length : below
267 text = text.slice(0, spot) + newText + text.slice(spot)
268 from = spot + newText.length
269 continue
270 }
271 const oldText = toEndingsOf(asText(chunk.oldLines), text)
272 // ponytail: a match inside a line can hide a whole-line match that
273 // overlaps it. The chunk then is not found, and the model adds context.
274 const isWhole = (match: { start: number; end: number }) => {
275 const startsLine = match.start === 0 || text[match.start - 1] === '\n'
276 const endsRight = !chunk.endOfFile || match.end === text.length
277 return startsLine && endsRight
278 }
279 const matches = findMatches(text.slice(searchFrom), oldText)
280 .map((match) => ({
281 start: match.start + searchFrom,
282 end: match.end + searchFrom,
283 }))
284 .filter(isWhole)
285 const [match, ...others] = matches
286 if (!match) throw new Error(`${label}: the old lines are not in the file.`)
287 if (others.length > 0) {
288 throw new Error(
289 `${label}: the old lines appear ${matches.length} times. Add context lines.`,
290 )
291 }
292 text = text.slice(0, match.start) + newText + text.slice(match.end)
293 from = match.start + newText.length
294 }
295 const result = ended ? text : text.replace(/\r?\n$/, '')
296 return hasBom ? BOM + result : result
298​
299/**
300 * One operation with its absolute paths. `to` is the move target, or `full`
301 * when the file does not move.
302 */
303interface Step {
304 operation: PatchOperation
305 full: string
306 to: string
308​
309/**
310 * Apply each step. Every file is read and checked first. The files are
311 * written and removed only when every operation fits, and `versions`
312 * remembers the files as the patch left them. Resolves to the lines of the
313 * result, the written files for the `afterWrite` hooks, and one report for
314 * each changed file, for {@link reportChange}.
315 */
316async function applyAll(
317 env: ToolEnv,
318 versions: FileVersions,
319 steps: ReadonlyArray<Step>,
320) {
321 const { backend } = env
322 // The new state of each file: its text, or `null` to remove it. A later
323 // operation on a file sees it. A removed file is always a file that was
324 // there before the patch.
325 const planned = new Map<string, string | null>()
326 // The text of each file before the patch, for the diffs, from the first
327 // step on the file (see `readForDiff`).
328 const original = new Map<string, DiffText>()
329 // The old path of each moved file, by its new path.
330 const movedFrom = new Map<string, string>()
331 const changes: Array<string> = []
332 for (const { operation, full, to } of steps) {
333 const shown = env.shown(full)
334 switch (operation.type) {
335 case 'add':
336 // Checked here, so a patch that does not fit writes nothing.
337 if ((await backend.stat(full))?.type === 'dir') {
338 throw new Error(`Cannot add ${shown}: it is a folder.`)
339 }
340 // An add can replace a file that is there.
341 if (!planned.has(full)) {
342 original.set(full, await readForDiff(backend, full))
343 }
344 planned.set(full, operation.content)
345 changes.push(`added ${shown}`)
346 break
347 case 'delete': {
348 if (!backend.remove) {
349 throw new Error(
350 `Cannot delete ${shown}: the workspace cannot remove files.`,
351 )
352 }
353 if (planned.has(full)) {
354 throw new Error(
355 `Cannot delete ${shown}: the patch changes it before.`,
356 )
357 }
358 const isFile = (await backend.stat(full))?.type === 'file'
359 if (!isFile) throw new Error(`Cannot delete ${shown}: no such file.`)
360 original.set(full, await readForDiff(backend, full))
361 planned.set(full, null)
362 changes.push(`deleted ${shown}`)
363 break
364 }
365 case 'update': {
366 const isMove = to !== full
367 const toShown = env.shown(to)
368 if (isMove) {
369 if (!backend.remove) {
370 throw new Error(
371 `Cannot move ${shown}: the workspace cannot remove files.`,
372 )
373 }
374 if (planned.has(full)) {
375 throw new Error(
376 `Cannot move ${shown}: the patch changes it before.`,
377 )
378 }
379 // The target must be free: no file, or a file that the patch
380 // removes before.
381 const isFree =
382 planned.get(to) === null ||
383 (!planned.has(to) && (await backend.stat(to)) === undefined)
384 if (!isFree) {
385 throw new Error(
386 `Cannot move ${shown} to ${toShown}: ${toShown} already exists.`,
387 )
388 }
389 }
390 const known = planned.get(full)
391 if (known === null) {
392 throw new Error(
393 `Cannot update ${shown}: the patch removes it before.`,
394 )
395 }
396 const before = known ?? (await readText(backend, full))
397 // The first step on the file: `before` is its text before the patch.
398 if (known === undefined) original.set(full, before)
399 planned.set(to, applyChunks(before, operation.chunks, shown))
400 if (isMove) {
401 planned.set(full, null)
402 movedFrom.set(to, full)
403 }
404 changes.push(
405 isMove ? `moved ${shown} to ${toShown}` : `updated ${shown}`,
406 )
407 break
408 }
409 }
410 }
411 const files = [...planned]
412 const written = files.flatMap(([full, text]) =>
413 text === null ? [] : [{ full, text }],
414 )
415 const removed = files.flatMap(([full, text]) => (text === null ? [full] : []))
416 for (const { full, text } of written) await backend.writeFile(full, text)
417 // The checks above refuse a removal when the backend has no `remove`.
418 for (const full of removed) await backend.remove?.(full)
419 for (const { full } of written) await versions.saw(full)
420 for (const full of removed) versions.forget(full)
421 // One report for each file. A move is one report, at its new path.
422 // ponytail: a move onto a file that the patch deleted before reports
423 // only the move, not the old text of the target.
424 const sources = new Set(movedFrom.values())
425 const reports = files.flatMap(([full, text]) => {
426 const isMovedAway = text === null && sources.has(full)
427 if (isMovedAway) return []
428 const from = movedFrom.get(full)
429 return [{ path: full, from, before: original.get(from ?? full) }]
430 })
431 return { changes, written: written.map(({ full }) => full), reports }
433​
434/**
435 * The `patch` tool: it changes files with a patch in the `*** Begin Patch`
436 * format (see {@link parsePatch}). The old lines of a chunk are found with
437 * {@link findMatches}. All files are checked before the first write, so a
438 * patch that does not fit changes nothing. The `afterWrite` hooks run for
439 * each written file. The result lists the changed files.
440 *
441 * - `*** Add File:` replaces a file that is there, like `write_file`.
442 * - `*** Delete File:` needs a file there.
443 * - `*** Move to:` writes the new path, then removes the old one. It refuses
444 * a target that is already there, unless the patch removes it first.
445 * - A delete or a move needs `remove` on the backend. Without it, the tool
446 * refuses them, before it writes anything.
447 * - A file that the patch removed or moved away cannot change again in the
448 * same patch. A file cannot be removed or moved after the patch changed it.
449 * - A file that changed since a tool read it fails the patch, before it
450 * writes anything (see `versions`).
451 * - The `beforeWrite` hooks run for each file first. A refusal fails the
452 * patch, before it writes anything.
453 * - After the hooks, each changed file sends `FileChanged` (see
454 * {@link reportChange}), with its text from before the patch. A move
455 * sends one `'moved'` event.
456 */
457export function patchTools(env: ToolEnv, versions: FileVersions) {
458 return [
459 toolDefinition({
460 name: 'patch',
461 description: DESCRIPTION,
462 inputSchema: {
463 type: 'object',
464 properties: { patch: { type: 'string' } },
465 required: ['patch'],
466 },
467 }).server(async (args: unknown, context) => {
468 const operations = parsePatch(stringArg(args, 'patch'))
469 // Resolve each path first. The rules decided an outside path before
470 // the call.
471 const steps: Array<Step> = []
472 for (const operation of operations) {
473 const full = await env.reach(operation.path, 'patch', 'file')
474 const movePath =
475 operation.type === 'update' ? operation.movePath : undefined
476 const to =
477 movePath === undefined
478 ? full
479 : await env.reach(movePath, 'patch', 'file')
480 steps.push({ operation, full, to })
481 }
482 // Hold the lock of every file, taken in one fixed order, so two
483 // patches cannot wait for each other.
484 const paths = [
485 ...new Set(steps.flatMap((step) => [step.full, step.to])),
486 ].sort()
487 // Every file that the patch changes, before the first write.
488 await beforeWrite(env, paths)
489 // The paths with no file before the locks. A file there under the
490 // locks is new, and the patch did not see it.
491 const missing = new Set<string>()
492 for (const path of paths) {
493 if (!(await versions.exists(path))) missing.add(path)
494 }
495 let run = async () => {
496 for (const path of paths) {
497 await versions.check(path, { missing: missing.has(path) })
498 }
499 return applyAll(env, versions, steps)
500 }
501 for (const path of paths) {
502 const inner = run
503 run = () => env.lock(path, inner)
504 }
505 const { changes, written, reports } = await run()
506 const notes = await afterWriteSeen(env, versions, written)
507 for (const report of reports) {
508 await reportChange(env, { ...report, toolCallId: context?.toolCallId })
509 }
510 return ['Applied the patch:', ...changes, ...notes].join('\n')
511 }),
512 ]