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

runner.ts

443 lines17.7 KB

1/**
2 * The reusable "run an agent CLI inside a sandbox and stream its events out"
3 * primitive. Harness adapters (claude-code, codex, …) spawn their CLI via the
4 * uniform {@link SandboxHandle} and consume newline-delimited JSON from stdout,
5 * which they then translate into AG-UI StreamChunks.
6 *
7 * This is intentionally transport-minimal: a stdout NDJSON pipe. Multi-client
8 * reconnect / replay belongs to the persistence/EventLog layer, not here.
9 *
10 * The `journal` option adds a second, opt-in transport: instead of holding the
11 * agent's stdout pipe directly, the host redirects it into an append-only file
12 * inside the sandbox and tails that file. See `journal.ts` for why (host death
13 * cannot SIGPIPE the agent, and a later host can resume the same file from byte
14 * 0). `spawnNdjson`'s signature and unjournaled behavior are unchanged; every
15 * existing caller keeps working exactly as before.
16 */
17import {
18 journalCleanupCommand,
19 journalPaths,
20 journalStderrReadCommand,
21 journaledCommand,
22 parseExitSentinel,
23} from './journal'
24import { readJournal } from './journal-reader'
25import { decodeBase64Stream } from './journal-bytes'
26import { awaitAttachableJournal } from './attach-preflight'
27import type { JournalPaths } from './journal'
28import type { ProcessOptions, SandboxHandle } from './contracts'
29import type { RunStore } from '@tanstack/ai'
30​
31export interface SpawnNdjsonOptions extends ProcessOptions {
32 /**
33 * Called for each raw stdout line that is non-empty but fails JSON parsing
34 * (e.g. a CLI banner). Defaults to ignoring it. Stderr is never parsed.
35 */
36 onNonJsonLine?: (line: string) => void
37 /**
38 * Written to the process stdin (then stdin is closed) right after spawn —
39 * e.g. the agent prompt for `claude -p`. Avoids putting the prompt in argv.
40 */
41 input?: string
42 /**
43 * Route the agent's stdout through an in-sandbox journal rather than holding
44 * its pipe directly.
45 *
46 * This is what makes a run survive host death: with nothing piped, there is
47 * no reader whose disappearance can SIGPIPE the agent, and a later host reads
48 * the same file from byte 0. Opt-in so every existing caller (and every
49 * existing test) is unaffected.
50 */
51 journal?: JournalOptions
53​
54/** Journaling configuration for {@link spawnNdjson}. */
55export interface JournalOptions {
56 /** Run id the journal path is derived from. Must match across hosts. */
57 runId: string
58 /** Journal directory. Defaults to `/tmp/tanstack-runs`. */
59 dir?: string
60 /**
61 * Read an EXISTING journal instead of starting the agent. The read still
62 * begins at byte 0 — the alignment step, not the reader, decides what has
63 * already been delivered.
64 */
65 attach?: boolean
66 /** Poll interval for providers that cannot follow. */
67 pollIntervalMs?: number
68 /**
69 * Run record store, consulted ONLY on an attach and only when the journal is
70 * absent, to tell "not written yet" from "will never be written" (see
71 * `attach-preflight.ts`). Optional so an attach with no store wired keeps the
72 * bounded wait while losing the unknown/terminal classification.
73 */
74 runs?: RunStore
75 /**
76 * Bounded wait for a live run's journal to appear on an attach, AND — on every
77 * path, attach or fresh — the bound on the read's first byte
78 * (`ReadJournalOptions.firstByteTimeoutMs`). One knob for both because they
79 * bound the same question from two sides: the preflight covers "the file does
80 * not exist", the read covers "the file exists but nothing is writing to it",
81 * and a caller that widens one always means to widen the other.
82 *
83 * Defaults to `DEFAULT_ATTACH_JOURNAL_WAIT_MS`.
84 */
85 attachWaitMs?: number
87​
88type JournaledOptions = SpawnNdjsonOptions & { journal: JournalOptions }
89​
90function isJournaled(options: SpawnNdjsonOptions): options is JournaledOptions {
91 return options.journal !== undefined
93​
94function resolvePaths(options: JournaledOptions) {
95 return journalPaths(options.journal.runId, options.journal.dir)
97​
98/**
99 * Strip the runner-only options, leaving what `handle.process.spawn` accepts.
100 *
101 * `signal` is deliberately KEPT: on the UNJOURNALED path the host holds the
102 * agent's stdout pipe, so a client disconnect should take the process down with
103 * it. The journaled path must not forward it — see
104 * {@link toJournaledSpawnOptions}.
105 */
106function toProcessOptions(options: SpawnNdjsonOptions): ProcessOptions {
107 const { onNonJsonLine, input, journal, ...rest } = options
108 void onNonJsonLine
109 void input
110 void journal
111 return rest
113​
114/**
115 * The journaled agent's spawn options: {@link toProcessOptions} MINUS `signal`.
116 *
117 * The request's signal must never reach the agent process on this path. Providers
118 * DO act on it at spawn time — local-process registers it to `killTree` the
119 * process group, and daytona and docker honor it too — so forwarding it means a
120 * client disconnect kills the journaled agent. The agent then writes no exit
121 * sentinel, and a successor host takes over a run that is already dead: the exact
122 * opposite of the guarantee documented on {@link startJournaledAgent}, and of the
123 * reason the journal is a file rather than a pipe.
124 *
125 * The signal is still honored for the READ. `readJournalNdjson` forwards it to
126 * `readJournal` and `awaitAttachableJournal` on its own, so a disconnecting
127 * client stops tailing immediately. Only the agent spawn outlives the request.
128 */
129function toJournaledSpawnOptions(options: JournaledOptions): ProcessOptions {
130 const { signal, ...rest } = toProcessOptions(options)
131 void signal
132 return rest
134​
135/** Split a stream of arbitrary string chunks into complete lines. */
136export async function* toLines(
137 chunks: AsyncIterable<string>,
138): AsyncIterable<string> {
139 let buffer = ''
140 for await (const chunk of chunks) {
141 buffer += chunk
142 let newlineIndex = buffer.indexOf('\n')
143 while (newlineIndex !== -1) {
144 const line = buffer.slice(0, newlineIndex)
145 buffer = buffer.slice(newlineIndex + 1)
146 yield line
147 newlineIndex = buffer.indexOf('\n')
148 }
149 }
150 if (buffer.length > 0) yield buffer
152​
153/**
154 * Start the agent with its stdout (and the `{"__exit":N}` sentinel) redirected
155 * into the journal, then return.
156 *
157 * Deliberately does NOT wait for the process and does NOT read its stdout: the
158 * whole point of journaling is that the host holds no handle on the agent's
159 * output, so a host that dies mid-run cannot take the agent down with it (no
160 * pipe to SIGPIPE). The spawned process is left running in the sandbox; the
161 * sentinel line the wrapper appends on exit is how anyone — this host or a
162 * successor — learns it finished. Stdin is still written directly to the
163 * spawned process, exactly as the unjournaled path does, since that transport
164 * is unaffected by where stdout goes.
165 */
166export async function startJournaledAgent(
167 handle: SandboxHandle,
168 command: string,
169 options: JournaledOptions,
170): Promise<void> {
171 const paths = resolvePaths(options)
172 const proc = await handle.process.spawn(
173 journaledCommand(command, paths),
174 toJournaledSpawnOptions(options),
175 )
176 if (options.input !== undefined) {
177 await proc.stdin.write(options.input)
178 await proc.stdin.end()
179 }
181​
182/** Chars of stderr attached to a non-zero-exit error, on both paths. */
183const STDERR_ERROR_CHARS = 1000
184​
185async function* singleValue(value: string): AsyncIterable<string> {
186 yield value
188​
189/**
190 * Read the tail of a run's stderr sidecar, for the error message only.
191 *
192 * Returns `''` on ANY failure — a provider whose `exec` rejects, a sidecar that
193 * no longer exists, a base64 frame the provider truncated. The caller is on its
194 * way to throwing the real failure (the agent's non-zero exit), and losing a
195 * diagnostic suffix must never replace that error with a cleanup error. Decoding
196 * is deliberately lossy: `journalStderrReadCommand` reads the LAST N bytes, so
197 * byte 0 of the frame can sit mid-character.
198 */
199async function readStderrTail(
200 handle: SandboxHandle,
201 paths: JournalPaths,
202): Promise<string> {
203 try {
204 const result = await handle.process.exec(journalStderrReadCommand(paths))
205 const decoder = new TextDecoder()
206 let text = ''
207 for await (const bytes of decodeBase64Stream(singleValue(result.stdout))) {
208 text += decoder.decode(bytes, { stream: true })
209 }
210 text += decoder.decode()
211 return text.trim()
212 } catch {
213 return ''
214 }
216​
217/**
218 * Delete a terminal run's journal. Best effort by construction: see
219 * {@link journalCleanupCommand} for why a failure here cannot be allowed to fail
220 * a run that has already finished.
221 */
222async function cleanupJournal(
223 handle: SandboxHandle,
224 paths: JournalPaths,
225): Promise<void> {
226 try {
227 await handle.process.exec(journalCleanupCommand(paths))
228 } catch {
229 // The sandbox may already be gone, `/tmp` may be read-only, the provider's
230 // `exec` may reject. Nothing about a completed run depends on the files
231 // still existing OR on them being gone, so there is nothing to report.
232 }
234​
235/**
236 * Read a run's journal and yield each line parsed as JSON.
237 *
238 * Always reads from byte 0 — the alignment step (a later phase), not this
239 * reader, decides what a client has already seen. Stops at the `{"__exit":N}`
240 * sentinel, and throws for a non-zero N so the calling adapter's existing
241 * `catch` turns it into a `RUN_ERROR`, the same observable outcome the
242 * unjournaled path produces from a non-zero `wait()`. There is nothing to
243 * `wait()` on here: the host holds a `tail`, not the agent process, so the
244 * sentinel line IS the exit code.
245 *
246 * The sentinel is also what bounds journal growth: reaching it means the run is
247 * terminal, and a terminal run's record is the event log, so both journal files
248 * are deleted before this iterable finishes. The ordering below is load-bearing
249 * and is asserted, not merely commented:
250 *
251 * - The sentinel is captured and the loop is `break`-ed, so the source's
252 * `finally` kills the `tail` BEFORE the `rm` runs — the reader is stopped, then
253 * its input is deleted, never the other way round.
254 * - `exitCode` stays `undefined` if the journal stream ends without a sentinel.
255 * NOTHING is deleted on that path either way — the run may be mid-flight and a
256 * successor host may still need every byte — but the two causes are then
257 * separated by `options.signal.aborted`: an aborted consumer returns quietly,
258 * while a stream that died on its own (killed `tail`, destroyed sandbox, torn
259 * pipe) THROWS. Returning for both is how a truncated read used to reach the
260 * client as a normally-completing run.
261 * - A non-zero sentinel deletes too. The run is terminal either way.
262 * - The stderr sidecar is read BEFORE the deletion that destroys it, so a
263 * non-zero exit carries up to {@link STDERR_ERROR_CHARS} chars of the agent's
264 * own diagnostics, exactly as the unjournaled path below does. That closes the
265 * "Known regression" this function used to document; the read is bounded and
266 * failure-swallowing (see {@link readStderrTail}), so it cannot turn a run
267 * failure into a cleanup failure.
268 *
269 * On an ATTACH (`journal.attach === true`) the read is preceded by
270 * {@link awaitAttachableJournal}, which fails fast for a runId the store does not
271 * know or has already terminalized and otherwise waits a BOUNDED time for a live
272 * run's journal to appear. Without it, an attach to a runId with no journal
273 * created an empty one (`journalFollowCommand` does that deliberately) and tailed
274 * it forever — no sentinel, no error, no timeout.
275 *
276 * One case this does NOT bound: a run that reaches its sentinel while DETACHED
277 * has no host reading it, so nothing observes the sentinel and nothing here
278 * runs. Sweeping those is `pruneJournals`' job (`journal-sweep.ts`): it consults
279 * the run store's status for each journal it finds and deletes only the terminal
280 * ones, from a cron the application schedules rather than from a run.
281 */
282export async function* readJournalNdjson(
283 handle: SandboxHandle,
284 options: JournaledOptions,
285): AsyncIterable<unknown> {
286 const paths = resolvePaths(options)
287 // ATTACH ONLY, and before the first read. `journalFollowCommand` CREATES the
288 // journal it tails, so an attach for a runId that never had one would
289 // otherwise create an empty file and tail it forever with no sentinel ever
290 // arriving. A fresh run must not be gated: its journal is created by its own
291 // `journaledCommand` spawn, which `spawnNdjson` has just issued.
292 if (options.journal.attach === true) {
293 await awaitAttachableJournal(handle, {
294 paths,
295 runId: options.journal.runId,
296 ...(options.journal.runs === undefined
297 ? {}
298 : { runs: options.journal.runs }),
299 ...(options.journal.attachWaitMs === undefined
300 ? {}
301 : { waitMs: options.journal.attachWaitMs }),
302 ...(options.signal === undefined ? {} : { signal: options.signal }),
303 })
304 }
305 let exitCode: number | undefined
306 for await (const { line } of readJournal(handle, {
307 paths,
308 fromByte: 0,
309 runId: options.journal.runId,
310 ...(options.signal === undefined ? {} : { signal: options.signal }),
311 ...(options.journal.pollIntervalMs === undefined
312 ? {}
313 : { pollIntervalMs: options.journal.pollIntervalMs }),
314 ...(options.journal.attachWaitMs === undefined
315 ? {}
316 : { firstByteTimeoutMs: options.journal.attachWaitMs }),
317 })) {
318 const trimmed = line.trim()
319 if (trimmed === '') continue
320 // The sentinel test comes FIRST and is nonce-checked, so an agent line that
321 // merely looks like a sentinel is delivered as the event it is instead of
322 // truncating the run (see `parseExitSentinel`).
323 const sentinel = parseExitSentinel(trimmed, paths)
324 if (sentinel !== null) {
325 exitCode = sentinel
326 break
327 }
328 let parsed: unknown
329 try {
330 parsed = JSON.parse(trimmed)
331 } catch {
332 options.onNonJsonLine?.(trimmed)
333 continue
334 }
335 yield parsed
336 }
337​
338 // The stream ended with no sentinel. Two very different causes share this
339 // shape, and collapsing them is how a torn-down read used to be recorded as a
340 // short but SUCCESSFUL run:
341 //
342 // - The CONSUMER aborted (lease lost, client gone, host shutting down). Not a
343 // failure and not terminal: return, having deleted nothing, because a
344 // successor host may still need every byte. `pipeToRunLog`'s post-loop check
345 // turns this into `'aborted'`.
346 // - The read DIED (the `tail` was killed, the sandbox was destroyed, the pipe
347 // was torn down). The iterable ends without an error, so returning here made
348 // the adapter emit a normally-completing but silently TRUNCATED run — in a
349 // function whose documented job is to throw so the adapter converts it to a
350 // `RUN_ERROR`. `signal.aborted` is what tells the two apart, and the throw
351 // matches the shape the unjournaled path already uses for a bad exit.
352 if (exitCode === undefined) {
353 if (options.signal?.aborted === true) return
354 throw new Error(
355 `Agent journal stream for run ${options.journal.runId} ended without an exit sentinel ` +
356 `(${paths.journal}). The run was NOT observed to finish: the tail was torn down, ` +
357 `the sandbox went away, or the agent's shell died before writing its sentinel. ` +
358 `Both journal files are left in place for a successor host.`,
359 )
360 }
361​
362 const stderr = exitCode === 0 ? '' : await readStderrTail(handle, paths)
363 await cleanupJournal(handle, paths)
364 if (exitCode !== 0) {
365 throw new Error(
366 `Agent process exited with code ${exitCode}` +
367 (stderr ? `: ${stderr.slice(0, STDERR_ERROR_CHARS)}` : ''),
368 )
369 }
371​
372/**
373 * Spawn `command` in the sandbox and yield each stdout line parsed as JSON.
374 *
375 * Without `options.journal`, behavior is byte-identical to before: resolves
376 * the spawn handle's exit via `wait()` after stdout closes; a non-zero exit
377 * with no events surfaced is the adapter's concern to detect.
378 *
379 * With `options.journal`, the agent's stdout is redirected into an in-sandbox
380 * journal (unless `journal.attach` is set, meaning a run already in flight)
381 * and then read back from byte 0 — one code path for a fresh run and an
382 * attach, both going through {@link readJournalNdjson}.
383 */
384export async function* spawnNdjson(
385 handle: SandboxHandle,
386 command: string,
387 options: SpawnNdjsonOptions = {},
388): AsyncIterable<unknown> {
389 if (isJournaled(options)) {
390 if (options.journal.attach !== true) {
391 await startJournaledAgent(handle, command, options)
392 }
393 yield* readJournalNdjson(handle, options)
394 return
395 }
396​
397 const { onNonJsonLine, input, ...processOptions } = options
398 const proc = await handle.process.spawn(command, processOptions)
399​
400 if (input !== undefined) {
401 await proc.stdin.write(input)
402 await proc.stdin.end()
403 }
404​
405 // Drain stderr concurrently. A CLI that fails before producing stdout (a
406 // broken install, an auth/permission refusal, …) prints to stderr and exits
407 // non-zero; without this, stdout-only parsing yields nothing and the failure
408 // vanishes. Capturing it lets us surface the cause below.
409 const stderrChunks: Array<string> = []
410 const stderrDrained = (async () => {
411 try {
412 for await (const chunk of proc.stderr) stderrChunks.push(chunk)
413 } catch {
414 // stderr stream torn down — use whatever was captured
415 }
416 })()
417​
418 for await (const line of toLines(proc.stdout)) {
419 const trimmed = line.trim()
420 if (trimmed === '') continue
421 let parsed: unknown
422 try {
423 parsed = JSON.parse(trimmed)
424 } catch {
425 onNonJsonLine?.(trimmed)
426 continue
427 }
428 yield parsed
429 }
430​
431 const exitCode = await proc.wait()
432 await stderrDrained
433 // A non-zero exit means the agent CLI itself failed. Throw so the adapter's
434 // catch turns it into a RUN_ERROR the UI can show, instead of ending the
435 // stream silently with no events.
436 if (exitCode !== 0) {
437 const stderr = stderrChunks.join('').trim()
438 throw new Error(
439 `Agent process exited with code ${exitCode}` +
440 (stderr ? `: ${stderr.slice(0, STDERR_ERROR_CHARS)}` : ''),
441 )
442 }