Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { toBase64 } from '../../media'
3import { mimeTypeOf } from '../../media-ref'
4import { isRecord } from '../../utils'
5import { pathsOf, stringArg } from './backend'
6import type { ContentPart } from '@tanstack/ai'
7import type { ToolEnv } from './backend'
8
9// The page limits stay inside the defaults of `boundToolOutput` (2000 lines,
10// 50 KiB), so that plugin does not cut a page again.
11const MAX_LINES = 2000
12const MAX_PAGE_BYTES = 50 * 1024
13const MAX_LINE_CHARS = 2000
14// A NUL byte in this many first bytes marks a binary file.
15const BINARY_CHECK_BYTES = 8 * 1024
16// Media goes to the model as inline base64, and it stays in the transcript,
17// so every model call after it sends it again. 256 KiB keeps that small.
18// ponytail: big media could go to the media store of the session with
19// `ctx.session.putMedia`, as a reference. Do it when 256 KiB is too small.
20const MAX_MEDIA_BYTES = 256 * 1024
21const MAX_SUGGESTIONS = 3
22
23// The first bytes of the files that go to the model as media parts. The
24// bytes decide, not the extension: a Git LFS pointer named `x.png` is text.
25const MEDIA = [
26 { type: 'image', mimeType: 'image/png', signature: /^\x89PNG/ },
27 { type: 'image', mimeType: 'image/jpeg', signature: /^\xff\xd8\xff/ },
28 { type: 'image', mimeType: 'image/gif', signature: /^GIF8/ },
29 { type: 'image', mimeType: 'image/webp', signature: /^RIFF[\s\S]{4}WEBP/ },
30 { type: 'document', mimeType: 'application/pdf', signature: /^%PDF-/ },
31] as const
32
33// The default decoder drops a byte order mark, so the model does not see
34// it. `edit_file` keeps the mark in the file.
35const decoder = new TextDecoder()
36const encoder = new TextEncoder()
37
38/** The edit distance of `a` and `b`: the fewest one-character changes. */
39function distance(a: string, b: string) {
40 // `row[j]` is the distance of the first i characters of `a` and the first
41 // j characters of `b`. Each pass over `a` makes the next row.
42 let row = Array.from({ length: b.length + 1 }, (_, j) => j)
43 for (let i = 0; i < a.length; i++) {
44 let diagonal = i
45 let left = i + 1
46 row = row.map((above, j) => {
47 if (j === 0) return left
48 const cost = a[i] === b[j - 1] ? 0 : 1
49 left = Math.min(above + 1, left + 1, diagonal + cost)
50 diagonal = above
51 return left
52 })
53 }
54 return row.at(-1) ?? 0
55}
56
57/**
58 * The error for a file that does not exist. It names up to 3 files in the
59 * same folder with a similar name: the same name in other letter case, the
60 * same name with another extension, or a name 2 or fewer changes away.
61 */
62async function notFound(env: ToolEnv, full: string) {
63 const { dirname, join, parse } = pathsOf(env.backend)
64 const folder = dirname(full)
65 const wanted = parse(full).base.toLowerCase()
66 const wantedStem = parse(wanted).name
67 // A missing folder has no names to suggest.
68 const entries = await env.backend.readdir(folder).catch(() => [])
69 const similar = entries
70 .filter((entry) => entry.type === 'file')
71 .map((entry) => {
72 const name = entry.name.toLowerCase()
73 const isSameStem = parse(name).name === wantedStem
74 return { name: entry.name, isSameStem, distance: distance(name, wanted) }
75 })
76 .filter((item) => item.isSameStem || item.distance <= 2)
77 .sort((a, b) => a.distance - b.distance)
78 .slice(0, MAX_SUGGESTIONS)
79 .map((item) => env.shown(join(folder, item.name)))
80 const message = `File not found: ${env.shown(full)}.`
81 return new Error(
82 similar.length > 0
83 ? `${message} Did you mean ${similar.join(', ')}?`
84 : message,
85 )
86}
87
88/** `line` with its number. A line over 2000 characters is cut. */
89function numbered(lineNumber: number, line: string) {
90 const isLong = line.length > MAX_LINE_CHARS
91 const text = isLong
92 ? `${line.slice(0, MAX_LINE_CHARS)}... [line cut: ${line.length - MAX_LINE_CHARS} more characters]`
93 : line
94 return `${lineNumber}\t${text}`
95}
96
97/**
98 * The lines of `text` from line `offset`, at most `limit`, and the number of
99 * lines. A final newline ends the last line. It does not start a new one.
100 */
101function linesOf(text: string, offset: number, limit: number) {
102 const all = text.split('\n')
103 if (text.endsWith('\n')) all.pop()
104 return { lines: all.slice(offset - 1, offset - 1 + limit), total: all.length }
105}
106
107/**
108 * The numbered lines of `window`, which starts at line `offset` of a file of
109 * `total` lines. At most 50 KiB. When the page shows fewer lines than
110 * `limit` and the file goes on, a note says how to read the next page.
111 */
112function page(
113 { lines: window, total }: { lines: Array<string>; total?: number },
114 options: { path: string; offset: number; limit: number | undefined },
115) {
116 const { path, offset, limit } = options
117 const shown: Array<string> = []
118 let bytes = 0
119 for (const [index, line] of window.entries()) {
120 const row = numbered(offset + index, line)
121 // One line is at most about 8 KB, so the first line always fits.
122 bytes += encoder.encode(row).length + 1
123 if (bytes > MAX_PAGE_BYTES) break
124 shown.push(row)
125 }
126 if (shown.length === 0) {
127 const count = total === undefined ? '' : ` ${path} has ${total} lines.`
128 return `[No lines from line ${offset}.${count}]`
129 }
130 const last = offset + shown.length - 1
131 // Without `total`, the file has more lines after the page.
132 const goesOn = total === undefined || last < total
133 const isCut = shown.length < (limit ?? Infinity) && goesOn
134 if (!isCut) return shown.join('\n')
135 const of = total === undefined ? '' : ` of ${total}`
136 return `${shown.join('\n')}\n\n[Showing lines ${offset}-${last}${of}. Read more with offset ${last + 1}.]`
137}
138
139/**
140 * `read_file`: numbered lines of a text file, a page at a time. An image
141 * (PNG, JPEG, GIF, WebP) or a PDF comes back as a content part. A binary
142 * file gets a short note, not its bytes. The text that `afterRead` hooks
143 * return is added after the lines of a text file.
144 */
145export function readTools(env: ToolEnv) {
146 return [
147 toolDefinition({
148 name: 'read_file',
149 description:
150 'Read a file in the workspace. Text comes back as lines numbered from 1, at most 2000 lines or 50 KiB a page. Use offset and limit to read other lines. Images (PNG, JPEG, GIF, WebP) and PDFs up to 256 KB come back as media.',
151 inputSchema: {
152 type: 'object',
153 properties: {
154 path: { type: 'string' },
155 offset: { type: 'number', description: 'First line, from 1' },
156 limit: { type: 'number', description: 'Most lines to read' },
157 },
158 required: ['path'],
159 },
160 replay: 'safe',
161 }).server(async (args: unknown) => {
162 const full = await env.reach(stringArg(args, 'path'), 'read_file', 'file')
163 const offset =
164 isRecord(args) && typeof args.offset === 'number'
165 ? Math.max(1, args.offset)
166 : 1
167 const limit =
168 isRecord(args) && typeof args.limit === 'number'
169 ? args.limit
170 : undefined
171 const pageLimit = Math.min(limit ?? MAX_LINES, MAX_LINES)
172 return env.lock(full, async () => {
173 const path = env.shown(full)
174 const { backend } = env
175 // One call when the file is there. A failed read checks if it is.
176 const missing = async (error: unknown): Promise<never> => {
177 if (!(await backend.stat(full))) throw await notFound(env, full)
178 throw error
179 }
180 // `readLines` reads one page. Without it, the whole file is read.
181 const paged = await backend
182 .readLines?.(full, { offset, limit: pageLimit })
183 .catch(missing)
184 const whole = paged
185 ? undefined
186 : await backend.readFile(full).catch(missing)
187 const head = paged?.head ?? whole?.subarray(0, BINARY_CHECK_BYTES)
188 const size = paged?.size ?? whole?.length ?? 0
189 const start = String.fromCharCode(...(head ?? []).slice(0, 12))
190 const media = MEDIA.find((item) => item.signature.test(start))
191 if (media) {
192 if (size > MAX_MEDIA_BYTES) {
193 const kb = Math.ceil(size / 1024)
194 throw new Error(
195 `${path} is ${kb} KB. read_file sends images and PDFs up to 256 KB. Make a smaller copy, for example with bash, and read that.`,
196 )
197 }
198 const bytes = whole ?? (await backend.readFile(full))
199 const part: ContentPart = {
200 type: media.type,
201 source: {
202 type: 'data',
203 value: toBase64(bytes),
204 mimeType: media.mimeType,
205 },
206 }
207 return [part]
208 }
209 if (head?.includes(0)) {
210 const type = mimeTypeOf(full)
211 const typeNote = type === undefined ? '' : `, ${type}`
212 return `${path} is a binary file (${size} bytes${typeNote}). read_file shows text, images, and PDFs only.`
213 }
214 const text = paged ?? linesOf(decoder.decode(whole), offset, pageLimit)
215 const parts = [page(text, { path, offset, limit })]
216 const hooks = env.hooks()
217 for (const hook of hooks) {
218 const extra = await hook.afterRead?.(full)
219 if (extra) parts.push(extra)
220 }
221 return parts.join('\n\n')
222 })
223 }),
224 ]
225}