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

lifecycle.md

90 lines5.2 KB

1---
2title: Lifecycle & Snapshots
3id: lifecycle
4order: 8
5description: "Reuse one sandbox per thread, snapshot the workspace after setup, and resume on the next run, so only the first run pays the cold-start cost."
6---
7​
8Reuse a sandbox across messages in a thread. A new sandbox clones the repo, installs dependencies, and runs `setup` again.
9​
10The `lifecycle` config lets you pay it once. Keep one sandbox per thread, take a snapshot after setup, and resume on the next run.
11​
12## Reuse a sandbox
13​
14Add `lifecycle` to `defineSandbox`:
15​
16```ts
17import { defineSandbox, defineWorkspace, githubRepo } from '@tanstack/ai-sandbox'
18import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
19​
20export const sandbox = defineSandbox({
21 id: 'repo-agent',
22 provider: dockerSandbox({ image: 'node:22' }),
23 workspace: defineWorkspace({
24 source: githubRepo({ repo: 'owner/app' }),
25 setup: ['corepack enable', 'pnpm install'],
26 }),
27 lifecycle: {
28 reuse: 'thread', // one sandbox per threadId
29 snapshot: 'after-setup', // snapshot once bootstrap is done
30 snapshotMaxAge: '24h', // make a new one when the snapshot is older
31 destroyOnComplete: false, // keep the sandbox for the next run
32 },
33})
34```
35​
36Pass the same `threadId` to `chat()` on each run. The first run bootstraps. Later runs resume the sandbox or restore the snapshot, and skip setup.
37​
38## The lifecycle fields
39​
40| Field | What it controls |
41| --- | --- |
42| `reuse` | `'thread'` (default) keeps one sandbox per `threadId`. `'none'` makes a fresh sandbox for each run. |
43| `snapshot` | `'after-setup'` takes a snapshot when bootstrap ends. `'after-run'` takes one when a run completes. `'none'` takes no snapshot. The default is `'after-setup'` when the provider supports snapshots, else `'none'`. |
44| `snapshotMaxAge` | A duration such as `'24h'` or `'30m'`. An older record is treated as stale and created again. |
45| `destroyOnComplete` | When `true`, the sandbox is destroyed after the run completes. When `false` (default), the next run can resume it. |
46| `keepAlive` | A duration hint such as `'30m'`, for how long to keep the sandbox warm. `@tanstack/ai-sandbox` does not read it. It is a hint for providers and host apps. Provider idle timers are on the [provider](./providers-advanced) config. |
47​
48## How it works
49​
50When a run needs a sandbox, `withSandbox` tries these in order:
51​
521. **Resume the running sandbox**, if a live one exists for this key.
532. **Restore the latest snapshot**, and skip setup.
543. **Create a fresh sandbox and bootstrap it**: clone, install, run `setup`, then take a snapshot.
55​
56Each step falls through to the next only when it is not available. A warm thread starts almost at once. A cold one does the full bootstrap.
57​
58Providers without snapshot support (for example `localProcessSandbox`) skip the snapshot step with no error. Providers without a durable disk or snapshots create and bootstrap again on every run. See [Providers (Advanced)](./providers-advanced) for what each provider supports.
59​
60> [!NOTE]
61> Provider snapshots make bootstrap faster. To keep the finished files after the sandbox is gone, use [Keep Files After Reload](./portable-snapshots-configure). Portable snapshots restore only into a new private sandbox, after the steps above. They never overwrite a live resumed sandbox.
62​
63## Advanced
64​
65### Stale snapshots
66​
67`snapshotMaxAge` takes `'<n>h'` (hours) or `'<n>m'` (minutes). When the stored record is older than this limit, the sandbox is treated as stale. It is created from scratch: setup runs again, and a new snapshot is taken. If you leave it unset, snapshots stay forever.
68​
69### The sandbox instance key
70​
71A sandbox is found by a compound key:
72​
73```txt
74sandboxInstanceKey = hash(threadId + sandbox.id + provider + workspaceHash + tenant?)
75```
76​
77The key includes the workspace hash, the provider name, and an optional tenant. So if you change the repo, the `setup` steps, the provider, or the tenant, you get a different key. Provider options such as the image are not in the key. If you change the image, also change `sandbox.id` to get a fresh sandbox. That starts a **fresh** sandbox, and you never resume a stale one that does not match your config. Keep those inputs the same across runs to keep hitting the same warm sandbox.
78​
79Providers without a durable disk or snapshots (for example ephemeral containers) keep the same key. But every run pays the bootstrap cost, because there is nothing durable to resume.
80​
81### Completion, cancel, and disconnect
82​
83`keepAlive` and `destroyOnComplete` apply when a run **completes**. They never keep a sandbox alive through an abort.
84​
85- **Cancel:** closing the agent's IO stream does not stop the agent process. So an explicit cancel always destroys the sandbox, whatever `destroyOnComplete` says. That is the only sure way to stop the agent from spending tokens.
86- **Disconnect:** Stop and a closed tab look the same to the server: the connection closes.
87 - With durability wired, a disconnect does not complete or destroy anything. The sandbox stays up, the agent keeps working, and the run record is marked detached. A later request can take it over.
88 - With no durability wired, a disconnect destroys the sandbox, the same as an abort.
89​
90See [Takeover & Detached Runs](./takeover#detach-vs-cancel) and [Durable Runs](./durable-runs).