Open History to see the last commit
1---
2title: The Run Journal (Advanced)
3id: sandbox-journal
4order: 12
5description: "A sandboxed agent writes its output to a file inside the sandbox, not to a pipe. If your server dies during a run, any other server can read the whole run back from that file."
6keywords:
7 - run journal
8 - readJournal
9 - journalPaths
10 - alignToStoredLog
11 - killableProcesses
12 - exitSentinelLine
13 - awaitAttachableJournal
14 - journal-stalled
15---
16
17The run journal writes each agent event to disk. A new server can read that log after the process that held the pipe exits.
18
19Any server with the sandbox handle and the run id can read the whole run again, from the first byte.
20
21## Turn on the journal
22
231. Pass both `runs` and `durability` to `withSandbox`. With only one of them, or neither, there is no journal and nothing warns you.
242. Forward the `runId` from the request to `chat()`. The journal path comes from it. Without it, a non-durable run gets a random id that no other server can compute.
253. Give the same durability adapter to the middleware and to the response.
26
27```ts
28import {
29 chat,
30 chatParamsFromRequest,
31 memoryStream,
32 toServerSentEventsResponse,
33} from '@tanstack/ai'
34import { claudeCodeText } from '@tanstack/ai-claude-code'
35import { memoryPersistence } from '@tanstack/ai-persistence'
36import {
37 createSecrets,
38 defineSandbox,
39 defineWorkspace,
40 githubRepo,
41 withSandbox,
42} from '@tanstack/ai-sandbox'
43import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
44
45// Local dev only. In production, every replica must reach the same stores.
46// See ./takeover for the production wiring.
47const { runs } = memoryPersistence().stores
48
49const sandbox = defineSandbox({
50 id: 'repo-agent',
51 provider: dockerSandbox({ image: 'node:22' }),
52 workspace: defineWorkspace({
53 source: githubRepo({ repo: 'owner/app' }),
54 setup: [
55 'npm install -g @anthropic-ai/claude-code --include=optional && claude --version',
56 ],
57 secrets: createSecrets({
58 ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY ?? '',
59 }),
60 }),
61})
62
63export async function POST(request: Request) {
64 const { messages, threadId, runId } = await chatParamsFromRequest(request)
65 // One adapter for the middleware and the response, so the journal and the
66 // delivery log describe the same run.
67 const adapter = memoryStream(request)
68
69 const stream = chat({
70 adapter: claudeCodeText('claude-opus-4-8'),
71 messages,
72 threadId,
73 // Required. A durable run without it throws DurableRunIdRequiredError.
74 runId,
75 // Both options, or there is no journal.
76 middleware: [withSandbox(sandbox, { runs, durability: { adapter } })],
77 })
78
79 return toServerSentEventsResponse(stream, { durability: { adapter } })
80}
81```
82
834. On the client, add nothing. `useChat` sends a new `runId` for every run, and `chatParamsFromRequest` reads it.
84
85```tsx
86import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
87
88export function Chat() {
89 const { messages, sendMessage } = useChat({
90 connection: fetchServerSentEvents('/api/chat'),
91 threadId: 'support-chat',
92 })
93
94 return (
95 <button onClick={() => sendMessage('Refactor the auth module')}>
96 Send ({messages.length} messages)
97 </button>
98 )
99}
100```
101
102Send a message. While the agent works, its output is in `/tmp/tanstack-runs/<runId>.ndjson` inside the sandbox.
103
104> [!WARNING]
105> Never reuse a `runId`. The journal is append-only, so a reused id appends to the old run's file. The second run then looks empty, or looks like it failed with the old exit code. Nothing throws. See [A runId must be unique per run](./journal-advanced#a-runid-must-be-unique-per-run).
106
107## How it works
108
109Each run gets two files in `/tmp/tanstack-runs`:
110
111- `<runId>.ndjson`: every NDJSON event the agent prints.
112- `<runId>.err`: the agent's stderr, kept separate so a CLI banner never mixes into the events.
113
114The agent writes to a file, not a pipe. So when your server goes away, no reader disappears, and nothing sends the agent a `SIGPIPE`. The agent keeps working.
115
116When the agent exits, the shell appends one exit line (the sentinel) to the journal. A reader that sees the sentinel knows the run is over, and it deletes both files.
117
118Every read starts at a byte offset. A fresh read starts at 0. A read on another server, five minutes later, is the same call. [Takeover & Detached Runs](./takeover) builds on this. A new server reads the journal from byte 0, and it streams only what the client has not seen.
119
120## Go deeper
121
122To read a journal yourself, handle stalled reads, seed sentinels, or replay against a stored log, see [Run Journal Internals](./journal-advanced).