If every agent run starts with pip install -r requirements.txt or npm ci, you pay for that install on every run, and every run needs network access to a package index. Both are avoidable. Install once, save the result, and start each run from it.
Sandscale’s mechanism for this is the snapshot. The snapshots guide says a snapshot is an archive of a sandbox’s /workspace, checked end to end. A new sandbox created with snapshotId starts with the snapshot’s files. Nothing mounted into the workspace is included, so runtime secrets are never in a snapshot.
The one rule: put everything in /workspace
A snapshot contains /workspace and nothing else. Packages installed into the system Python’s site-packages, or a global node_modules, are not in it. So:
- Python: create a virtualenv under
/workspace(here/workspace/.venv) and install into it. - Node: keep the project in
/workspace/app, sonpm ciputsnode_modulesthere. - Caches you want kept, such as a build cache, also go under
/workspace.
The code
Type-checked with tsc --strict against @sandscale/sdk 1.0. The calls are sandboxes.create, run, writeFile, snapshot, snapshots.get and stop from the TypeScript SDK reference.
import { Sandscale } from '@sandscale/sdk';
const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function sh(id: string, region: string | undefined, command: string, timeoutSeconds = 600) {
const r = await sandscale.sandboxes.run(id, ['bash', '-lc', command], {
region,
workdir: '/workspace/app',
timeoutSeconds,
});
if (r.exitCode !== 0 || r.timedOut) {
throw new Error(`"${command}" failed (exit ${r.exitCode}${r.timedOut ? ', timed out' : ''}):\n${r.stderr.slice(-2_000)}`);
}
return r.stdout;
}
// Run once (or whenever the lockfile changes): install dependencies, then snapshot /workspace.
export async function prepareBase(files: Record<string, string>, label: string) {
const prep = await sandscale.sandboxes.create({
template: 'builtin:python',
network: 'allowlist', // the package index must be on your organization's allowlist
timeoutSeconds: 1800,
labels: { app: 'base-prep' },
});
const region = prep.region;
try {
await sandscale.sandboxes.run(prep.id, ['mkdir', '-p', '/workspace/app'], { region });
for (const [path, content] of Object.entries(files)) {
await sandscale.sandboxes.writeFile(prep.id, `/workspace/app/${path}`, content, { region });
}
// Only /workspace is in a snapshot, so the virtualenv must live there too.
await sh(prep.id, region, 'python3 -m venv /workspace/.venv');
await sh(prep.id, region, '/workspace/.venv/bin/pip install --no-input -r requirements.txt');
let snap = await sandscale.sandboxes.snapshot(prep.id, { region, label });
while (snap.status === 'creating') {
await sleep(2_000);
snap = await sandscale.snapshots.get(snap.id, { region });
}
if (snap.status !== 'ready') throw new Error(`snapshot ${snap.id} ${snap.status}: ${snap.failure ?? ''}`);
return snap;
} finally {
await sandscale.sandboxes.stop(prep.id, { region });
}
}
// Every agent run: start from the snapshot, with no network.
export async function runTask(snapshotId: string, command: string) {
const sb = await sandscale.sandboxes.create({
snapshotId,
timeoutSeconds: 1800,
labels: { app: 'agent-run' },
});
try {
return await sh(sb.id, sb.region, `source /workspace/.venv/bin/activate && ${command}`, 900);
} finally {
await sandscale.sandboxes.stop(sb.id, { region: sb.region });
}
}
Step by step
Prepare in a sandbox with network, run without. prepareBase creates its sandbox with network: 'allowlist', which uses your organization’s egress allowlist where your plan includes it, so pip can reach the package index. Agent runs created by runTask pass no network, so they get the default, none. The dependencies are already there; the agent does not need the internet, and is safer without it.
Fail loudly while preparing. The sh helper throws on a nonzero exit or a timeout, with the end of stderr. A snapshot of a half-installed environment is worse than no snapshot.
Wait for ready. sandboxes.snapshot returns a Snapshot whose status may be creating. The code polls snapshots.get until it is ready, and throws with the failure message if it ends up failed.
Stop the prep sandbox. Once the snapshot is ready, the prep box has done its job. Sandboxes started from a snapshot do not depend on the sandbox it came from.
Start runs from the snapshot. sandboxes.create({ snapshotId }) gives each run a fresh sandbox with the prepared files. Fresh processes, same files: unlike a memory snapshot, nothing like random number generator state is shared between runs. MicroVM snapshot pitfalls explains why that matters.
Check the interpreter once. The virtualenv points at the Python it was created with. After you prepare a new base, run python3 --version in a sandbox started from the snapshot and compare it with the prep sandbox, so a mismatch shows up in your pipeline rather than in an agent run.
When to rebuild
Rebuild when the lockfile changes. A simple scheme: label the snapshot with a hash of requirements.txt or package-lock.json, keep the snapshot id in your config keyed by that hash, and prepare a new one when the hash changes. sandboxes.listSnapshots lists the snapshots of one sandbox, and snapshots.list returns your organization’s snapshots with how much of the snapshot quota is used.
Retention, quotas and storage
- The guide says snapshots work within your organization’s snapshot policy: whether they are on, how many, how large, and how long they are kept. Snapshots past retention are deleted for you; a
Snapshothas anexpiresAtwhen one applies. snapshots.deleteremoves one; sandboxes already started from it keep running.- The plans reference says the first 10 GB of snapshots and templates is free; above your plan’s storage allowance, paid plans pay $0.15 per GB-month.
A named template from a snapshot
If many services or teams start from the same base, templates.create({ name, snapshotId }) creates an organization template from the snapshot, so people can start from it by name.
When not to use a snapshot
If each run needs a different repository, a snapshot of one repository does not help; consider a snapshot of the toolchain only, with the repository uploaded per run. And if a run must start from the exact in-memory state of a previous one, such as a conversation’s running interpreter, use pause and resume on that one sandbox instead.