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

lifecycle.md

142 lines6.5 KB

1---
2title: Lifecycle & Snapshots
3id: lifecycle
4order: 8
5description: "Control sandbox reuse, snapshot the bootstrapped workspace after setup, and resume across runs to cut cold-start cost."
6---
7​
8Bootstrapping a sandbox (cloning the repo, installing dependencies, running
9`setup`) is the expensive part of a run. The lifecycle config lets you pay that
10cost once and reuse the result: keep one sandbox per thread, snapshot it after
11setup, and resume instead of re-bootstrapping on the next run.
12​
13When you must also recover files after a sandbox is gone, configure
14[Keep Files After Reload](./portable-snapshots-configure). Provider-native
15snapshots make bootstrap faster. Portable snapshots save the completed
16workspace as durable application data.
17​
18```ts
19import { defineSandbox, defineWorkspace, githubRepo } from '@tanstack/ai-sandbox'
20import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
21​
22const sandbox = defineSandbox({
23 id: 'repo-agent',
24 provider: dockerSandbox({ image: 'node:22' }),
25 workspace: defineWorkspace({
26 source: githubRepo({ repo: 'owner/app' }),
27 setup: ['corepack enable', 'pnpm install'],
28 }),
29 lifecycle: {
30 reuse: 'thread', // one sandbox per threadId ('none' = fresh per run)
31 snapshot: 'after-setup', // snapshot once bootstrapped (provider-permitting)
32 keepAlive: '30m', // hint to keep the sandbox warm between runs
33 destroyOnComplete: false, // keep it for the next run
34 },
35})
36```
37​
38## The lifecycle object
39​
40| Field | What it controls |
41| ------------------- | ------------------------------------------------------------------------------------------- |
42| `reuse` | `'thread'` keeps one sandbox per `threadId`; `'none'` provisions a fresh sandbox per run. |
43| `snapshot` | `'after-setup'` snapshots the workspace once bootstrap finishes, on snapshot-capable providers. |
44| `keepAlive` | Duration hint (e.g. `'30m'`) for how long the sandbox should stay warm between runs. Nothing in `@tanstack/ai-sandbox` reads it today; it is a hint for providers and host apps. Provider idle timers live on the [provider](./providers) config. |
45| `destroyOnComplete` | When `false`, the sandbox survives the run so the next one can resume it. |
46| `snapshotMaxAge` | Duration (e.g. `'24h'`) after which a stored snapshot is treated as stale and re-created. |
47​
48### These fields govern *completion*, not cancellation
49​
50`keepAlive` and `destroyOnComplete` describe what happens when a run **finishes**.
51They never keep a sandbox alive through an abort: closing the agent's IO stream
52does not kill the agent process, so an explicit cancel destroys the sandbox
53regardless of `destroyOnComplete`, and that is the only reliable way to stop the
54agent burning tokens.
55​
56A **disconnect** is the third case, and it is not the same as a cancel. A user
57pressing Stop and a user closing the tab produce an identical connection close.
58On a run with durability wired, a disconnect neither completes nor destroys: the
59sandbox stays up, the agent keeps working, and the run record is marked detached
60so a later request can take it over. With no durability wired, a disconnect
61destroys, exactly as an abort does. See
62[Takeover & Detached Runs](./takeover#detach-vs-cancel).
63​
64## Snapshot after setup
65​
66When the provider supports snapshots (see [Providers](./providers)), bootstrap
67automatically takes a snapshot after `setup` completes. The snapshot caches the
68fully bootstrapped [workspace](./workspace) (the cloned repo with dependencies
69installed) so subsequent runs resume from it instead of re-running the setup
70steps, which dramatically reduces cold-start time.
71​
72`snapshot: 'after-setup'` is the default whenever the provider reports snapshot
73support, so you usually do not set it explicitly. Providers without snapshot
74support (e.g. `localProcessSandbox`) skip the snapshot step silently.
75​
76```ts
77import { defineSandbox, defineWorkspace, githubRepo } from '@tanstack/ai-sandbox'
78import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
79​
80const sandbox = defineSandbox({
81 id: 'repo-agent',
82 provider: dockerSandbox({ image: 'node:22' }),
83 workspace: defineWorkspace({
84 source: githubRepo({ repo: 'owner/app' }),
85 setup: ['corepack enable', 'pnpm install'],
86 }),
87 lifecycle: {
88 reuse: 'thread',
89 // 'after-setup' is the default when the provider supports snapshots.
90 snapshot: 'after-setup',
91 // Optional: re-create (re-bootstrap) when the snapshot is older than this.
92 snapshotMaxAge: '24h',
93 },
94})
95```
96​
97### Stale snapshots
98​
99`snapshotMaxAge` accepts a duration string (`'24h'`, `'30m'`, etc.). When the
100stored snapshot is older than the limit, the sandbox treats it as stale and
101re-creates from scratch, re-running setup and capturing a new snapshot. Leave
102it unset to keep snapshots indefinitely.
103​
104## The sandbox instance key
105​
106A sandbox is keyed by a compound `sandboxInstanceKey`:
107​
108```txt
109sandboxInstanceKey = hash(threadId + sandbox.id + provider + workspaceHash + tenant?)
110```
111​
112Because the key folds in the workspace hash, the provider, and an optional
113tenant. Changing any input that would invalidate a cached environment means the
114repo, the `setup` steps, the provider image, or the tenant, produces a
115different key. That means you safely start a **fresh** sandbox rather than
116resuming a stale one whose snapshot no longer matches your config. Keep those
117inputs stable across runs to keep hitting the same warm sandbox.
118​
119## Ensure order
120​
121When a run needs a sandbox, the layer resolves it in this order:
122​
1231. **Resume the running sandbox**, if a live sandbox already exists for the key.
1242. **Restore the latest snapshot**, recreate from the most recent snapshot,
125 skipping setup.
1263. **Create fresh and bootstrap**, clone, install, run `setup`, then snapshot.
127​
128Each step falls through to the next only when the prior one is unavailable. This
129is what turns a warm thread into a near-instant start, and a cold one into a
130full bootstrap.
131​
132Portable sandbox snapshots run after this lifecycle work. They restore a saved
133workspace only into a newly created private sandbox. They never overwrite a
134live resumed sandbox. See [Portable Snapshots](./portable-snapshots).
135​
136> Which providers support durable disk, snapshots, and resume-by-id is listed on
137> [Providers](./providers).
138​
139Providers without durable disk or snapshots (e.g. ephemeral containers)
140re-create and re-bootstrap under the same identity: the `sandboxInstanceKey`
141stays stable, but every run pays the bootstrap cost because there is nothing
142durable to resume.