@tanstack/ai-sandbox
Version:
Provider-agnostic sandbox layer for TanStack AI — run harness adapters inside isolated sandboxes (defineSandbox, defineWorkspace, withSandbox) with a uniform SandboxHandle, workspace bootstrap, policy, and resumable lifecycle.
134 lines (133 loc) • 5.11 kB
JavaScript
import { SandboxSnapshotError, captureSandboxFiles, restoreSandboxFiles } from "./snapshots.js";
import { withWriterLease } from "./snapshot-operations.js";
// src/checkpoints.ts
/**
* Saves the files of a sandbox as a new checkpoint at the head of a thread.
* It works on any `SandboxHandle`, also outside `withSandbox`.
*
* It takes the writer lease of the thread for the full capture. If another
* writer holds the lease, it throws `SandboxCheckpointWriterConflictError`.
* If the head moves during the capture, the store throws
* `SandboxCheckpointConflictError`. A bad file in the sandbox throws
* `SandboxSnapshotError`.
*
* ```ts
* const checkpoint = await captureSandboxCheckpoint({
* handle,
* checkpoints,
* blobs,
* threadId,
* label: 'before-migration',
* })
* ```
*/
async function captureSandboxCheckpoint(input) {
const { handle, checkpoints, blobs, threadId, label, signal } = input;
signal?.throwIfAborted();
return withWriterLease(() => checkpoints.acquireWriter(threadId), true, async (writer, throwIfLost) => {
const files = await captureSandboxFiles(handle, {
blobs,
workspaceRoot: input.workspaceRoot
}, input.policy, input.secrets);
signal?.throwIfAborted();
const head = await checkpoints.getHead(threadId);
signal?.throwIfAborted();
const checkpoint = {
id: input.id ?? `checkpoint-${crypto.randomUUID()}`,
threadId,
parentCheckpointId: head,
createdAt: Date.now(),
reason: label === void 0 ? "automatic" : "named",
...label === void 0 ? {} : { label },
files: files.files,
conversation: input.conversation ?? [],
artifacts: []
};
await throwIfLost();
await checkpoints.append({
checkpoint,
expectedHeadId: head,
writer
});
return checkpoint;
});
}
/**
* Writes the files of a checkpoint into a sandbox. The sandbox can be a new
* one, for example a new container after a crash.
*
* Without `checkpointId`, it restores the head of the thread. When the thread
* has no checkpoint, it returns `null` and does not touch the sandbox.
* When `checkpointId` does not exist or is on another thread, it throws
* `SandboxSnapshotError` with code `SANDBOX_SNAPSHOT_MISSING_CHECKPOINT`.
*
* Restore only into a sandbox that no other process writes to during the
* restore. Files in the folder that are not in the checkpoint are removed.
*
* ```ts
* const restored = await restoreSandboxCheckpoint({
* handle: newHandle,
* checkpoints,
* blobs,
* threadId,
* })
* if (restored === null) {
* // First run of this thread. Nothing to restore.
* }
* ```
*/
async function restoreSandboxCheckpoint(input) {
const { checkpoints, threadId } = input;
const checkpointId = input.checkpointId ?? await checkpoints.getHead(threadId);
if (checkpointId === null) return null;
const checkpoint = await checkpoints.get(checkpointId);
if (checkpoint === null || checkpoint.threadId !== threadId) throw new SandboxSnapshotError("SANDBOX_SNAPSHOT_MISSING_CHECKPOINT", `Checkpoint '${checkpointId}' does not exist on thread '${threadId}'`);
await restoreSandboxFiles(input.handle, {
blobs: input.blobs,
workspaceRoot: input.workspaceRoot
}, checkpoint, input.policy);
return checkpoint;
}
var SWEPT_PREFIXES = ["sandbox-files/", "sandbox-artifacts/"];
/**
* Deletes stored blobs that no checkpoint uses. It looks only at keys under
* `sandbox-files/` and `sandbox-artifacts/`, and returns the deleted keys,
* sorted.
*
* A capture puts its blobs first and appends the checkpoint after. Until the
* append, a new blob has no reference. So the sweep keeps every blob that is
* younger than `olderThanMs`. Make `olderThanMs` longer than your longest
* capture.
*
* A capture does not upload a blob that already exists. So a capture that
* runs during the sweep can use an old blob that the sweep deletes. Run the
* sweep when no capture runs, for example from a nightly job.
*
* Throws `RangeError` when `olderThanMs` is not a finite number of 0 or more.
*
* ```ts
* const deleted = await sweepSandboxBlobs({
* checkpoints,
* blobs: { list: listAllKeys, delete: (key) => bucket.delete(key) },
* olderThanMs: 24 * 60 * 60 * 1000,
* })
* ```
*/
async function sweepSandboxBlobs(input) {
const { checkpoints, blobs, olderThanMs } = input;
if (!(Number.isFinite(olderThanMs) && olderThanMs >= 0)) throw new RangeError("olderThanMs must be a finite number of 0 or more");
const cutoff = (input.now ?? (() => Date.now()))() - olderThanMs;
const listed = await Promise.all(SWEPT_PREFIXES.map(async (prefix) => (await blobs.list(prefix)).filter((blob) => blob.key.startsWith(prefix))));
const references = await checkpoints.listBlobReferences();
const referenced = new Set(references.filter((ref) => ref.references > 0).map((ref) => ref.key));
const deleted = [];
const candidates = listed.flat();
for (const blob of candidates) {
if (!(!referenced.has(blob.key) && blob.uploadedAt <= cutoff)) continue;
await blobs.delete(blob.key);
deleted.push(blob.key);
}
return deleted.sort();
}
export { captureSandboxCheckpoint, restoreSandboxCheckpoint, sweepSandboxBlobs };
//# sourceMappingURL=checkpoints.js.map