Open History to see the last commit
1/**
2 * The durability seam for a sandboxed run: the option shape `withSandbox` takes,
3 * the capability harness adapters read, and the two guards that keep a
4 * "durable" run actually recoverable.
5 *
6 * A run is durable only when BOTH a `RunStore` and a `StreamDurability` are
7 * wired, because either alone is useless: a record with no event log cannot be
8 * replayed, and a log with no record cannot be found, claimed, or reaped. So the
9 * capability exists or it does not — there is no half-configured state, and
10 * every existing app (which wires neither) keeps today's behavior untouched.
11 */
12import { createCapability } from '@tanstack/ai'
13import { DEFAULT_JOURNAL_DIR } from './journal'
14import { alignToStoredLog, isBridgeCustomChunk } from './align'
15import type { JournalOptions } from './runner'
16import type { InternalLogger } from '@tanstack/ai/adapter-internals'
17import type { RunStore, StreamChunk, StreamDurability } from '@tanstack/ai'
18
19/** `withSandbox(sandbox, { durability })`. */
20export interface SandboxDurabilityOptions<TOffset extends string = string> {
21 /**
22 * Delivery-durable event log for the run. Same key and shape as the
23 * transport's `durability.adapter`, so one adapter instance can be handed to
24 * both `withSandbox` and `toServerSentEventsResponse`.
25 *
26 * Generic in the offset type, defaulted to `string`, for the same reason
27 * {@link SandboxRunDriverOptions} and {@link ReapOptions} are:
28 * `StreamDurability` is INVARIANT in `TOffset` (`read` takes an offset in),
29 * so a backend that brands its cursors — `@tanstack/ai-durable-stream`'s
30 * `durableStream`, the multi-host production backend the sandbox docs point
31 * at — is not assignable to `StreamDurability<string>`. Without the parameter
32 * the resume route could be wired with it and the route that STARTS the run
33 * could not.
34 */
35 adapter: StreamDurability<TOffset>
36 /** Journal directory inside the sandbox. Defaults to `/tmp/tanstack-runs`. */
37 journal?: string
38 /**
39 * Whether a client disconnect DETACHES (leave the agent running) instead of
40 * destroying the sandbox. Defaults to `true` whenever durability is wired,
41 * because that is the whole point of wiring it.
42 *
43 * Set `false` to keep today's destroy-on-disconnect cost profile while still
44 * getting resumable DELIVERY (a reload replays the log). An explicit cancel
45 * destroys either way.
46 */
47 detachOnDisconnect?: boolean
48 /**
49 * Read an EXISTING run's journal instead of starting a new agent. Set by the
50 * attach route's `drive()` callback, never by an application's POST handler.
51 *
52 * This is where `attach` lives, and deliberately NOT on `chat()`: `chat()` is
53 * core and must not gain sandbox vocabulary, and the provider options are
54 * per-model type state, not per-request lifecycle.
55 */
56 attach?: boolean
57 /** Journal poll interval for providers that cannot follow. */
58 pollIntervalMs?: number
59 /**
60 * How long an ATTACH waits for a live run's journal to appear before failing
61 * with a `JournalAttachUnavailableError`. Defaults to
62 * `DEFAULT_ATTACH_JOURNAL_WAIT_MS` (10s). Only the wait is configurable: an
63 * unknown or terminal runId fails immediately regardless, since no amount of
64 * waiting changes either verdict.
65 */
66 attachWaitMs?: number
67}
68
69/**
70 * The view of a caller's event log that the capability bus carries.
71 *
72 * Deliberately NOT the whole `StreamDurability`. `read` is the only member that
73 * takes an offset *in*, which is what makes `StreamDurability` invariant in
74 * `TOffset` and a branded-cursor backend unassignable to
75 * `StreamDurability<string>`. Every other member mentions the offset only in a
76 * return position, so this type is a genuine SUPERTYPE of
77 * `StreamDurability<TOffset>` for every `TOffset extends string` — which is the
78 * one property that lets a single concrete capability instantiation accept a
79 * branded backend. `createCapability<T>()` forces exactly one instantiation
80 * (the value type is a plain type argument, and TypeScript has no higher-kinded
81 * types), so the payload cannot be parameterized the way the *option* above is.
82 *
83 * Dropping `read` costs nothing, and that is a property of the seam rather than
84 * luck: the bus is the JOURNAL/ALIGNMENT seam, and alignment reads the stored
85 * prefix through `snapshot()` — never `read()`, which tails an open log forever
86 * (see `alignToStoredLog`). Replay *by offset* belongs to the delivery seam,
87 * and that seam (`toServerSentEventsResponse`, `sandboxRunDriver`) receives the
88 * application's own adapter directly, with its brand intact.
89 */
90export type SandboxDurabilityLog = Omit<StreamDurability, 'read'>
91
92/**
93 * Resolved durability, published on the capability bus by `withSandbox`.
94 *
95 * Deliberately carries NO detached-run TTL. The only actor that enforces one is
96 * `reapDetachedRuns`, which runs from a cron with no chat in flight — so it has
97 * no `CapabilityContext` and cannot read this bus at all. A TTL published here
98 * could therefore only ever be read by nobody, while the sweep took its own
99 * `ReapOptions.detachedRunTtlMs`; the two would silently disagree. The reaper's
100 * required option is the single source of truth.
101 */
102export interface SandboxRunDurability {
103 runs: RunStore
104 adapter: SandboxDurabilityLog
105 journalDir: string
106 attach: boolean
107 detachOnDisconnect: boolean
108 pollIntervalMs?: number
109 attachWaitMs?: number
110}
111
112/**
113 * Provided by `withSandbox` only when a run is genuinely durable (both stores
114 * wired). Harness adapters read it with `getOptional` and treat its absence as
115 * "no journaling contract to honour", which is exactly today's behavior.
116 */
117export const SandboxDurabilityCapability =
118 createCapability<SandboxRunDurability>()('sandbox-durability')
119
120/** Destructured accessors, matching `./capabilities`. */
121export const [getSandboxDurability, provideSandboxDurability] =
122 SandboxDurabilityCapability
123
124/**
125 * A durable run was started without a caller-supplied `runId`.
126 *
127 * Thrown rather than defaulted because the failure is otherwise INVISIBLE: an
128 * adapter-generated id (`${name}-${Date.now()}-${Math.random()...}`) produces a
129 * journal path at `/tmp/tanstack-runs/<id>.ndjson` that no successor host can
130 * recompute, so the run streams normally, records normally, and is silently
131 * unrecoverable. A loud failure at the start of `chatStream` is strictly better
132 * than a run that only reveals itself as non-durable during an incident.
133 */
134export class DurableRunIdRequiredError extends Error {
135 constructor(readonly adapter: string) {
136 super(
137 `${adapter}: a durable sandboxed run requires a caller-supplied \`runId\`. ` +
138 `The journal path and the deterministic message-id generator are both derived from it, ` +
139 `so a successor host can only resume a run whose \`runId\` it can recompute. ` +
140 `Pass \`runId\` to chat({ ... }), or drop \`runs\`/\`durability\` from withSandbox(...) to run non-durably.`,
141 )
142 this.name = 'DurableRunIdRequiredError'
143 }
144}
145
146/**
147 * Resolve the `runId` a harness adapter will journal under.
148 *
149 * Replaces the bare `options.runId ?? this.generateId()` in every harness
150 * adapter. The fallback is preserved for non-durable runs — several `chat()`
151 * paths pass `runId` as a conditional spread, so `undefined` is reachable and
152 * removing the fallback would break them for no benefit.
153 *
154 * The `durable` check runs BEFORE `fallback()`, and that ordering is load
155 * bearing: a generated id must never be minted for a durable run, not even one
156 * that is discarded, because the whole point is that no such id can exist.
157 */
158export function resolveDurableRunId(
159 runId: string | undefined,
160 options: { durable: boolean; adapter: string; fallback: () => string },
161): string {
162 if (runId !== undefined && runId.length > 0) return runId
163 if (options.durable) throw new DurableRunIdRequiredError(options.adapter)
164 return options.fallback()
165}
166
167/**
168 * An ATTACHING durable run was driven without the run record's `threadId`.
169 *
170 * The sibling of {@link DurableRunIdRequiredError}, for the other id an attach
171 * cannot mint for itself. `threadId` lands in EVERY chunk a harness adapter
172 * emits (see each package's `stream/translate.ts`), so a replay that generates a
173 * fresh one produces a stream that differs from the stored log in its very first
174 * chunk. `alignToStoredLog` then fails at index 0 with a
175 * `JournalReplayThreadIdMismatchError` — mid-stream, after the takeover has
176 * already claimed the run. Refusing up front is strictly better, and mirrors
177 * what `resolveDurableRunId` does for an id whose absence is equally fatal.
178 *
179 * Core already does its part: `startRunDriver` reads the record and hands
180 * `active.threadId` to `drive({ runId, threadId, signal })`. This error exists
181 * for the one gap it cannot close — application `drive` code that forgets to
182 * forward it into `chat()`.
183 */
184export class DurableThreadIdRequiredError extends Error {
185 constructor(readonly adapter: string) {
186 super(
187 `${adapter}: an ATTACHING durable sandboxed run requires the run record's \`threadId\`. ` +
188 `Every emitted chunk carries \`threadId\`, so an attach that generates a fresh one replays a stream whose first chunk ` +
189 `already differs from the stored log, and alignment fails at index 0 (\`JournalReplayThreadIdMismatchError\`) even though ` +
190 `the agent behaved identically. Forward the run record's \`threadId\` — the one \`sandboxRunDriver\` passes to ` +
191 `\`drive({ runId, threadId, signal })\` — into \`chat({ ... })\` on the attach route. ` +
192 `A durable FRESH run needs none: that run is what establishes the \`threadId\`.`,
193 )
194 this.name = 'DurableThreadIdRequiredError'
195 }
196}
197
198/**
199 * Resolve the `threadId` a harness adapter will stamp on every chunk.
200 *
201 * Replaces the bare `options.threadId ?? this.generateId()` in the journaling
202 * harness adapters. Only the durable-AND-attaching quadrant throws; the other
203 * three keep the generated fallback and are byte-identical to before:
204 *
205 * | durable | attaching | behavior |
206 * | ------- | --------- | --------------------------------------------------- |
207 * | no | no | fallback — a plain non-durable run |
208 * | no | yes | fallback — not reachable today, and harmless anyway |
209 * | yes | no | fallback — the FRESH run that ESTABLISHES the id |
210 * | yes | yes | throw {@link DurableThreadIdRequiredError} |
211 *
212 * The durable-fresh row is the load-bearing one. A fresh durable run legitimately
213 * mints its `threadId` (there is no record to reuse one from), so throwing on
214 * `durable` alone — the obvious over-simplification — would break every durable
215 * run that has ever worked. Only re-entering an existing run has an id it MUST
216 * reuse, which is exactly the condition `attach` already expresses.
217 *
218 * As in `resolveDurableRunId`, the guard runs BEFORE `fallback()`: a generated id
219 * must never be minted on this path, not even one that is then discarded.
220 */
221export function resolveDurableThreadId(
222 threadId: string | undefined,
223 options: {
224 durable: boolean
225 attaching: boolean
226 adapter: string
227 fallback: () => string
228 },
229): string {
230 if (threadId !== undefined && threadId.length > 0) return threadId
231 if (options.durable && options.attaching) {
232 throw new DurableThreadIdRequiredError(options.adapter)
233 }
234 return options.fallback()
235}
236
237/**
238 * An ATTACH was driven into a code path that can never replay a run.
239 *
240 * The third sibling of {@link DurableRunIdRequiredError} and
241 * {@link DurableThreadIdRequiredError}, and the one that is not about a missing
242 * id: here every id is present and the path itself is the problem.
243 *
244 * `sandboxRunDriver`'s `drive()` re-invokes `chat()` with `attach: true`. On a
245 * JOURNALING path that is genuinely a replay — `spawnNdjson` tails the journal
246 * the previous host wrote, `awaitAttachableJournal` refuses a hopeless attach up
247 * front, and `alignedIfAttaching` suppresses the prefix already delivered. A
248 * protocol path with none of those three has no journal to tail and nothing to
249 * align against, so `attach: true` does not resume anything: it starts the agent
250 * over from scratch against the workspace the first attempt already mutated, and
251 * appends its entire output to a log that still holds the first attempt's.
252 *
253 * Deliberately NOT a `JournalAttachUnavailableError`. That error means "a
254 * journal that should exist has not appeared yet" — retryable, scoped to a wait
255 * (`attachWaitMs`). This condition is categorically different: the path cannot
256 * attach AT ALL, so telling a caller to wait would point it at something that is
257 * never coming. A 5xx/501-shaped refusal, not a 504.
258 *
259 * `reason` names the missing capability in the adapter's own vocabulary (which
260 * protocol, which spawn path), because the fix is always to change how the run
261 * is spawned or routed, never to retry.
262 */
263export class DurableAttachNotSupportedError extends Error {
264 constructor(
265 readonly adapter: string,
266 readonly reason: string,
267 ) {
268 super(
269 `${adapter}: this code path cannot ATTACH to an existing durable run (${reason}). ` +
270 `It does not journal, so there is no stored output to replay and no alignment to suppress what was already delivered. ` +
271 `Proceeding would re-run the agent from scratch against the workspace the previous attempt already modified, and double-append its entire output to the run log. ` +
272 `Route the attach through a journaling spawn path, or drop \`runs\`/\`durability\` from withSandbox(...) so the run is never resumed in the first place. ` +
273 `This is not a transient condition — unlike \`JournalAttachUnavailableError\`, waiting and retrying can never make it succeed.`,
274 )
275 this.name = 'DurableAttachNotSupportedError'
276 }
277}
278
279/**
280 * Resolve `withSandbox`'s two durability options into the capability payload, or
281 * `undefined` when the app has not opted in.
282 *
283 * BOTH `runs` and `durability` are required. A half-configured app gets
284 * `undefined` **silently** rather than a warning: it has not asked for
285 * durability, so there is nothing to warn about, and the resulting behavior
286 * (destroy on disconnect, no journal) is exactly today's.
287 */
288export function resolveSandboxDurability<TOffset extends string = string>(
289 options:
290 | { runs?: RunStore; durability?: SandboxDurabilityOptions<TOffset> }
291 | undefined,
292): SandboxRunDurability | undefined {
293 const runs = options?.runs
294 const durability = options?.durability
295 if (runs === undefined || durability === undefined) return undefined
296 return {
297 runs,
298 adapter: durability.adapter,
299 journalDir: durability.journal ?? DEFAULT_JOURNAL_DIR,
300 attach: durability.attach === true,
301 detachOnDisconnect: durability.detachOnDisconnect !== false,
302 ...(durability.pollIntervalMs === undefined
303 ? {}
304 : { pollIntervalMs: durability.pollIntervalMs }),
305 ...(durability.attachWaitMs === undefined
306 ? {}
307 : { attachWaitMs: durability.attachWaitMs }),
308 }
309}
310
311/**
312 * Build the `spawnNdjson` journal option for a run, or `undefined` when the run
313 * is not durable — in which case `spawnNdjson` takes its original, unjournaled
314 * path (`isJournaled` tests `options.journal !== undefined`, `runner.ts:70-72`)
315 * and behavior is byte-identical to a pre-durability run.
316 *
317 * `JournalOptions.dir` is optional, but this always supplies it: the resolved
318 * durability has already defaulted `journalDir`, and a successor host must
319 * recompute the same path rather than re-derive the default independently.
320 *
321 * `runs` and `attachWaitMs` are carried ONLY when attaching, and that is not a
322 * micro-optimization: they exist for `awaitAttachableJournal`, which the reader
323 * runs on the attach path alone. A fresh run has no journal yet BY DESIGN (its own
324 * `journaledCommand` spawn creates it moments later), so handing it a run store
325 * would only invite a future change to gate a path where absence proves nothing.
326 */
327export function journalOptionsFor(
328 durability: SandboxRunDurability | undefined,
329 runId: string,
330): JournalOptions | undefined {
331 if (durability === undefined) return undefined
332 return {
333 runId,
334 dir: durability.journalDir,
335 attach: durability.attach,
336 ...(durability.pollIntervalMs === undefined
337 ? {}
338 : { pollIntervalMs: durability.pollIntervalMs }),
339 ...(durability.attach
340 ? {
341 runs: durability.runs,
342 ...(durability.attachWaitMs === undefined
343 ? {}
344 : { attachWaitMs: durability.attachWaitMs }),
345 }
346 : {}),
347 }
348}
349
350/**
351 * Align a harness stream against the run's stored log — but ONLY on an attach.
352 *
353 * The `attach` guard is not an optimization, it is a CORRECTNESS requirement.
354 * `alignToStoredLog` snapshots the log before the first chunk is pulled and
355 * treats everything in that snapshot as "already delivered". On a FRESH run that
356 * premise is false: if such a run were aligned against a log that already holds
357 * entries — a `runId` collision, a retried request — its own chunks would be
358 * matched against those entries and silently SUPPRESSED instead of delivered,
359 * which is silent data loss rather than a slow path. Aligning only when
360 * re-entering an existing run keeps the transform's premise ("this stream is a
361 * replay of what is already stored") actually true.
362 *
363 * `isBridgeCustomChunk` is passed because the stored log holds the previous
364 * host's MERGED output, including live bridged-tool CUSTOM events that a replay
365 * cannot reproduce; without it a bridged-tool run could not be taken over at
366 * all. Wrap the merge RESULT, never the pre-merge translator, or the comparison
367 * is against a stream the log never contained.
368 */
369export function alignedIfAttaching(
370 chunks: AsyncIterable<StreamChunk>,
371 durability: SandboxRunDurability | undefined,
372 logger?: InternalLogger,
373): AsyncIterable<StreamChunk> {
374 if (durability === undefined || !durability.attach) return chunks
375 return alignToStoredLog(chunks, {
376 durability: durability.adapter,
377 isOutOfBand: isBridgeCustomChunk,
378 ...(logger === undefined ? {} : { logger }),
379 })
380}