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

durability.ts

309 lines14.3 KB

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
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
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 }
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()
166​
167/**
168 * An ATTACH was driven into a code path that can never replay a run.
169 *
170 * The sibling of {@link DurableRunIdRequiredError} that is not about a
171 * missing id: here every id is present and the path itself is the problem.
172 *
173 * `sandboxRunDriver`'s `drive()` re-invokes `chat()` with `attach: true`. On a
174 * JOURNALING path that is genuinely a replay — `spawnNdjson` tails the journal
175 * the previous host wrote, `awaitAttachableJournal` refuses a hopeless attach up
176 * front, and `alignedIfAttaching` suppresses the prefix already delivered. A
177 * protocol path with none of those three has no journal to tail and nothing to
178 * align against, so `attach: true` does not resume anything: it starts the agent
179 * over from scratch against the workspace the first attempt already mutated, and
180 * appends its entire output to a log that still holds the first attempt's.
181 *
182 * Deliberately NOT a `JournalAttachUnavailableError`. That error means "a
183 * journal that should exist has not appeared yet" — retryable, scoped to a wait
184 * (`attachWaitMs`). This condition is categorically different: the path cannot
185 * attach AT ALL, so telling a caller to wait would point it at something that is
186 * never coming. A 5xx/501-shaped refusal, not a 504.
187 *
188 * `reason` names the missing capability in the adapter's own vocabulary (which
189 * protocol, which spawn path), because the fix is always to change how the run
190 * is spawned or routed, never to retry.
191 */
192export class DurableAttachNotSupportedError extends Error {
193 constructor(
194 readonly adapter: string,
195 readonly reason: string,
196 ) {
197 super(
198 `${adapter}: this code path cannot ATTACH to an existing durable run (${reason}). ` +
199 `It does not journal, so there is no stored output to replay and no alignment to suppress what was already delivered. ` +
200 `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. ` +
201 `Route the attach through a journaling spawn path, or drop \`runs\`/\`durability\` from withSandbox(...) so the run is never resumed in the first place. ` +
202 `This is not a transient condition — unlike \`JournalAttachUnavailableError\`, waiting and retrying can never make it succeed.`,
203 )
204 this.name = 'DurableAttachNotSupportedError'
205 }
207​
208/**
209 * Resolve `withSandbox`'s two durability options into the capability payload, or
210 * `undefined` when the app has not opted in.
211 *
212 * BOTH `runs` and `durability` are required. A half-configured app gets
213 * `undefined` **silently** rather than a warning: it has not asked for
214 * durability, so there is nothing to warn about, and the resulting behavior
215 * (destroy on disconnect, no journal) is exactly today's.
216 */
217export function resolveSandboxDurability<TOffset extends string = string>(
218 options:
219 | { runs?: RunStore; durability?: SandboxDurabilityOptions<TOffset> }
220 | undefined,
221): SandboxRunDurability | undefined {
222 const runs = options?.runs
223 const durability = options?.durability
224 if (runs === undefined || durability === undefined) return undefined
225 return {
226 runs,
227 adapter: durability.adapter,
228 journalDir: durability.journal ?? DEFAULT_JOURNAL_DIR,
229 attach: durability.attach === true,
230 detachOnDisconnect: durability.detachOnDisconnect !== false,
231 ...(durability.pollIntervalMs === undefined
232 ? {}
233 : { pollIntervalMs: durability.pollIntervalMs }),
234 ...(durability.attachWaitMs === undefined
235 ? {}
236 : { attachWaitMs: durability.attachWaitMs }),
237 }
239​
240/**
241 * Build the `spawnNdjson` journal option for a run, or `undefined` when the run
242 * is not durable — in which case `spawnNdjson` takes its original, unjournaled
243 * path (`isJournaled` tests `options.journal !== undefined`, `runner.ts:70-72`)
244 * and behavior is byte-identical to a pre-durability run.
245 *
246 * `JournalOptions.dir` is optional, but this always supplies it: the resolved
247 * durability has already defaulted `journalDir`, and a successor host must
248 * recompute the same path rather than re-derive the default independently.
249 *
250 * `runs` and `attachWaitMs` are carried ONLY when attaching, and that is not a
251 * micro-optimization: they exist for `awaitAttachableJournal`, which the reader
252 * runs on the attach path alone. A fresh run has no journal yet BY DESIGN (its own
253 * `journaledCommand` spawn creates it moments later), so handing it a run store
254 * would only invite a future change to gate a path where absence proves nothing.
255 */
256export function journalOptionsFor(
257 durability: SandboxRunDurability | undefined,
258 runId: string,
259): JournalOptions | undefined {
260 if (durability === undefined) return undefined
261 return {
262 runId,
263 dir: durability.journalDir,
264 attach: durability.attach,
265 ...(durability.pollIntervalMs === undefined
266 ? {}
267 : { pollIntervalMs: durability.pollIntervalMs }),
268 ...(durability.attach
269 ? {
270 runs: durability.runs,
271 ...(durability.attachWaitMs === undefined
272 ? {}
273 : { attachWaitMs: durability.attachWaitMs }),
274 }
275 : {}),
276 }
278​
279/**
280 * Align a harness stream against the run's stored log — but ONLY on an attach.
281 *
282 * The `attach` guard is not an optimization, it is a CORRECTNESS requirement.
283 * `alignToStoredLog` snapshots the log before the first chunk is pulled and
284 * treats everything in that snapshot as "already delivered". On a FRESH run that
285 * premise is false: if such a run were aligned against a log that already holds
286 * entries — a `runId` collision, a retried request — its own chunks would be
287 * matched against those entries and silently SUPPRESSED instead of delivered,
288 * which is silent data loss rather than a slow path. Aligning only when
289 * re-entering an existing run keeps the transform's premise ("this stream is a
290 * replay of what is already stored") actually true.
291 *
292 * `isBridgeCustomChunk` is passed because the stored log holds the previous
293 * host's MERGED output, including live bridged-tool CUSTOM events that a replay
294 * cannot reproduce; without it a bridged-tool run could not be taken over at
295 * all. Wrap the merge RESULT, never the pre-merge translator, or the comparison
296 * is against a stream the log never contained.
297 */
298export function alignedIfAttaching(
299 chunks: AsyncIterable<StreamChunk>,
300 durability: SandboxRunDurability | undefined,
301 logger?: InternalLogger,
302): AsyncIterable<StreamChunk> {
303 if (durability === undefined || !durability.attach) return chunks
304 return alignToStoredLog(chunks, {
305 durability: durability.adapter,
306 isOutOfBand: isBridgeCustomChunk,
307 ...(logger === undefined ? {} : { logger }),
308 })