Open History to see the last commit
1---
2title: The Run Journal (Advanced)
3id: sandbox-journal
4order: 12
5description: "Every sandboxed agent run writes its NDJSON output to an append-only journal inside the sandbox, so the host reads a file instead of holding a pipe."
6keywords:
7 - run journal
8 - readJournal
9 - journalPaths
10 - alignToStoredLog
11 - killableProcesses
12 - exitSentinelLine
13 - awaitAttachableJournal
14 - journal-stalled
15---
16
17A sandboxed coding agent can work for ten minutes. If the host process holding
18the agent's stdout pipe goes away in minute three, that pipe breaks, the agent
19gets a `SIGPIPE`, and the work is gone. Nothing is left to read, because the
20only copy of the agent's output was in flight.
21
22So the agent does not write to a pipe. Its stdout is redirected to a file inside
23the sandbox, and the host tails that file:
24
25```
26/tmp/tanstack-runs/<runId>.ndjson every NDJSON event the agent emitted
27/tmp/tanstack-runs/<runId>.err the agent's stderr, kept separate
28```
29
30Because there is no pipe, there is no reader whose disappearance can signal the
31agent. And because the journal is a file, a reader can start at byte 0 whenever
32it likes.
33
34## You have to ask for a journal
35
36**Journaling is not on by default, and this is the first thing to get right —
37everything else on this page assumes the file exists.** The three built-in
38harness adapters (`grokBuildText`, `claudeCodeText`, `codexText`) journal a run
39only when that run is **durable**, which means `withSandbox` was given **both**
40`runs` and `durability` — `withSandbox(sandbox, { runs, durability: { adapter } })`,
41as the snippet below does. Pass neither (a plain `withSandbox(sandbox)`) or only one, and there is no
42journal at all: `journalOptionsFor` answers `undefined`, `spawnNdjson` takes its
43original unjournaled path, and the agent's stdout is a pipe again, exactly as it
44was before this feature existed. Nothing warns — a half-configured app has not
45asked for durability, so there is nothing to warn about. If you go looking for
46`/tmp/tanstack-runs/<runId>.ndjson` after running a plain `withSandbox(sandbox)`,
47you will not find it, and the reason is here rather than in your provider.
48
49Why both: a record with no event log cannot be replayed, and a log with no record
50cannot be found, claimed, or reaped. There is no useful half.
51
52## Give every run an id you can recompute
53
54The journal path is derived from `runId` alone, so a `runId` you cannot
55reproduce is a journal nobody can find. Adapters fall back to a random internal
56id on a **non-durable** run; on a durable one there is no fallback at all —
57`chatStream` throws `DurableRunIdRequiredError`, deliberately, because an id no
58successor host can recompute produces a run that streams normally and is
59silently unrecoverable.
60
61So forward the `runId` the request already carries, alongside the two stores that
62turn journaling on:
63
64```ts
65import {
66 chat,
67 chatParamsFromRequest,
68 memoryStream,
69 toServerSentEventsResponse,
70} from '@tanstack/ai'
71import { claudeCodeText } from '@tanstack/ai-claude-code'
72import { memoryPersistence } from '@tanstack/ai-persistence'
73import { withSandbox } from '@tanstack/ai-sandbox'
74// Your `defineSandbox(...)` result.
75import { sandbox } from './sandbox'
76
77// Single-process stand-ins, enough to see a journal on your laptop. A real
78// deployment needs a store and a stream backend every replica can reach — see
79// ./takeover for that wiring, plus the distributed lock it requires.
80const persistence = memoryPersistence()
81const { runs } = persistence.stores
82
83export async function POST(request: Request) {
84 const { messages, threadId, runId } = await chatParamsFromRequest(request)
85 // One instance, handed to both the middleware and the transport, so the
86 // journal and the delivery log describe the same run. `memoryStream` reads the
87 // run id from the `X-Run-Id` header `@tanstack/ai-client` sends, so it needs
88 // no help on a POST route; `durableStream` does — see ./takeover.
89 const adapter = memoryStream(request)
90 const stream = chat({
91 adapter: claudeCodeText('claude-sonnet-4-6'),
92 messages,
93 threadId,
94 // Without this a durable run throws: the journal path and the deterministic
95 // message ids are both derived from it, so a later reader can only find the
96 // journal of a run whose `runId` it can recompute.
97 runId,
98 // BOTH options, or there is no journal to read.
99 middleware: [withSandbox(sandbox, { runs, durability: { adapter } })],
100 })
101 return toServerSentEventsResponse(stream, { durability: { adapter } })
102}
103```
104
105`@tanstack/ai-client` mints a fresh `runId` for every run and puts it in the
106AG-UI request body, which is what `chatParamsFromRequest` hands back. So the
107client half of this is nothing at all: `useChat` already sends a unique id per
108run, and reconnecting behaviour is unchanged.
109
110```tsx
111import { fetchServerSentEvents } from '@tanstack/ai-client'
112import { useChat } from '@tanstack/ai-react'
113
114export function Chat() {
115 const { messages, sendMessage } = useChat({
116 connection: fetchServerSentEvents('/api/chat'),
117 })
118 return (
119 <button onClick={() => sendMessage('Refactor the auth module')}>
120 Send ({messages.length} messages)
121 </button>
122 )
123}
124```
125
126### A `runId` must be unique per run
127
128The journal is append-only, and `/tmp/tanstack-runs` is a fixed absolute path
129that outlives any single run, test, or process. Reusing a `runId` therefore does
130not start a fresh journal. It appends to the old one, behind the old run's exit
131sentinel.
132
133A reader stops at the last matching sentinel it sees in its tail window. So a
134reused id makes the second run look like it emitted no events at all, or like it
135failed with the previous run's exit code. Nothing throws, nothing warns: you get
136a silently empty run.
137
138This is not enforced, because refusing to append would break the replay the
139append-only rule exists for. Derive the id from something unique per run (a
140UUID, or the client's own `runId`) and never hardcode a literal.
141
142## Reading a journal
143
144`readJournal` yields one complete line at a time, each tagged with the absolute
145byte position just past its newline. A partial line the agent is still writing
146is never yielded, so a position is always a byte offset you can resume from.
147
148```ts
149import { journalPaths, readJournal } from '@tanstack/ai-sandbox'
150// A live `SandboxHandle`, e.g. from `provider.create(...)`.
151import { handle } from './sandbox-handle'
152
153async function tailRun(runId: string) {
154 for await (const { line, endPosition } of readJournal(handle, {
155 paths: journalPaths(runId),
156 })) {
157 console.log(endPosition, line)
158 }
159}
160```
161
162Nothing about that call changes for a run that started five minutes ago under a
163different process. Resume is not a separate code path: every read is
164`tail -c +N` for some N, and a fresh run is simply N = 0.
165
166Two details worth knowing:
167
168- **The journal is only ever touched through the shell**, never through
169 `handle.fs.*`. On the local-process provider, `fs.write` resolves `/tmp`
170 under the sandbox root while a shell redirect hits the real host `/tmp`. Both
171 halves agree with each other precisely because nothing uses `fs`. If you write
172 your own journal tooling, keep it on `handle.process`.
173- **Stderr lives in its own sidecar file**, so a `tail` diagnostic or a chatty
174 CLI banner can never splice itself into the event bytes. A non-zero exit
175 carries the tail of that sidecar in its error message.
176
177### Follow or poll, chosen by capability
178
179Most providers can run a killable `tail -c +N -f` under `spawn`, which streams
180with no polling cost. A provider whose spawned processes cannot be stopped gets
181a poll loop of bounded `exec` calls instead, each of which terminates on its
182own, so nothing unstoppable is ever started inside the sandbox.
183
184The choice reads `backgroundProcesses && killableProcesses` off the handle's
185capabilities, never the provider's name, so a bring-your-own provider with the
186same limitation is treated the same way. See
187[`killableProcesses`](./providers#capabilities) for which providers declare
188what.
189
190You can force either strategy for a diagnostic:
191
192```ts
193import { journalPaths, journalReadStrategy, readJournal } from '@tanstack/ai-sandbox'
194import { handle } from './sandbox-handle'
195
196console.log(journalReadStrategy(handle)) // 'follow' | 'poll'
197
198const lines = readJournal(handle, {
199 paths: journalPaths('run-2a7f'),
200 strategy: 'poll',
201 pollIntervalMs: 100,
202})
203```
204
205## The exit sentinel carries a nonce
206
207The line a run's shell appends after the agent exits is not the bare
208`{"__exit":N}` it once was. It now carries a second field too:
209
210```json
211{"__exit":0,"__nonce":"3f9c1a7b..."}
212```
213
214The agent's stdout and this sentinel line are redirected into the *same*
215unframed journal file, with no framing between them. Without the nonce, any
216line an agent happened to print that was also shaped like `{"__exit":N}` — an
217echoed fixture, a `cat`-ed diagnostics file, a dumped config — was a valid
218sentinel. The reader took the *first* matching line in its tail window, so an
219agent that printed such a line early made `probeRunExit` report a run that was
220still mid-flight as `'finished'`. The reaper then drove that run to terminal
221and reclaimed its sandbox out from under a live agent — the one thing this
222whole journal mechanism promises never to do.
223
224`__nonce` is a per-run value derived from the `runId`:
225`sha256('tanstack-ai-sandbox/journal-exit-sentinel/v1:' + runId)`, truncated to
22632 hex characters. It is **derived, not random**, on purpose: the reaper reads
227journals written by a process that is already gone, with nothing but the
228`runId` to go on, so a successor host has to be able to recompute the same
229nonce the original process wrote. `parseJournalExit` now scans its window from
230the **end** backwards (the shell always writes the real sentinel after all of
231the agent's own output) and refuses a matching line whose `__exit` value is not
232an integer, rather than coercing it to `0`.
233
234Both changes narrow the accidental-forgery class to nothing, but the residual
235is honest: because the nonce is derived rather than secret, an agent that knows
236its own `runId` and reimplements the derivation could still emit a matching
237line on purpose. Closing that would need a secret carried on the run record
238that only a legitimate host can read — a `RunStore` schema change, not
239something this journal-composition module can do on its own.
240
241If you seed a journal by hand — a test, a fixture, a custom harness that is not
242going through `journaledCommand` — write the sentinel with
243`exitSentinelLine(paths, exitCode)` rather than hand-rolling the JSON, so you
244produce the exact bytes the shell's `printf` would:
245
246```ts
247import { exitSentinelLine, journalPaths } from '@tanstack/ai-sandbox'
248
249function seedSentinel(runId: string, exitCode: number): string {
250 const paths = journalPaths(runId)
251 return exitSentinelLine(paths, exitCode)
252 // '{"__exit":0,"__nonce":"..."}' — append this, not a hand-written object.
253}
254```
255
256## A read can fail: `'journal-stalled'`
257
258`readJournal` cannot hang forever waiting for a journal that will never
259produce anything. Both the follow strategy and the poll strategy bound their
260wait for the journal's **first** byte to `DEFAULT_ATTACH_JOURNAL_WAIT_MS`
261(10 seconds by default); a read that receives nothing in that window throws
262`JournalAttachUnavailableError` with `reason: 'journal-stalled'` instead of
263parking.
264
265That bound exists because `journalFollowCommand`'s first act is `: >> file` —
266it has to create the journal before it can tail it. So an attach against a
267`runId` whose journal never existed used to manufacture an empty file and
268follow it forever, and once that file existed, every later existence probe
269(`test -f`) succeeded too, so the same runId hung on every subsequent attach as
270well. The bound applies only to the first byte: once a journal starts
271producing, however long the agent thinks between lines is the agent's
272business, and no deadline here cuts a healthy run short.
273
274```ts
275import {
276 JournalAttachUnavailableError,
277 journalPaths,
278 readJournal,
279} from '@tanstack/ai-sandbox'
280import { handle } from './sandbox-handle'
281
282async function tailWithStallGuard(runId: string) {
283 try {
284 for await (const { line } of readJournal(handle, {
285 paths: journalPaths(runId),
286 runId,
287 })) {
288 console.log(line)
289 }
290 } catch (error) {
291 if (error instanceof JournalAttachUnavailableError && error.reason === 'journal-stalled') {
292 // The journal exists but nothing is appending to it and no sentinel can
293 // arrive — the run's shell was killed before it wrote one, or the read
294 // itself just created an empty file for a runId with no journal.
295 } else {
296 throw error
297 }
298 }
299}
300```
301
302Override the wait per call with `firstByteTimeoutMs`, or pass `0` to disable
303it entirely — only where some other deadline already covers the read, since an
304unbounded read of an empty journal never returns.
305
306### Gating an attach before the read even starts
307
308`readJournal` has no `RunStore` and no `runId` to look one up with, so it
309cannot tell an unknown or terminal run apart from a live one that simply
310hasn't written its first line yet — every case looks the same to it and gets
311the same bounded wait. A caller that *does* have a store can ask a sharper
312question first with `awaitAttachableJournal`: it consults the run record
313before falling back to the same bounded wait, so a stale or mistyped `runId`
314fails fast as `'unknown-run'` or `'terminal-run'` instead of waiting out the
315full timeout.
316
317```ts
318import { awaitAttachableJournal, journalPaths } from '@tanstack/ai-sandbox'
319import { memoryPersistence } from '@tanstack/ai-persistence'
320import { handle } from './sandbox-handle'
321
322// The same `RunStore` `withSandbox` was given.
323const { runs } = memoryPersistence().stores
324
325async function gateAttach(runId: string) {
326 await awaitAttachableJournal(handle, {
327 paths: journalPaths(runId),
328 runId,
329 runs,
330 })
331 // Only after this resolves is it worth calling `readJournal`.
332}
333```
334
335## Replaying a journal against a log you already delivered
336
337The rule, in one sentence: **the log wins for clients, the journal wins for the
338driver's resume position.** Everything in this section is that rule made
339mechanical.
340
341A host that translated journal bytes 0 to 1000 and appended the resulting chunks
342to a [resumable-stream](../resumable-streams/overview) log, then went away, left
343the client holding those chunks. A host reading the same journal from byte 0 will
344re-derive them. Appending them a second time corrupts the client: its de-dup is
345keyed on the offset the durability adapter minted, so a re-appended chunk looks
346new, and the stream processor concatenates text deltas and tool-call arguments
347unconditionally. Duplicated prose and `{"a":1}{"a":1}` arguments.
348
349`alignToStoredLog` is the primitive that prevents it. It reads the stored prefix
350once with `snapshot()`, checks that the replay reproduces it, suppresses it, and
351yields only the remainder:
352
353```ts
354import { memoryStream } from '@tanstack/ai'
355import { alignToStoredLog } from '@tanstack/ai-sandbox'
356import type { StreamChunk } from '@tanstack/ai'
357
358async function forwardRemainder(
359 request: Request,
360 replayed: AsyncIterable<StreamChunk>,
361) {
362 const durability = memoryStream(request)
363 for await (const chunk of alignToStoredLog(replayed, { durability })) {
364 await durability.append([chunk])
365 }
366}
367```
368
369Plain `append`, in append order, with offsets the adapter mints. No caller-chosen
370offsets are involved, which is why this works on `durableStream` as well as
371`memoryStream`. See
372[Offset ownership](../resumable-streams/advanced#offset-ownership).
373
374### Ids are deterministic, so replay is comparable
375
376Alignment can only recognise a stored chunk if re-translation reproduces it, and
377a message id built from `Date.now()` plus `Math.random()` never does. So the
378journaled path mints ids from a run-scoped counter instead.
379
380The visible consequence: a message id looks like `<runId>-0`, `<runId>-1`, and so
381on, rather than `<provider>-<timestamp>-<random>`. Ids remain unique per run and
382opaque; if you were parsing them for a provider name or a timestamp, stop.
383
384Comparison excludes `timestamp`, which is wall-clock and cannot be reproduced.
385Every other field participates, including nested tool-call arguments and fields
386whose value is explicitly `undefined`.
387
388### Divergence throws
389
390If the replay produces a different chunk than the log holds at that index,
391`alignToStoredLog` throws `JournalReplayDivergedError` with the index and both
392fingerprints. It does not forward the mismatch.
393
394```ts
395import { JournalReplayDivergedError } from '@tanstack/ai-sandbox'
396
397function describe(error: unknown): string {
398 if (error instanceof JournalReplayDivergedError) {
399 return `chunk ${error.index}: stored ${error.stored}, replayed ${error.replayed}`
400 }
401 throw error
402}
403```
404
405Loud failure is the right trade here because the alternative is not degraded
406delivery, it is corrupt delivery: the client has no safety net below its
407offset de-dup, so a duplicate is unsurvivable. A divergence means translation
408stopped being deterministic, which is a bug to fix rather than a condition to
409recover from.
410
411### What determinism does not cover
412
413The guarantee is translator-level: translating the same journal bytes twice
414yields the same chunk sequence.
415
416On `@tanstack/ai-codex` and `@tanstack/ai-claude-code`, the translated stream is
417merged with a second stream carrying host-tool-bridge events from live tool
418execution. Those events do not occur on a replay, and their interleaving with
419translated chunks is timing-dependent in any case. A run that used bridged tools
420can therefore still diverge, and it will say so rather than deliver corrupt
421data.
422
423`grokBuildText`'s git-diff chunks are also outside translation: they are shelled
424out for after the translated stream ends, so they are not reproducible either.
425They are emitted only at the tail of a completing run.
426
427## Journal lifetime
428
429Both files are deleted once the reader observes the exit sentinel, for
430a zero and a non-zero exit alike. A read that ends without a sentinel (the
431consumer stopped, the client went away) deletes nothing: the run may still be
432in flight and every byte may still be needed.
433
434One case needs a sweep. A run that reaches its sentinel with nobody reading its
435journal has no reader to observe the sentinel, so nothing cleans up, and that
436journal would survive until the sandbox does not. `pruneJournals` from
437`@tanstack/ai-sandbox` bounds it: a sweep over the journal directory that deletes
438only the journals whose runs the `RunStore` reports terminal, and keeps
439everything else. Like the run reaper, it is a function your application
440schedules — see [Reaping & Retention](./reaping).
441
442"Until the sandbox does not" is doing real work in that sentence. On a provider
443whose capabilities declare `durableFilesystem: false` — Cloudflare is the
444bundled one — the filesystem holding the journal lives exactly as long as the
445container instance, so the journal's durability is bounded by the container's,
446not by the run's. That is the tier boundary from
447[Durable Runs Explained](./durable-runs): journal-only durability equals
448sandbox lifetime, and outliving the sandbox requires the log-first tier.
449
450## What you can build on this today
451
452- **A run whose host dies keeps working.** The agent has no pipe to lose, and
453 its output is on disk inside the sandbox.
454- **Any process with the sandbox handle and the `runId` can read the whole run
455 back**, from byte 0, with `readJournal`.
456- **Replay against an already-delivered log is exact**, via `alignToStoredLog`,
457 with divergence surfaced rather than swallowed.
458
459And automatic handoff of a live run from one host to another **is** wired up.
460`sandboxRunDriver` drives the alignment primitive for you: a successor claims the
461run under a lease, bumps the run record's fencing epoch so the predecessor can no
462longer append, waits for the stored log to stop growing, replays the journal from
463byte 0 through `alignToStoredLog`, and appends only the remainder.
464
465Do not hand-roll that orchestration. `alignToStoredLog` on its own protects one
466writer against re-appending its own prefix; it does nothing about *two* writers,
467and two hosts appending one log is exactly how the duplicate-delivery corruption
468described above reappears — plus a superseded host writing a terminal status over
469a run its successor is healthily streaming. The lease, the epoch fence on both
470the log and the run record, and the quiescence wait are what close those, and
471they are what the driver gives you. See
472[Takeover & Detached Runs](./takeover).
473
474## See also
475
476- [Durable Runs Explained](./durable-runs): why the output goes to a file at all,
477 in plain language and with no code
478- [Takeover & Detached Runs](./takeover): `sandboxRunDriver`, detach-on-disconnect,
479 and single-writer fencing — the wiring that drives everything on this page
480- [Providers](./providers): the `killableProcesses` capability and the read
481 strategy it selects
482- [Harnesses](./harnesses): which adapters journal, and how they derive `runId`
483- [Resumable Streams (Advanced)](../resumable-streams/advanced): offset
484 ownership and the `snapshot()` read alignment depends on
485- [Custom Durability Adapter](../resumable-streams/custom-adapter): the
486 five-method contract, including `snapshot()`