Open History to see the last commit
1---
2title: Takeover & Detached Runs (Advanced)
3id: sandbox-takeover
4order: 13
5description: "Let a sandboxed agent run outlive the browser tab: detach on disconnect, then take the run over from another host and resume streaming where the log left off."
6keywords:
7 - detached run
8 - run takeover
9 - sandboxRunDriver
10 - detachOnDisconnect
11 - detachedRunTtlMs
12 - requestRunCancel
13 - JournalReplayDivergedError
14 - driverEpoch
15---
16
17A sandboxed coding agent can work for ten minutes. A browser tab does not last
18ten minutes. Users refresh, close the laptop, lose wifi, and hit a load balancer
19that lands the next request on a different replica.
20
21Without durability wired, the disconnect is fatal: `withSandbox`'s abort path
22destroys the sandbox on every abort, deliberately, because closing the agent's
23IO stream does **not** kill the agent process (a Docker `exec` survives its
24client), so destroying the container is the only reliable way to stop it burning
25tokens. Correct for a cancel. Ruinous for a refresh.
26
27Durable runs split those two cases apart. A disconnect **detaches**: the agent
28keeps working, the sandbox stays up, and the run record remembers that nobody is
29watching. A later request **takes the run over**, replays what was already
30delivered, and continues streaming the rest.
31
32This page is the wiring. It builds on two pages you should read first:
33[The Run Journal](./journal) (where the agent's output lives, and why it is a
34file rather than a pipe) and
35[Resumable Streams](../resumable-streams/overview) (the delivery log a client
36reconnects to).
37
38## Durability is one opt-in, not two
39
40`withSandbox` takes `runs` and `durability`. A run is durable only when **both**
41are present, because either alone is useless: a record with no event log cannot
42be replayed, and a log with no record cannot be found, claimed, or reaped. There
43is no half-configured state. Pass one and you get exactly today's behavior,
44silently and with no warning, because you have not asked for durability.
45
46Pass the **same** `RunStore` chat persistence uses, so one record describes the
47run instead of two that disagree.
48
49## Both routes must address the same backend stream
50
51Read this before the snippets. A `StreamDurability` is bound to **one run**,
52and `durableStream(request, options)` resolves which run through core's
53`resolveResumeRunId`: the `X-Run-Id` header first, then `?runId` on the
54request URL. Core's own `memoryStream` uses the same resolver, so no two
55durability adapters can disagree about which run a request names.
56
57- A **POST from `@tanstack/ai-client`** carries the run id in the `X-Run-Id`
58 header, not the URL. The POST URL stays byte-identical to a plain, non-durable
59 chat request.
60- A **GET join** carries it in the URL instead: `joinRun` requests
61 `?offset=-1&runId=<runId>`.
62
63So `durableStream(request, durableOptions)` on both routes resolves the same
64`agent-runs/<runId>` stream, whichever way the run id arrived. Nothing to rewrite,
65nothing to force onto a copy of the URL:
66
67```ts
68import { durableStream } from '@tanstack/ai-durable-stream'
69
70// The external Durable Streams backend every replica can reach. See
71// ../resumable-streams/advanced for the full option set (auth headers, batch
72// size, reconnect tuning).
73export const durableOptions = {
74 server: 'https://streams.example.com',
75 streamPrefix: 'agent-runs',
76}
77```
78
79A request naming no run at all (neither header nor query) throws rather than
80silently producing into a stream no attach request could ever name:
81
82```
83durableStream: a runId is required: send it as an X-Run-Id header or a
84?runId query param
85```
86
87That only bites a client that bypasses `@tanstack/ai-client` (a custom
88`fetch`, a hand-rolled reconnect): make sure it sends one of the two, an
89`X-Run-Id` header on the POST or `?runId` on the URL. A mid-stream SSE
90reconnect to the POST route still works. It arrives carrying `Last-Event-ID` and the
91same `X-Run-Id` header the original POST used, so `durableStream` resolves the run and
92honors the resume offset.
93
94And a caller with no live `Request` at all (a cron, a Durable Object `alarm()`)
95synthesizes one from scratch instead. See the reaper's own
96`durabilityFor` in [Reaping & Retention](./reaping).
97
98## Server: start a durable run
99
100```ts
101import {
102 chat,
103 chatParamsFromRequest,
104 toServerSentEventsResponse,
105} from '@tanstack/ai'
106import { withLocks } from '@tanstack/ai/locks'
107import { claudeCodeText } from '@tanstack/ai-claude-code'
108import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
109import { withSandbox } from '@tanstack/ai-sandbox'
110import { durableStream } from '@tanstack/ai-durable-stream'
111// The options from the section above.
112import { durableOptions } from './durability'
113// Your distributed LockStore. `InMemoryLockStore` is NOT enough here. See
114// "Requirements" below.
115import { locks } from './locks'
116// Your `defineSandbox(...)` result.
117import { sandbox } from './sandbox'
118
119// Development stand-in. A durable run needs a store every replica can read;
120// see ../persistence/build-your-own-adapter.
121const persistence = memoryPersistence()
122const { runs } = persistence.stores
123
124export async function POST(request: Request) {
125 const { messages, threadId, runId } = await chatParamsFromRequest(request)
126 // ONE adapter instance, handed to both the middleware and the transport, so
127 // the journal path and the delivery log describe the same run.
128 // `@tanstack/ai-client` sends `X-Run-Id` on every POST, which is exactly what
129 // `durableStream` resolves first, so this already addresses
130 // `agent-runs/<runId>`: the same stream the attach route below reads.
131 const adapter = durableStream(request, durableOptions)
132
133 const stream = chat({
134 adapter: claudeCodeText('claude-opus-4-8'),
135 messages,
136 threadId,
137 // Required for a durable run. Omit it and `chatStream` throws
138 // `DurableRunIdRequiredError`. See "Requirements".
139 runId,
140 middleware: [
141 withPersistence(persistence),
142 withLocks(locks),
143 withSandbox(sandbox, {
144 runs,
145 durability: { adapter },
146 }),
147 ],
148 })
149
150 return toServerSentEventsResponse(stream, { durability: { adapter } })
151}
152```
153
154Three things changed compared with a plain sandboxed chat endpoint, and each one
155is load bearing:
156
157- **`runs` + `durability`** turn on detach-on-disconnect and publish
158 `DetachableRunCapability` on the bus, which is how `withPersistence` learns
159 that an abort on this run is a detach rather than a cancel.
160- **`runId` is forwarded**, not generated. The journal path, the deterministic
161 message-id generator, **and the backend stream name** are all derived from it,
162 so a successor host can only resume a run whose `runId` it can recompute.
163- **The adapter instance is shared** between `withSandbox` and the response, and it is
164 keyed by that same `runId`. That is what makes the attach route below address this
165 very stream.
166
167One thing must **not** be there: an `abortController` that mirrors `request.signal`.
168
169A plain sandboxed endpoint mirrors it, because there a disconnect should end the run.
170On a durable run it destroys the thing you are trying to protect. Aborting the run
171makes `chat()` return at its cancellation check right after middleware `setup`, so the
172harness adapter's `chatStream` is never called and **the agent inside the sandbox you
173just spent minutes building is never launched**. Switch tabs while the UI still says
174"starting the sandbox" and you come back to an empty log for a run that did nothing.
175No takeover can recover it either, because an agent that never started wrote no
176journal to replay.
177
178The disconnect still reaches `withSandbox` without it. The durable transport notifies
179the run the moment the response body is cancelled, **without** aborting it, and then:
180
181- `withSandbox` stamps `detachedSince` and `sandboxKey`, and publishes the detach
182 verdict.
183- The run keeps draining into its still-open delivery log.
184- A rejoining client tails that log.
185
186Passing `runs` plus `durability` buys all of that. There is nothing else to wire.
187
188A genuine stop is unaffected, because it arrives out of band (see
189[Detach vs cancel](#detach-vs-cancel)). That is the only channel that can tell "the
190user wants this stopped" from "the user closed a tab", since both are the same socket
191close on the wire.
192
193### On `memoryStream`, raise the first-chunk deadline
194
195A rejoin during the sandbox build fails with
196`Memory stream run produced no data within 100ms`, and the run it calls gone is
197healthy. `memoryStream` gives up on a from-start rejoin when the run produces no chunk
198within `firstChunkDeadlineMs`, which defaults to 100ms. That default fits chat, where
199an in-flight run's log already holds chunks. A sandboxed run emits nothing until
200`ensure` has built the sandbox and cloned the repo.
201
202Raise it on **every** handle for the run. The `GET` that serves the rejoin is the call
203that actually applies it:
204
205```ts
206import { memoryStream } from "@tanstack/ai";
207
208// Longer than your slowest `ensure`.
209const FIRST_CHUNK_DEADLINE_MS = 15 * 60_000;
210
211// POST (the producer) and GET (the rejoin) alike.
212export function adapterFor(request: Request) {
213 return memoryStream(request, {
214 firstChunkDeadlineMs: FIRST_CHUNK_DEADLINE_MS,
215 });
216}
217```
218
219Failing fast buys nothing once you gate the rejoin on `findActiveRun`, which already
220excludes a run that is really gone before the join is attempted.
221
222Two things make this a backstop rather than the main defence:
223
224- `durableStream` runs no first-chunk deadline at all. Its `read` parks for a live
225 reader, so an empty in-flight log simply waits.
226- A fresh durable producer appends one `CUSTOM` `run.accepted` chunk
227 (`RUN_ACCEPTED_EVENT`) before it pulls the producer stream, so a rejoin attaches in
228 milliseconds instead of waiting on the harness. That chunk also keeps the client from
229 abandoning the join, since `ai-client` gives up on a rejoin that receives nothing for
230 2s and a sandbox build always takes longer.
231
232## Server: take the run over
233
234The takeover happens in the `GET` handler that already serves resumes. Add a
235`driver` and the same request that replays the log also claims the run and keeps
236driving it.
237
238Every adapter here comes from the **same** `durableStream(request, durableOptions)`
239the `POST` route used, so the log this route replays, the log the drive appends
240to, and the log the producing route wrote are provably one stream:
241`agent-runs/<runId>`.
242
243```ts
244import { chat, resumeServerSentEventsResponse } from '@tanstack/ai'
245import { withLocks } from '@tanstack/ai/locks'
246import { claudeCodeText } from '@tanstack/ai-claude-code'
247import { durableStream } from '@tanstack/ai-durable-stream'
248import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
249import { sandboxRunDriver, withSandbox } from '@tanstack/ai-sandbox'
250// The same backend options as the POST route.
251import { durableOptions } from './durability'
252import { locks } from './locks'
253import { sandbox } from './sandbox'
254import type { StreamChunk } from '@tanstack/ai'
255
256const persistence = memoryPersistence()
257const { messages: messageStore, runs } = persistence.stores
258
259/**
260 * The claim hands `drive` an `AbortSignal` that fires the moment this host loses
261 * ownership; `chat()` takes an `AbortController`. Mirror one onto the other so a
262 * lost claim actually stops the drive.
263 */
264function controllerFor(signal: AbortSignal): AbortController {
265 const controller = new AbortController()
266 const abort = (): void => controller.abort(signal.reason)
267 if (signal.aborted) abort()
268 else signal.addEventListener('abort', abort, { once: true })
269 return controller
270}
271
272export function GET(request: Request) {
273 async function* driveRun(input: {
274 runId: string
275 threadId: string
276 signal: AbortSignal
277 }): AsyncIterable<StreamChunk> {
278 // The client sent no history: it is reconnecting, not asking a question.
279 const stored = await messageStore.loadThread(input.threadId)
280 const stream = chat({
281 adapter: claudeCodeText('claude-opus-4-8'),
282 messages: stored,
283 threadId: input.threadId,
284 runId: input.runId,
285 abortController: controllerFor(input.signal),
286 middleware: [
287 withPersistence(persistence),
288 withLocks(locks),
289 withSandbox(sandbox, {
290 runs,
291 // `attach: true` is the whole difference: the harness tails the run's
292 // EXISTING journal instead of starting a second agent. It belongs
293 // here and never on `chat()`, which has no sandbox vocabulary. It
294 // is set only by an attach route, never by a POST handler.
295 durability: {
296 // `request` already names this run (`?runId` on an attach GET),
297 // so `durableStream` resolves the same `agent-runs/<runId>` the
298 // journal replay aligns against.
299 adapter: durableStream(request, durableOptions),
300 attach: true,
301 },
302 }),
303 ],
304 })
305 for await (const chunk of stream) yield chunk
306 }
307
308 return resumeServerSentEventsResponse({
309 // The replaying adapter is the one adapter here whose `resumeFrom()` matters,
310 // and the offset it must return (`?offset=-1` from a join, or an SSE
311 // reconnect's `Last-Event-ID`) lives on the incoming request. `durableStream`
312 // resolves the run the same way on every route, `X-Run-Id` header first,
313 // then `?runId`, so this addresses the same `agent-runs/<runId>` the POST
314 // route wrote, whichever way a given request names the run.
315 adapter: durableStream(request, durableOptions),
316 driver: sandboxRunDriver({
317 request,
318 runs,
319 locks,
320 // Per-run log factory. Core resolves the id from this same request
321 // through the same `resolveResumeRunId` `durableStream` uses, so every
322 // call for this run talks to the same backend stream and `snapshot()`
323 // sees this host's own appends. The state lives in the Durable Streams
324 // backend, not this process.
325 durability: () => durableStream(request, durableOptions),
326 drive: driveRun,
327 }),
328 })
329}
330```
331
332The response is **byte-identical** whether or not you pass `driver`: it still
333replays from the durability log. The drive runs beside it, appending to the run's
334producer-side log, and the response tails what lands. That separation is what
335lets a taken-over run keep `chat()`'s normal middleware path, so
336`withPersistence`'s `onFinish` still saves the transcript of a run that finished
337while detached.
338
339Everything about the takeover is **total by construction**. Every failure is
340logged and swallowed, and the response still serves the log:
341
342| Situation | What happens |
343| --- | --- |
344| No run id on the request, or no record | Serve the log, drive nothing. |
345| The record is already terminal | Serve the log, drive nothing. A second tab attaching to a finished run must still see the transcript. |
346| Another host holds the claim | Serve the log, drive nothing. Two tabs attaching at once: one wins the lease and drives, the other tails. |
347| The drive throws | Logged server-side. It cannot be reported to a response that is already streaming; the run's own `RUN_ERROR` event is that channel. |
348
349Serverless platforms need a keep-alive for the background drive. Pass
350`waitUntil: (promise) => ctx.waitUntil(promise)`.
351
352## Client: reconnect and continue
353
354A mid-stream drop needs nothing: `useChat` reconnects with the last offset and
355the server replays from the log.
356
357```tsx
358import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
359
360export function Chat() {
361 const chat = useChat({
362 connection: fetchServerSentEvents('/api/chat'),
363 })
364
365 return (
366 <button onClick={() => void chat.sendMessage('Refactor the auth module')}>
367 Send ({chat.messages.length} messages)
368 </button>
369 )
370}
371```
372
373A full reload is different. The page comes back with no `Last-Event-ID`, so it
374has to ask which run is still going and then join it from the start with
375`joinRun` (a read-only `GET` with `offset=-1`), which is exactly the handler
376above. That `GET` is what claims the run, so joining and taking over are the same
377request.
378
379```tsx
380import { fetchServerSentEvents } from '@tanstack/ai-client'
381import { useEffect, useState } from 'react'
382import type { StreamChunk } from '@tanstack/ai'
383
384export function ResumeInFlight({ threadId }: { threadId: string }) {
385 const [chunks, setChunks] = useState<Array<StreamChunk>>([])
386
387 useEffect(() => {
388 const controller = new AbortController()
389 const connection = fetchServerSentEvents('/api/chat')
390
391 async function rejoin(): Promise<void> {
392 const response = await fetch(
393 `/api/chat/active?threadId=${encodeURIComponent(threadId)}`,
394 { signal: controller.signal },
395 )
396 const body: unknown = await response.json()
397 if (typeof body !== 'object' || body === null || !('runId' in body)) return
398 const runId = body.runId
399 if (typeof runId !== 'string') return
400 for await (const chunk of connection.joinRun(runId, controller.signal)) {
401 setChunks((previous) => [...previous, chunk])
402 }
403 }
404
405 void rejoin().catch(() => {
406 // The run finished, or there was none. Nothing to rejoin.
407 })
408 return () => controller.abort()
409 }, [threadId])
410
411 return <p>{chunks.length} events replayed</p>
412}
413```
414
415The "which run" endpoint is `RunStore.findActiveRun`, which resolves a live run
416from the **stable** `threadId` rather than the ephemeral run id a single turn may
417mint several of. It is an optional store method, so feature-detect it.
418
419```ts
420import { memoryPersistence } from '@tanstack/ai-persistence'
421
422const persistence = memoryPersistence()
423const { runs } = persistence.stores
424
425export async function GET(request: Request) {
426 const threadId = new URL(request.url).searchParams.get('threadId')
427 if (threadId === null) {
428 return new Response('threadId is required', { status: 400 })
429 }
430 // Optional on the RunStore contract, so a backend that omits it degrades to
431 // "no active run" instead of throwing.
432 const active = await runs.findActiveRun(threadId)
433 return Response.json({ runId: active?.runId ?? null })
434}
435```
436
437All four HTTP connection adapters (`fetchServerSentEvents`, `fetchHttpStream`,
438`xhrServerSentEvents`, `xhrHttpStream`) expose `joinRun`. For NDJSON, pair it
439with `resumeHttpResponse` on the server; the driver wiring is identical.
440
441## Detach vs cancel
442
443**This is the part that is easy to get wrong, and getting it wrong is
444expensive.** A user pressing Stop and a user closing the tab produce the
445*identical* connection close. There is nothing in the disconnect to tell them
446apart.
447
448So intent is never inferred from the disconnect. It arrives **out of band**, and
449there are exactly two bands, and either one is authoritative:
450
4511. **Durable**: `requestRunCancel(runs, runId)` records `cancelRequested` on
452 the run record. This is the only channel that reaches a run being driven by a
453 *different* host than the one the cancel request landed on, which is the
454 normal case for a detached run.
4552. **In-process**: abort the run's own `AbortController` with
456 `RUN_CANCEL_REASON`. Core reads that reason back when it builds `AbortInfo`,
457 so `AbortInfo.cancelRequested` is `true` for that abort and `false` for a
458 plain disconnect. Fast path when the cancel reaches the driving host.
459
460A cancel endpoint should do **both**. `requestRunCancel` deliberately writes no
461status: recording intent is not the same as the run having stopped, and only the
462driver knows when the agent is actually dead and the sandbox is gone.
463
464```ts
465import { RUN_CANCEL_REASON, requestRunCancel } from '@tanstack/ai'
466import { memoryPersistence } from '@tanstack/ai-persistence'
467
468const persistence = memoryPersistence()
469const { runs } = persistence.stores
470
471/**
472 * Runs this process is currently driving. Only ever a fast path: a run driven by
473 * another replica is absent here, and the durable band is what reaches it.
474 */
475const driving = new Map<string, AbortController>()
476
477export async function POST(request: Request) {
478 const body: unknown = await request.json()
479 if (typeof body !== 'object' || body === null || !('threadId' in body)) {
480 return new Response('threadId is required', { status: 400 })
481 }
482 const threadId = body.threadId
483 if (typeof threadId !== 'string') {
484 return new Response('threadId must be a string', { status: 400 })
485 }
486
487 const active = await runs.findActiveRun(threadId)
488 if (!active) return new Response(null, { status: 204 })
489
490 // Band 1: durable, so a remote driver observes it on its next teardown.
491 await requestRunCancel(runs, active.runId)
492 // Band 2: in-process, so a co-located driver stops immediately.
493 driving.get(active.runId)?.abort(RUN_CANCEL_REASON)
494
495 return new Response(null, { status: 204 })
496}
497```
498
499Populate `driving` where you create the run's `AbortController`: in the `POST`
500handler for a fresh run, and in `controllerFor` on the takeover path.
501
502On the client, `chat.stop()` sends the server nothing. A durable run then
503continues, because a refresh looks the same. Call the endpoint too.
504
505```tsx
506import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
507
508export function StoppableChat({ threadId }: { threadId: string }) {
509 const chat = useChat({
510 threadId,
511 connection: fetchServerSentEvents('/api/chat'),
512 })
513
514 async function stopRun(): Promise<void> {
515 // Local: stop rendering the stream immediately.
516 chat.stop()
517 // Remote: tell the server this was intent, not a lost connection.
518 await fetch('/api/chat/cancel', {
519 method: 'POST',
520 headers: { 'Content-Type': 'application/json' },
521 body: JSON.stringify({ threadId }),
522 })
523 }
524
525 return <button onClick={() => void stopRun()}>Stop</button>
526}
527```
528
529### What each path writes
530
531| Event | `withSandbox` | `withPersistence` | Delivery log |
532| --- | --- | --- | --- |
533| Disconnect, durable, `detachOnDisconnect` on, no cancel recorded | Keeps the sandbox; writes `detachedSince` and `sandboxKey` | Writes **nothing**; the record stays `'running'` | Left **open**, no terminal appended |
534| Cancel (either band) | Destroys the sandbox, always, regardless of `destroyOnComplete` | Writes `'aborted'` with `finishedAt` | Terminal `RUN_ERROR`, then closed |
535| Disconnect on a non-durable run | Destroys the sandbox | Writes `'aborted'` | Terminal `RUN_ERROR`, then closed |
536
537The delivery-log column is what makes takeover work at all. A detached run's log
538has to stay open and terminal-free: a closed log ends the attaching client's
539replay at the prefix, and a stored synthetic `RUN_ERROR` is a chunk the takeover's
540journal replay cannot reproduce, so alignment diverges and a perfectly healthy run
541is recorded as `'failed'`. See [`RunDetachedCapability`](#rundetachedcapability)
542for how the verdict reaches the transport.
543
544`keepAlive` / `destroyOnComplete: false` govern *successful completion* only.
545They never keep a sandbox alive through a cancel.
546
547Get this backwards in either direction and it hurts: a Stop button that only
548calls `chat.stop()` leaks running sandboxes that keep spending tokens with nobody
549watching, and treating every disconnect as a cancel kills a user's ten-minute
550refactor on a wifi blip.
551
552### What cancel means on a provider that cannot kill
553
554On a provider whose capabilities declare `killableProcesses: false` (Daytona,
555Vercel, and Cloudflare among the bundled ones (see
556[the measured table](./providers#killableprocesses-across-the-bundled-providers))
557and no signal reaches the agent process: `kill()` does not stop it, and no
558`AbortSignal` crosses the provider boundary. There, **the sandbox destroy the
559cancel path performs is not cleanup, it is the cancel**. It is the only mechanism
560that actually stops the agent. Wire a cancel to anything less (mark the record
561`'aborted'`, close the log, skip the destroy) and what you have built is
562"marked cancelled, still running": the UI says stopped while the agent keeps
563working and the sandbox keeps billing.
564
565## Single-writer safety
566
567Only one host may write a run, and the client has no safety
568net below its offset de-dup. If two hosts both snapshot the log, both compute a
569"remainder", and both append it, the same logical chunk lands twice under two
570different offsets, so it looks new to the client, and the stream processor
571applies text and tool-argument deltas unconditionally. You get doubled prose and
572`{"a":1}{"a":1}` tool arguments. Takeover is by definition two hosts wanting one
573run, so the exclusion has to be real.
574
575`sandboxRunDriver` wires it for you, in three layers:
576
5771. **A lease.** The entire drive runs inside `LockStore.withLock` on a per-run
578 key, so the snapshot and every append after it are one critical section. A
579 lease-backed lock aborts the drive's signal the moment ownership is lost.
5802. **An epoch.** Each successful claim bumps `RunRecord.driverEpoch`. The log
581 re-reads it periodically and refuses to append once a higher epoch exists.
582 This covers what a lease cannot: a lock whose renewal is coarser than the
583 run's append rate, or one whose signal never fires at all.
5843. **Quiescence.** The successor waits for the stored log to stop growing before
585 its first append, so a predecessor that is still writing is *observed* rather
586 than raced. The window defaults to `DEFAULT_FENCE_QUIET_MS` (5 seconds) and is
587 configurable with `fenceQuietMs`. If the log never quiesces, the drive fails
588 instead of appending into a log another host is still writing.
589
590### Both authoritative channels are fenced
591
592A run's facts live in **two** places: its event log and its record. Fencing only
593the log does not remove the harm, it relocates it. A superseded driver whose
594append is refused folds that refusal into a terminal `runs.update`, and the
595record then reads `'failed'` for a run the successor is healthily streaming.
596Every consumer that branches on terminal status (`isTerminalRunStatus`,
597`findActiveRun`, a status poller, a reaper) would then believe a live run had
598died, on the authority of a host that no longer owns it.
599
600So both seams are closed, over the same claim:
601
602- **The log.** A superseded driver's `append` is refused. The **first** refusal
603 latches the fence permanently shut: every later append refuses immediately,
604 without a re-read. That permanence matters, because the refused append is followed
605 directly by the recovery path's own terminal `RUN_ERROR`, and that log belongs
606 to the *successor*, so a dead host's error chunk would fail the stream for
607 every client attached to the healthy run.
608- **The record.** A terminal-status `update` from a lost claim is **suppressed**:
609 it resolves without writing. Non-terminal writes still pass through, including
610 a stale `detachedSince` or `sandboxKey`. Those cannot make a live run look
611 finished, and the successor owns and overwrites them anyway.
612
613The practical upshot for you: **a terminal status on the record is trustworthy.**
614A status poller may believe it.
615
616`close()` is outside both fences, deliberately. It runs on every teardown path
617including the teardown *caused* by losing the claim, and a fenced `close` would
618wedge the record at `'running'` with every live tailer parked forever: a
619durability `read` only ends when the log closes. A wedged run with parked clients
620is worse than the write being prevented.
621
622### Errors you can branch on
623
624```ts
625import {
626 RunClaimLostError,
627 RunClaimNotAcquiredError,
628 RunDriverPipeOutsideClaimError,
629} from '@tanstack/ai-sandbox'
630
631function describeDriveFailure(error: unknown): string {
632 if (error instanceof RunClaimNotAcquiredError) {
633 // 'terminal' | 'unknown' | 'superseded': normal, not a bug.
634 return `not driving ${error.runId}: ${error.reason}`
635 }
636 if (error instanceof RunClaimLostError) {
637 return `superseded mid-drive at epoch ${error.heldEpoch}`
638 }
639 if (error instanceof RunDriverPipeOutsideClaimError) {
640 // A programming error: the options object was taken apart and `pipe` called
641 // outside `claim`, so there is no epoch to fence with.
642 return `run ${error.runId}: pipe ran outside its claim`
643 }
644 throw error
645}
646```
647
648The first two are ordinary outcomes of a contended takeover and
649`resumeServerSentEventsResponse` already swallows both. You will see them in
650logs, not in responses.
651
652### What this is not
653
654It is not airtight fencing. A predecessor paused (GC, VM suspend) for longer than
655the quiescence window, between its last fence check and its append landing at the
656backend, can still write one batch. Closing that needs a compare-and-set on the
657durability write, which `StreamDurability.append` does not offer. The mitigation
658is deployment-level: use a lease-backed distributed `LockStore`, and keep
659`fenceQuietMs` above the lease's renewal interval.
660
661## Replay and divergence
662
663A takeover does not resume the journal from where the dead host stopped. It
664re-reads the journal **from byte zero** and re-translates it, which reproduces
665chunks the client already has. Alignment is what makes that safe: the stored log
666is read once, the replay is verified against it by fingerprint, the matching
667prefix is suppressed, and only the remainder is appended and delivered. The log
668*is* the checkpoint, so there is no window in which a checkpoint and the log can
669disagree. The precedence rule this implements: **the log wins for what clients
670see; the journal wins for where the taking-over driver resumes.**
671
672Two properties make the comparison possible, and both are already true on the
673journaled path:
674
675- **Ids are deterministic.** A journaled run mints message ids from a run-scoped
676 counter (`<runId>-0`, `<runId>-1`, …) rather than a timestamp plus randomness.
677- **Alignment runs only on an attach.** On a fresh run the transform's premise
678 ("this stream is a replay of what is already stored") is false, and aligning
679 anyway would match a fresh run's own chunks against pre-existing log entries
680 and silently *suppress* them. That is data loss, not a slow path.
681
682### `JournalReplayDivergedError`
683
684If the replay produces a different chunk than the log already holds at that
685index, `JournalReplayDivergedError` is thrown with the index and both
686fingerprints.
687
688```ts
689import { JournalReplayDivergedError } from '@tanstack/ai-sandbox'
690
691function report(error: unknown): string {
692 if (error instanceof JournalReplayDivergedError) {
693 return `diverged at ${error.index}: stored ${error.stored}, replayed ${error.replayed}`
694 }
695 throw error
696}
697```
698
699Read it plainly: **the agent's replay produced a different sequence of events
700than the log already delivered.** Translation stopped being deterministic. The
701realistic causes are an id generator that is not run-scoped, a translator that
702consults the clock, or a journal that was rewritten (most often a reused
703`runId`).
704
705What to do about it: treat it as a bug to fix, not a condition to recover from.
706Do not catch it and continue. The log is authoritative and already went to the
707client, so forwarding past a mismatch delivers a stream whose prefix and suffix
708disagree about message identity, and the client cannot survive that. Log the
709index and both fingerprints, let the run fail, and check `runId` uniqueness
710first.
711
712One tolerance exists. On adapters that splice host-tool-bridge events into their
713output (`@tanstack/ai-codex`, `@tanstack/ai-claude-code`), the log holds `CUSTOM`
714chunks fired by *live* tool execution, which a replay runs no tools to reproduce.
715Alignment skips those as out-of-band, up to `DEFAULT_MAX_OUT_OF_BAND_SKIP` (64)
716consecutive entries. The bound is what keeps this a tolerance rather than a
717search: unbounded, a genuine determinism regression would scan forward looking
718for any fingerprint that happens to match.
719
720## Configuration
721
722All of these live under `withSandbox(sandbox, { durability: { … } })`.
723
724| Option | Default | What it does |
725| --- | --- | --- |
726| `adapter` | required | The run's delivery-durable event log. Same instance you hand the transport. |
727| `journal` | `/tmp/tanstack-runs` (`DEFAULT_JOURNAL_DIR`) | Journal directory inside the sandbox. |
728| `detachOnDisconnect` | `true` whenever durability is wired | Whether a disconnect detaches instead of destroying the sandbox. |
729| `attach` | `false` | Read an existing run's journal instead of starting an agent. Set by an attach route's `drive`, never by a `POST` handler. |
730| `pollIntervalMs` | adapter default | Journal poll interval for providers that cannot follow a file. |
731
732There is deliberately no `detachedRunTtl` here. The only actor that enforces a
733TTL is `reapDetachedRuns`, which runs from a cron with no chat request in
734flight, so it cannot read anything `withSandbox` publishes on the
735per-request capability bus, so a TTL stored here could only ever go unread,
736while the sweep took its own `detachedRunTtlMs`, and the two would silently
737disagree. So the sweep's `detachedRunTtlMs` (milliseconds, no default, no
738string parsing) is the single source of truth; see [Reaping &
739Retention](./reaping) for sizing it.
740
741**The reaper ships, but nothing schedules it.** `reapDetachedRuns` from
742`@tanstack/ai-sandbox` is the sweep. It reads the optional
743`RunStore.listReclaimable({ now, ttlMs })`, which returns runs that are
744`'running'`, have a `detachedSince`, and whose `detachedSince <= now - ttlMs`
745(inclusive). It drives each run its out-of-band journal probe says already finished
746to a terminal status so the transcript lands, cancels and terminalizes the ones
747past `detachedRunTtlMs`, and destroys the sandbox named by `sandboxKey` through
748`sandboxReclaimer`. It never clears `detachedSince`: that marker is the evidence
749its TTL accounting selected the run on. (The takeover path clears it, because a
750viewer is attached again.)
751
752It is a plain async function with no timer and no daemon, so **calling it on a
753schedule is your job**: a cron route, a queue consumer, a Durable Object
754`alarm()`, a `waitUntil`. Treat that as a hard requirement of wiring
755`durability`, not a nice-to-have: until something invokes it, nothing closes a
756detached run's delivery log, so every attached client parks forever,
757`detachedRunTtlMs` is enforced by nothing, and the sandbox bills indefinitely.
758
759[Reaping & Retention](./reaping) is the whole picture: the sweep's outcomes, why
760it never drives a run to find out whether it finished, `pruneJournals`,
761`reclaimSandbox`, ready-to-paste schedules for Node, Vercel Cron, and a
762Cloudflare `alarm()`, and how to size the TTL against the sweep interval.
763
764Set `detachOnDisconnect: false` to keep today's destroy-on-disconnect cost
765profile while still getting resumable *delivery*: a reload replays the log, but
766the agent does not survive the disconnect. An explicit cancel destroys the
767sandbox either way.
768
769### `DetachableRunCapability`
770
771A neutral boolean that core owns. `withSandbox` provides it as `true` only when a
772run is genuinely durable; `withPersistence` reads it with `getOptional` to decide
773whether an abort is terminal (`'aborted'`) or a detach (write nothing). It lives
774in core so the two packages can agree without either importing the other. A
775persistence → sandbox import would invert the layering. Read it in your own
776middleware if you need the same distinction; absent means "not detachable", which
777is every app that has not wired durability.
778
779### `RunDetachedCapability`
780
781Its past-tense counterpart, also owned by core. `DetachableRunCapability` is
782published at setup and only says a disconnect *may* be survived;
783`RunDetachedCapability` is published on the abort path by `withSandbox`'s detach
784branch and says the run **was** detached. The agent is still working and a later
785attach can take it over.
786
787Its consumer is the durable delivery sink behind `toServerSentEventsResponse` /
788`toHttpResponse`. Without the verdict the sink terminalizes every abort, which
789defeats takeover (see the table above). The fact travels on the **stream object
790itself**, so there is nothing to wire: passing `chat()`'s stream to the response
791helper is already mandatory, and both sides hold the same object.
792
793```ts
794import { provideRunDetached } from '@tanstack/ai'
795import type { CapabilityContext } from '@tanstack/ai'
796
797// You do not write this. `withSandbox` does, on its detach branch, from a hook
798// that already holds the middleware context. Shown only so the fact is legible.
799function markRunDetached(ctx: CapabilityContext): void {
800 provideRunDetached(ctx, true)
801}
802```
803
804Only a plain, intentless disconnect of a detachable run publishes it. An explicit
805cancel in either band, a disconnect on a non-detachable run,
806`detachOnDisconnect: false`, a provider failure, and a normal finish all leave it
807unpublished, and the sink appends its terminal and closes the log exactly as it
808always has. Core additionally refuses to treat an abort carrying
809`RUN_CANCEL_REASON` as a detach, whatever a middleware publishes. A user pressing
810Stop always gets a closed, terminal log.
811
812## Requirements
813
814**A real `LockStore`.** `InMemoryLockStore` cannot coordinate across hosts: it
815serializes claims within one process, and the signal it hands out is a fresh
816`AbortController().signal` that is never aborted, so the lease can never report a
817loss. Two replicas can then drive one run and duplicate its log. `withSandbox`
818emits a warning when durability is wired over an in-memory lock (including when
819no lock is wired at all, since the fallback *is* in-memory). See
820[Locks](../advanced/locks).
821
822**A caller-supplied `runId`.** A durable run throws
823`DurableRunIdRequiredError` at the start of `chatStream` when none is passed.
824That is deliberately loud, because the alternative is invisible: an
825adapter-generated id produces a journal path no successor host can recompute, so
826the run streams normally, records normally, and is silently unrecoverable. You
827would only discover it during an incident.
828
829**The run record's `threadId`, on an attaching run.** An ATTACHING durable run
830throws `DurableThreadIdRequiredError` when driven without the run record's
831`threadId`. `threadId` rides in **every** emitted chunk, so an attach that
832generates a fresh one replays a stream whose very first chunk already differs
833from the stored log. Alignment fails at index 0 with
834`JournalReplayThreadIdMismatchError`, a subclass of
835[`JournalReplayDivergedError`](#journalreplaydivergederror) reported above,
836even though the agent behaved identically. This is the asymmetry to keep
837straight: a durable **fresh** run needs no caller `threadId`, because that run is
838what establishes it, but a durable run that is **attaching** must reuse the
839one already on the record, which is exactly the `threadId: input.threadId`
840forwarded by `driveRun` above.
841
842**A `RunStore` that persists every durable-run field.** `createOrResume`,
843`update`, and `get` are required; `update` must accept and round-trip all of
844`status`, `finishedAt`, `error`, `usage`, `sandboxKey`, `detachedSince`,
845`cancelRequested`, and `driverEpoch`. The last four are exactly what a
846hand-written backend tends to omit, and each one breaks a specific
847mechanism: no `driverEpoch` means no fencing, no `cancelRequested` means Stop
848cannot reach a remote driver, no `detachedSince`/`sandboxKey` means nothing can
849reclaim the sandbox. Two invariants also hold: `createOrResume` returns an
850existing record **unchanged** (that is what makes resuming safe), and `update` on
851an unknown `runId` is a **no-op** that must not throw.
852
853`findActiveRun` is required: it is how you rejoin by thread. `listReclaimable`
854is optional and feature-detected, but `reapDetachedRuns` needs it to have
855anything to sweep: a store without it cannot be reaped at all.
856
857## Adapter authors
858
859If you are writing a harness adapter rather than an application, three exports
860are yours: `getSandboxDurability` reads the resolved durability off the
861capability bus, `journalOptionsFor` turns it into the journal option
862`spawnNdjson` takes, and `alignedIfAttaching` applies alignment on attach only.
863Wrap the *merged* output stream, never the pre-merge translator, or you compare
864against a stream the log never contained. See [Harnesses](./harnesses).
865
866## See also
867
868- [Durable Runs Explained](./durable-runs): the mental model behind this page, in
869 plain language and with no code. Start there if any of the above felt abrupt
870- [The Run Journal](./journal): where the agent's output lives, `runId`
871 uniqueness, and `alignToStoredLog`
872- [Sandbox Instance Durability](./durability): keeping the sandbox itself
873 findable across processes
874- [Lifecycle & Snapshots](./lifecycle): `destroyOnComplete`, `keepAlive`, and
875 snapshots
876- [Resumable Streams](../resumable-streams/overview) and
877 [Advanced](../resumable-streams/advanced): the delivery log, `joinRun`, and
878 offset ownership
879- [Locks](../advanced/locks): the distributed lock a durable run requires
880- [Persistence overview](../persistence/overview) and
881 [Store Reference](../persistence/store-reference): the shared
882 `RunStore`