Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { createOutputTail } from '@tanstack/ai-utils'
3import { isRecord } from '../../utils'
4import { boundText } from '../bound-output'
5import { pathsOf, runOf, stringArg } from './backend'
6import { JobEnded, JobOutput, JobStarted } from './events'
7import type { PluginEvent } from '../../extensions'
8import type { BackgroundJobsApi } from '../../plugins'
9import type { RunContext } from '../../types'
10import type { ToolEnv } from './backend'
11
12/** The longest timeout that one call can ask for: 10 minutes. */
13const MAX_TIMEOUT_MS = 10 * 60 * 1000
14/**
15 * How much output the model gets: the last lines. The limits are below the
16 * defaults of `boundToolOutput` (2000 lines, 50 KiB), so that plugin does
17 * not cut the result again and remove the exit code.
18 */
19const OUTPUT_LIMITS = {
20 maxLines: 1000,
21 maxBytes: 20 * 1024,
22 keep: 'tail',
23} as const
24/** Added to the environment of every command, so tools can see an agent. */
25const AGENT_ENV = { AGENT: '1' }
26/** Shell syntax that can hide a command inside another command. */
27const HIDDEN_COMMAND = /\$\(|`|<\(|>\(|<</
28/** The operators between simple commands. `||` comes before `|`. */
29const OPERATORS = ['&&', '||', ';', '|', '\n']
30
31/**
32 * The simple commands in a shell command, so a permission rule can check
33 * each one. It splits on `&&`, `||`, `;`, `|`, and new lines that are not
34 * in quotes or after a backslash.
35 *
36 * It fails closed: for `$(`, a backtick, `<(`, `>(`, a heredoc (`<<`), an
37 * unquoted `(`, or a quote that does not close, the whole command comes
38 * back as one part. The permission rules never allow a part that still has
39 * shell syntax in it.
40 *
41 * @example
42 * ```ts
43 * splitCommand('ls && rm -rf x') // ['ls', 'rm -rf x']
44 * splitCommand('echo $(rm x)') // ['echo $(rm x)']
45 * ```
46 */
47export function splitCommand(command: string) {
48 if (HIDDEN_COMMAND.test(command)) return [command]
49 const parts: Array<string> = []
50 let part = ''
51 // The open quote. In `'...'` every character is as is. In `"..."` and
52 // `$'...'` a backslash escapes the next character.
53 let quote: "'" | '"' | "$'" | undefined
54 for (let i = 0; i < command.length; i++) {
55 const char = command.charAt(i)
56 if (quote === "'") {
57 if (char === "'") quote = undefined
58 part += char
59 continue
60 }
61 if (char === '\\') {
62 part += command.slice(i, i + 2)
63 i++
64 continue
65 }
66 if (quote !== undefined) {
67 const closes = char === (quote === '"' ? '"' : "'")
68 if (closes) quote = undefined
69 part += char
70 continue
71 }
72 const operator = OPERATORS.find((item) => command.startsWith(item, i))
73 if (operator !== undefined) {
74 parts.push(part)
75 part = ''
76 i += operator.length - 1
77 continue
78 }
79 // A subshell or a function body, for example `ls() ( rm -rf x ); ls`.
80 if (char === '(') return [command]
81 if (command.startsWith("$'", i)) {
82 quote = "$'"
83 part += "$'"
84 i++
85 continue
86 }
87 if (char === "'" || char === '"') quote = char
88 part += char
89 }
90 if (quote !== undefined) return [command]
91 parts.push(part)
92 // Remove only spaces and tabs, the blanks of the shell. A `\r` stays, so
93 // the permission rules see it.
94 return parts
95 .map((item) => item.replace(/^[ \t]+|[ \t]+$/g, ''))
96 .filter((item) => item !== '')
97}
98
99/**
100 * The command parts of a `bash` call, for `PermissionResources`. Throws when
101 * `command` is not a string, and that refuses the call.
102 *
103 * @example
104 * ```ts
105 * PermissionResources.item({ bash: { commands: bashResources } })
106 * ```
107 */
108export function bashResources(input: unknown) {
109 return splitCommand(stringArg(input, 'command'))
110}
111
112/** At most this many background jobs run at a time in a session. */
113const DEFAULT_MAX_JOBS = 8
114/** A job sends at most one output event in this time. */
115const OUTPUT_EVERY_MS = 250
116/** One output event has at most the newest 64 KiB. */
117const MAX_EVENT_OUTPUT = 64 * 1024
118
119/** Sends a plugin event, like `ctx.emit` of a plugin. */
120type Emit = <T>(event: PluginEvent<T>, value: T) => void
121
122/**
123 * The output events of job `jobId`. `push` keeps new text. The text goes
124 * out at most once each {@link OUTPUT_EVERY_MS}. `flush` sends what waits
125 * now, and `stop` drops it.
126 */
127function outputEvents(jobId: string, emit: Emit) {
128 let waiting = createOutputTail(MAX_EVENT_OUTPUT)
129 let hasText = false
130 let timer: ReturnType<typeof setTimeout> | undefined
131 let lastSent = 0
132 const flush = () => {
133 clearTimeout(timer)
134 timer = undefined
135 if (!hasText) return
136 const output = waiting.text()
137 waiting = createOutputTail(MAX_EVENT_OUTPUT)
138 hasText = false
139 lastSent = Date.now()
140 emit(JobOutput, { jobId, output })
141 }
142 const push = (text: string) => {
143 if (text === '') return
144 waiting.push(text)
145 hasText = true
146 if (timer) return
147 const wait = Math.max(0, lastSent + OUTPUT_EVERY_MS - Date.now())
148 timer = setTimeout(flush, wait)
149 // The timer must not keep the process alive.
150 timer.unref?.()
151 }
152 const stop = () => {
153 clearTimeout(timer)
154 timer = undefined
155 }
156 return { push, flush, stop }
157}
158
159/** The jobs of one session: the ones that run, and how many started. */
160interface Jobs {
161 started: number
162 running: Set<{ kill: () => void }>
163}
164
165/**
166 * The jobs of each session, by its signal. A session signal outlives a
167 * reload, so the jobs from before a reload are still found, killed, and
168 * counted. Each signal gets one abort listener, not one for each setup.
169 */
170const sessionJobs = new WeakMap<AbortSignal, Jobs>()
171
172/** The jobs of the session of `signal`. Without it, new jobs of their own. */
173function jobsOf(signal: AbortSignal | undefined) {
174 const known = signal && sessionJobs.get(signal)
175 if (known) return known
176 const jobs: Jobs = { started: 0, running: new Set() }
177 if (!signal) return jobs
178 sessionJobs.set(signal, jobs)
179 signal.addEventListener(
180 'abort',
181 () => {
182 for (const job of jobs.running) job.kill()
183 },
184 { once: true },
185 )
186 return jobs
187}
188
189/**
190 * `bash`: run a shell command in the workspace folder. Every command gets
191 * `AGENT=1` in its environment. The model gets the exit code and the last
192 * part of the output. The abort signal of the run stops the command.
193 *
194 * With `background: true`, the call returns at once with a job id, and
195 * `note` tells the model when the job ends. Background jobs need
196 * `env.backend.spawn`. At most `maxJobs` run at a time in a session. They
197 * are killed when `signal` aborts. With `emit`, each job sends events:
198 * `tanstack/workspace-tools:job-started`, `tanstack/workspace-tools:job-output` (at most one each 250 ms), and
199 * `tanstack/workspace-tools:job-ended`.
200 *
201 * A command that runs in the foreground supports `detach` of the tool
202 * context, while fewer than `maxJobs` jobs run: the host can move it to the
203 * background while it runs. Then the end of the run does not stop it,
204 * `signal` kills it like a job, and `jobs` gets the id of its process in
205 * the backend, when the backend gave one.
206 */
207export function bashTools(
208 env: ToolEnv,
209 options: {
210 /** Stop the command after this many milliseconds. Default: 120,000. */
211 timeoutMs?: number
212 /**
213 * Tells the model that a background job ended. `user` is the user
214 * of the run that started the job: the turn of the note runs as that
215 * user. Without it, no one is told.
216 */
217 note?: (text: string, user: RunContext['user']) => Promise<void>
218 /**
219 * When the model gets only the end of the output, the full output is
220 * saved in this folder, and the model gets the path. Relative to the
221 * workspace, or absolute.
222 */
223 spillDir?: string
224 /**
225 * Takes the secrets of the session out of the output that `spillDir`
226 * gets. The model gets tool results that the session scrubs, so the file
227 * must not keep what the result does not.
228 */
229 scrub?: (text: string) => string
230 /** Kills the background jobs that still run, for example on plugin cleanup. */
231 signal?: AbortSignal
232 /**
233 * Told when a background job starts and ends, with the id of its
234 * process in the backend and the thread of its run. The session logs
235 * it.
236 */
237 jobs?: BackgroundJobsApi
238 /**
239 * Sends the events of the background jobs: {@link JobStarted},
240 * {@link JobOutput}, and {@link JobEnded}. Without it, there are none.
241 */
242 emit?: Emit
243 /**
244 * At most this many background jobs run at a time in the session of
245 * `signal`. One more gives a tool error. Default: 8.
246 */
247 maxJobs?: number
248 } = {},
249) {
250 const {
251 timeoutMs: defaultTimeoutMs = 120_000,
252 note,
253 spillDir,
254 scrub = (text: string) => text,
255 signal,
256 maxJobs = DEFAULT_MAX_JOBS,
257 } = options
258 // A restart cannot reach these processes. `options.jobs` lets a durable
259 // session note the jobs that a crash stopped. The ids come from the
260 // session, so a job after a reload does not reuse the id of a job that
261 // still runs.
262 const jobs = jobsOf(signal)
263
264 /** Save the full output in `dir`. Gives back the note for the model. */
265 const spill = async (dir: string, output: string) => {
266 const { join, resolve } = pathsOf(env.backend)
267 const path = join(resolve(env.root, dir), `bash-${crypto.randomUUID()}.txt`)
268 try {
269 await env.backend.writeFile(path, scrub(output))
270 return `[Full output saved to ${env.shown(path)}.]`
271 } catch (error) {
272 // The cut output is still useful, so a failed save does not fail the call.
273 return `[The full output was not saved: ${String(error)}]`
274 }
275 }
276
277 /** The exit code and the end of `output`, as the model gets them. */
278 const report = async (exitCode: number, output: string) => {
279 const bounded = boundText(output, OUTPUT_LIMITS)
280 const lines = [`exit code: ${exitCode}`, bounded.text]
281 if (bounded.truncated && spillDir !== undefined) {
282 lines.push(await spill(spillDir, output))
283 }
284 return lines.join('\n')
285 }
286
287 /**
288 * Start `command` in the background, for `run`. `note` tells the model
289 * when it ends, in a turn of the user of `run`.
290 */
291 const startJob = async (
292 command: string,
293 cwd: string,
294 run: RunContext | undefined,
295 ) => {
296 const threadId = run?.threadId
297 if (!env.backend.spawn) {
298 throw new Error('This workspace cannot run commands in the background.')
299 }
300 if (signal?.aborted) throw new Error('The session is closed.')
301 if (jobs.running.size >= maxJobs) {
302 throw new Error(
303 `${jobs.running.size} background jobs run already, and the limit is ${maxJobs}. Wait until a job ends, then start this one.`,
304 )
305 }
306 const { emit } = options
307 // The output can come before `spawn` returns, so the id is made first.
308 const jobId = `bash-${jobs.started + 1}`
309 const events = emit && outputEvents(jobId, emit)
310 const job = env.backend.spawn(command, {
311 cwd,
312 env: AGENT_ENV,
313 ...(events ? { onOutput: events.push } : {}),
314 })
315 jobs.started += 1
316 jobs.running.add(job)
317 emit?.(JobStarted, { jobId, command })
318 // The log gets the start before the end: `tell` starts after it.
319 const backendId = await job.jobId
320 options.jobs?.started({
321 jobId,
322 label: command,
323 ...(backendId !== undefined ? { backendId } : {}),
324 ...(threadId !== undefined ? { threadId } : {}),
325 })
326 const tell = async () => {
327 // A job that fails to wait gives its place back too.
328 const { exitCode } = await job
329 .wait()
330 .catch((error: unknown) => {
331 events?.stop()
332 throw error
333 })
334 .finally(() => jobs.running.delete(job))
335 // A closed session keeps the job as running in the log, so the next
336 // host tells the model that it stopped. No one gets its events now.
337 if (signal?.aborted) {
338 events?.stop()
339 return
340 }
341 events?.flush()
342 emit?.(JobEnded, { jobId, exitCode })
343 try {
344 if (note === undefined) return
345 const result = await report(exitCode, job.output())
346 await note(`Background job ${jobId} ended.\n${result}`, run?.user)
347 } finally {
348 options.jobs?.ended({
349 jobId,
350 ...(threadId !== undefined ? { threadId } : {}),
351 })
352 }
353 }
354 // No one waits for the job, so a failed note must not crash the process.
355 tell().catch(() => undefined)
356 return { jobId, status: 'started' }
357 }
358
359 return [
360 toolDefinition({
361 name: 'bash',
362 description:
363 'Run a shell command in the workspace folder. You get the exit code and the last 1000 lines (20 KiB) of the output. For a command that runs long, like a dev server, set background to true: the call returns at once, and you get a note when the command ends.',
364 inputSchema: {
365 type: 'object',
366 properties: {
367 command: { type: 'string' },
368 timeoutMs: {
369 type: 'number',
370 description:
371 'Stop the command after this many milliseconds. At most 600000.',
372 },
373 background: {
374 type: 'boolean',
375 description: 'Run the command in the background.',
376 },
377 },
378 required: ['command'],
379 },
380 replay: 'never',
381 }).server(async (args: unknown, context) => {
382 const command = stringArg(args, 'command')
383 // The shell runs in the working folder, so it must be in the workspace.
384 const cwd = await env.reach('.', 'bash', 'folder')
385 if (isRecord(args) && args.background === true) {
386 return startJob(command, cwd, runOf(context))
387 }
388 const requested = isRecord(args) ? args.timeoutMs : undefined
389 // A timeout of 0 would mean no timeout, so it gets the default.
390 const isTimeout = typeof requested === 'number' && requested > 0
391 // The run stops the command while it runs in the foreground.
392 const stop = new AbortController()
393 const runSignal = context?.abortSignal
394 const onRunAbort = () => stop.abort()
395 runSignal?.addEventListener('abort', onRunAbort, { once: true })
396 if (runSignal?.aborted) stop.abort()
397 const job = { kill: () => stop.abort() }
398 let isDone = false
399 // The id of the process, so a later host can stop a moved command.
400 let backendId: string | undefined
401 const work = env.backend
402 .exec(command, {
403 cwd,
404 env: AGENT_ENV,
405 timeoutMs: isTimeout
406 ? Math.min(requested, MAX_TIMEOUT_MS)
407 : defaultTimeoutMs,
408 signal: stop.signal,
409 onStart: (id) => {
410 backendId = id
411 },
412 })
413 .finally(() => {
414 isDone = true
415 runSignal?.removeEventListener('abort', onRunAbort)
416 jobs.running.delete(job)
417 })
418 .then(({ exitCode, stdout, stderr }) =>
419 report(exitCode, `${stdout}${stderr ? `\nstderr:\n${stderr}` : ''}`),
420 )
421 // The host can move the command to the background. The timeout still
422 // applies to it. A moved command is a job, so only under the limit.
423 // ponytail: the limit is checked at the start. Jobs that start before
424 // the move can go over it by the moved commands.
425 const detach = jobs.running.size < maxJobs ? context?.detach : undefined
426 if (!detach) return work
427 const moved = detach(work).then((text) => {
428 // The run can end now, and the command goes on as a job of the
429 // session. The session signal kills it, not the run.
430 runSignal?.removeEventListener('abort', onRunAbort)
431 const jobId = context?.toolCallId
432 if (!isDone) {
433 jobs.running.add(job)
434 // The session logged the move. Add the backend id, so a later
435 // host can report and stop the command.
436 if (jobId !== undefined && backendId !== undefined) {
437 const { threadId } = context ?? {}
438 options.jobs?.started({
439 jobId,
440 backendId,
441 label: command,
442 ...(threadId !== undefined ? { threadId } : {}),
443 })
444 }
445 }
446 // The session closed already, so its listener does not run again.
447 if (signal?.aborted) job.kill()
448 return text
449 })
450 return Promise.race([work, moved])
451 }),
452 ]
453}