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

edit.ts

326 lines11.6 KB

1import { toolDefinition } from '@tanstack/ai'
2import { isRecord } from '../../utils'
3import { afterWrite, beforeWrite, readText, stringArg } from './backend'
4import { readForDiff, reportChange } from './file-change'
5import type { ToolEnv } from './backend'
6​
7const BOM = ''
8​
9/**
10 * How one match level changes text before the search. `pieces` cuts the text
11 * into pieces, and `change` gives the new text of each piece. `changes` is a
12 * fast test: false when the level leaves the text as it is.
13 */
14interface Level {
15 pieces: RegExp
16 change: (piece: RegExpExecArray) => string
17 changes: (text: string) => boolean
19​
20// The match levels after the exact text, from strict to loose.
21const LEVELS: ReadonlyArray<Level> = [
22 // Unicode NFC form. A piece is a character and the marks after it.
23 // ponytail: decomposed Hangul jamo stay apart. Cut by grapheme if needed.
24 {
25 pieces: /\P{M}\p{M}*|\p{M}+/gu,
26 change: (piece) => piece[0].normalize('NFC'),
27 changes: (text) => text.normalize('NFC') !== text,
28 },
29 // Spaces and tabs at the end of each line removed.
30 {
31 pieces: /([^\S\n]+(?=\n|$))|[\s\S]/g,
32 change: (piece) => (piece[1] ? '' : piece[0]),
33 changes: (text) => /[^\S\n](?=\n|$)/.test(text),
34 },
36​
37/**
38 * `text` changed by `level`, and where each character of the result starts in
39 * `text`. `at[i]` is `undefined` inside a changed piece. The last entry of
40 * `at` is the end of `text`.
41 */
42function changed(text: string, level: Level) {
43 let result = ''
44 const at: Array<number | undefined> = []
45 const pieces = text.matchAll(level.pieces)
46 for (const piece of pieces) {
47 const next = level.change(piece)
48 // An unchanged piece maps one to one. A changed piece maps its start only.
49 const same = next === piece[0]
50 for (let i = 0; i < next.length; i++) {
51 at.push(same || i === 0 ? piece.index + i : undefined)
52 }
53 result += next
54 }
55 at.push(text.length)
56 return { text: result, at }
58​
59/** Where `find` starts in `text`, without overlaps. None for an empty `find`. */
60function indexesOf(text: string, find: string) {
61 const found: Array<number> = []
62 if (find === '') return found
63 let index = text.indexOf(find)
64 while (index !== -1) {
65 found.push(index)
66 index = text.indexOf(find, index + find.length)
67 }
68 return found
70​
71/** `text` with the line endings of `content`: CRLF when it has one, else LF. */
72export function toEndingsOf(text: string, content: string) {
73 return text.replace(/\r?\n/g, content.includes('\r\n') ? '\r\n' : '\n')
75​
76/**
77 * Find `find` in `content`. Three levels are tried in order, and the first
78 * level with a match wins:
79 *
80 * 1. The exact text.
81 * 2. Both sides in Unicode NFC form.
82 * 3. Spaces and tabs at the end of each line ignored. A match then also covers
83 * the trailing spaces of its last line.
84 *
85 * `find` first gets the line endings of `content`, so LF text matches a CRLF
86 * file.
87 *
88 * Returns each match as `{ start, end }` offsets into the original `content`,
89 * in order and without overlaps. An empty array means no match. More than one
90 * match means the text is not unique.
91 *
92 * @example
93 * ```ts
94 * findMatches('a \nb\n', 'a\nb') // [{ start: 0, end: 5 }]
95 * ```
96 */
97export function findMatches(content: string, find: string) {
98 const wanted = toEndingsOf(find, content)
99 const exact = indexesOf(content, wanted)
100 if (exact.length > 0) {
101 return exact.map((start) => ({ start, end: start + wanted.length }))
102 }
103 for (const level of LEVELS) {
104 // A level that changes neither side finds only the exact matches, and
105 // there are none. On a big file the change is slow, so skip it.
106 if (!level.changes(content) && !level.changes(wanted)) continue
107 const { text, at } = changed(content, level)
108 const needle = changed(wanted, level).text
109 const starts = indexesOf(text, needle)
110 const matches = starts.flatMap((index) => {
111 const start = at[index]
112 const end = at[index + needle.length]
113 // A match must start and end where a piece starts.
114 return start === undefined || end === undefined ? [] : [{ start, end }]
115 })
116 if (matches.length > 0) return matches
117 }
118 return []
120​
121/**
122 * What each chat run of one workspace binding saw of each file: its size and
123 * change time when a tool read it or wrote it. A write checks that the file
124 * is still as its own chat run saw it, so an edit of another session, of a
125 * subagent, or of a parallel agent is never lost. `chatOf` gives the chat run
126 * of the call that runs now. Without one, the calls share one record. Call
127 * each function under the lock of the path. The paths come from `env.reach`.
128 *
129 * ponytail: a change that keeps the size and the `mtimeMs` is not seen.
130 */
131export function fileVersions(
132 env: ToolEnv,
133 chatOf: () => object | undefined = () => undefined,
134) {
135 type Seen = Map<string, { size: number; mtimeMs: number }>
136 const shared: Seen = new Map()
137 const byChat = new WeakMap<object, Seen>()
138 /** The record of the chat run of the call that runs now. */
139 const records = () => {
140 const chat = chatOf()
141 if (!chat) return shared
142 const known = byChat.get(chat)
143 if (known) return known
144 const created: Seen = new Map()
145 byChat.set(chat, created)
146 return created
147 }
148 return {
149 /** Remember the file at `path` as it is now: a tool read or wrote it. */
150 saw: async (path: string) => {
151 const seen = records()
152 const info = await env.backend.stat(path)
153 if (info?.type === 'file') {
154 seen.set(path, { size: info.size, mtimeMs: info.mtimeMs })
155 } else {
156 seen.delete(path)
157 }
158 },
159 /** Forget `path`: a tool removed it. */
160 forget: (path: string) => {
161 records().delete(path)
162 },
163 /** Is something at `path`? Call it before the lock. */
164 exists: async (path: string) =>
165 (await env.backend.stat(path)) !== undefined,
166 /**
167 * Throws when the file at `path` changed since a tool read or wrote it.
168 * For a file that no tool read, it throws only when the tool saw no file
169 * there before the lock (`missing`), and a file is there now.
170 */
171 check: async (path: string, { missing }: { missing: boolean }) => {
172 const known = records().get(path)
173 const now = await env.backend.stat(path)
174 const shown = env.shown(path)
175 if (known) {
176 const isSame =
177 now?.type === 'file' &&
178 now.size === known.size &&
179 now.mtimeMs === known.mtimeMs
180 if (!isSame) {
181 throw new Error(
182 `${shown} changed since it was read. Read it again before you edit it.`,
183 )
184 }
185 return
186 }
187 if (missing && now !== undefined) {
188 throw new Error(
189 `${shown} was created while the tool waited. Read it before you edit it.`,
190 )
191 }
192 },
193 }
195​
196/** The file record of a binding, from {@link fileVersions}. */
197export type FileVersions = ReturnType<typeof fileVersions>
198​
199/**
200 * Run the `afterWrite` hooks for the `written` files, after their locks: a
201 * hook (a formatter) never runs while a lock is held. Then `versions`
202 * remembers each file as the hooks left it, under its lock again, so the
203 * next write does not take the formatter's change for a change of another
204 * session. Resolves to the notes of the hooks.
205 *
206 * ponytail: a write of another session between the hooks and that lock
207 * counts as seen too.
208 */
209export async function afterWriteSeen(
210 env: ToolEnv,
211 versions: FileVersions,
212 written: ReadonlyArray<string>,
213) {
214 // No hook, no change: the write remembered the files already.
215 if (!env.hooks().some((hook) => hook.afterWrite)) return []
216 const notes: Array<string> = []
217 for (const full of written) notes.push(...(await afterWrite(env, full)))
218 for (const full of written) await env.lock(full, () => versions.saw(full))
219 return notes
221​
222/**
223 * `write_file` and `edit_file`. The `beforeWrite` hooks can refuse the call
224 * first. Each write checks with `versions` that
225 * the file did not change since a tool read it. After each write, the
226 * `afterWrite` hooks run for the file, and then the tool sends `FileChanged`
227 * (see {@link reportChange}). `edit_file` finds the old text with
228 * {@link findMatches}. It writes the new text with the line endings of the
229 * file, and keeps a byte order mark.
230 */
231export function editTools(env: ToolEnv, versions: FileVersions) {
232 return [
233 toolDefinition({
234 name: 'write_file',
235 description: 'Create or replace a file in the workspace.',
236 inputSchema: {
237 type: 'object',
238 properties: { path: { type: 'string' }, content: { type: 'string' } },
239 required: ['path', 'content'],
240 },
241 }).server(async (args: unknown, context) => {
242 const full = await env.reach(
243 stringArg(args, 'path'),
244 'write_file',
245 'file',
246 )
247 const content = stringArg(args, 'content')
248 await beforeWrite(env, [full])
249 const missing = !(await versions.exists(full))
250 const before = await env.lock(full, async () => {
251 await versions.check(full, { missing })
252 // The old text, for the diff. A file over 1 MiB is not read.
253 const old = await readForDiff(env.backend, full)
254 await env.backend.writeFile(full, content)
255 await versions.saw(full)
256 return old
257 })
258 const notes = await afterWriteSeen(env, versions, [full])
259 await reportChange(env, {
260 path: full,
261 before,
262 toolCallId: context?.toolCallId,
263 })
264 return [`Wrote ${env.shown(full)}.`, ...notes].join('\n')
265 }),
266 toolDefinition({
267 name: 'edit_file',
268 description:
269 'Replace exact text in a file. `old` must appear once, unless `replaceAll` is true.',
270 inputSchema: {
271 type: 'object',
272 properties: {
273 path: { type: 'string' },
274 old: { type: 'string' },
275 new: { type: 'string' },
276 replaceAll: { type: 'boolean' },
277 },
278 required: ['path', 'old', 'new'],
279 },
280 }).server(async (args: unknown, context) => {
281 const full = await env.reach(stringArg(args, 'path'), 'edit_file', 'file')
282 const oldText = stringArg(args, 'old')
283 const newText = stringArg(args, 'new')
284 const replaceAll = isRecord(args) && args.replaceAll === true
285 await beforeWrite(env, [full])
286 const edited = await env.lock(full, async () => {
287 // The edit reads the file itself, so a file that no tool read can
288 // change. One that a tool read must be as that read saw it.
289 await versions.check(full, { missing: false })
290 const before = await readText(env.backend, full)
291 const matches = findMatches(before, oldText)
292 const count = matches.length
293 if (count === 0) throw new Error('The old text is not in the file.')
294 if (count > 1 && !replaceAll) {
295 throw new Error(
296 `The old text appears ${count} times. Add context, or set replaceAll.`,
297 )
298 }
299 const replacement = toEndingsOf(newText, before)
300 let after = ''
301 let from = 0
302 for (const { start, end } of matches) {
303 after += before.slice(from, start) + replacement
304 from = end
305 }
306 after += before.slice(from)
307 // Keep the byte order mark, also when the new text drops it.
308 const keepBom = before.startsWith(BOM) && !after.startsWith(BOM)
309 await env.backend.writeFile(full, keepBom ? BOM + after : after)
310 await versions.saw(full)
311 return { count, before }
312 })
313 const notes = await afterWriteSeen(env, versions, [full])
314 await reportChange(env, {
315 path: full,
316 before: edited.before,
317 toolCallId: context?.toolCallId,
318 })
319 const { count } = edited
320 return [
321 `Edited ${env.shown(full)} (${count} change${count > 1 ? 's' : ''}).`,
322 ...notes,
323 ].join('\n')
324 }),
325 ]