UNPKG

@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.

319 lines (318 loc) • 13.5 kB
import { ModelMessage } from '@tanstack/ai'; export interface SandboxSnapshotFileEntry { path: string; kind: 'file'; blobKey: string; size: number; /** Permission bits of the file (`mode & 0o777`). Old snapshots have none. */ mode?: number; } export interface SandboxSnapshotDirectoryEntry { path: string; kind: 'dir'; } /** A symbolic link. `target` is the link text as `readlink` gives it. */ export interface SandboxSnapshotSymlinkEntry { path: string; kind: 'symlink'; target: string; } export type SandboxSnapshotEntry = SandboxSnapshotFileEntry | SandboxSnapshotDirectoryEntry | SandboxSnapshotSymlinkEntry; export interface SandboxSnapshotArtifact { artifactId: string; name: string; mimeType: string; size: number; blobKey: string; createdAt: number; } export interface SandboxCheckpoint { id: string; threadId: string; parentCheckpointId: string | null; createdAt: number; reason: 'automatic' | 'named' | 'fork-root'; label?: string; sourceRunId?: string; files: ReadonlyArray<SandboxSnapshotEntry>; conversation: ReadonlyArray<ModelMessage>; artifacts: ReadonlyArray<SandboxSnapshotArtifact>; } /** * Stores the checkpoints of each thread, the head of each thread, the writer * leases, and a reference count for each blob key. * * Implement it against your own storage. For example, keep manifests, heads, * leases and counts in SQL, and keep blob bytes in R2. The store only counts * blob references. It never reads or deletes blob bytes. * * Rules for every method: * * - A thread is a chain. Each checkpoint points to its parent with * `parentCheckpointId`. The head is the newest checkpoint of the chain. * - Checkpoint ids are unique across all threads. * - A stored checkpoint never changes. Reads return copies. A change to a * returned value does not change the store. * - Thread ids and checkpoint ids are non-empty, well-formed Unicode strings. * Other values throw `SandboxCheckpointInvalidIdError`. * - A write is all or nothing. Do the checks and the write in one * transaction. When a write throws, the store does not change. * - A write checks its writer first. `writer.threadId` must be the thread of * the write, and the lease must be current. Else the write throws * `SandboxCheckpointWriterLostError`. * * Prove an implementation with `runSandboxCheckpointStoreConformance` from * `@tanstack/ai-sandbox/testkit`. */ export interface SandboxCheckpointStore { /** * Returns the checkpoint with this id, or `null` when there is none. * A missing id does not throw. */ get: (id: string) => Promise<SandboxCheckpoint | null>; /** * Returns all checkpoints of the thread, also the ones that are not on the * head chain. Sort by `createdAt` (oldest first), then by the UTF-8 bytes * of the id. An unknown thread returns `[]`. */ list: (threadId: string) => Promise<Array<SandboxCheckpoint>>; /** Returns the head id of the thread, or `null` when it has no head. */ getHead: (threadId: string) => Promise<string | null>; /** * Adds a checkpoint and makes it the head, as one compare-and-swap. * * Checks, in this order (each one throws and changes nothing): * * 1. Ids are valid: `SandboxCheckpointInvalidIdError`. * 2. `files`, `artifacts` and a finite `createdAt` are valid: * `SandboxCheckpointInvalidEntryError`. * 3. The writer is current: `SandboxCheckpointWriterLostError`. * 4. The id is not used in any thread: `SandboxCheckpointDuplicateIdError`. * 5. The current head is `expectedHeadId` (`null` for an empty thread): * `SandboxCheckpointConflictError`. * 6. `parentCheckpointId` is `expectedHeadId`. A missing parent id counts as * `null`: `SandboxCheckpointParentMismatchError`. * * Then add 1 to the count of each distinct blob key of the checkpoint. The * keys are the `blobKey` of each `file` entry and of each artifact. * Directories and symlinks have no blob. */ append: (input: { checkpoint: SandboxCheckpoint; expectedHeadId: string | null; writer: SandboxCheckpointWriter; }) => Promise<{ headId: string; }>; /** * Removes the head checkpoint of the thread. * * The writer must be current. `checkpointId` must be the current head, else * it throws `SandboxCheckpointNotHeadError`. The head moves to the * `parentCheckpointId` of the removed checkpoint. The thread has no head * when that is `null`, or when that checkpoint was removed by * `deleteCheckpoints`. Subtract 1 from the count of each distinct blob key of * the removed checkpoint. Forget a key when its count gets to 0. */ deleteHead: (input: { threadId: string; checkpointId: string; writer: SandboxCheckpointWriter; }) => Promise<void>; /** * Takes the writer lease of the thread. It does not wait. * * When an unexpired lease exists, it throws * `SandboxCheckpointWriterConflictError`. An expired lease can be taken * over. Each new lease gets a new `ownerToken` and a `fence` that is higher * than all earlier fences of the thread. Each thread has its own lease. */ acquireWriter: (threadId: string) => Promise<SandboxCheckpointWriterLease>; /** * Returns each blob key with a count above 0, for all threads. Sort by the * UTF-8 bytes of the key. Do not return keys with a count of 0. * * The count is the number of stored checkpoints that use the key. A * checkpoint that uses a key two times counts one time. A blob sweep * deletes only the blobs that are not in this list. */ listBlobReferences: () => Promise<Array<{ key: string; references: number; }>>; /** * Optional. Copies one checkpoint into a new, empty thread as its root, in * one transaction. Stores without this method cannot fork. * * The new checkpoint has `reason: 'fork-root'` and `parentCheckpointId: * null`. It becomes the head of the new thread, and its blob keys get 1 * more reference. The writer must be the current writer of the destination * thread. Errors are `SandboxCheckpointError` with these codes: * * - `SANDBOX_SNAPSHOT_FORK_SOURCE_NOT_FOUND`: no source checkpoint. * - `SANDBOX_SNAPSHOT_FORK_SOURCE_THREAD_MISMATCH`: the source is in another * thread, or source and destination are the same thread. * - `SANDBOX_SNAPSHOT_FORK_DESTINATION_NOT_EMPTY`: the destination thread * already has data, or the new id is used. * * Prove it with `runSandboxCheckpointForkConformance` from * `@tanstack/ai-sandbox/testkit`. */ forkFromCheckpoint?: SandboxCheckpointForkCapability['forkFromCheckpoint']; /** * Optional. Removes old checkpoints of a thread so that `keep` checkpoints * stay: the head and the newest ones before it. * * - `keep` is a safe integer of 1 or more. Else it throws * `SandboxCheckpointInvalidEntryError`. * - The writer is checked like in `deleteHead`. * - "Newest" follows the parent chain from the head, not `createdAt`. * - Checkpoints of the thread that are not on the head chain stay as they * are. * - For each removed checkpoint, subtract its blob references like * `deleteHead` does. * - The oldest kept checkpoint keeps its `parentCheckpointId`. That id can * point to a removed checkpoint, and `get` returns `null` for it. A * later `deleteHead` of that checkpoint leaves the thread with no head. * - Remove all of them in one transaction, or none. * * Returns the removed ids, oldest first. A thread with `keep` or fewer * checkpoints on its chain returns `{ deleted: [] }`. */ deleteCheckpoints?: (input: { threadId: string; keep: number; writer: SandboxCheckpointWriter; }) => Promise<{ deleted: Array<string>; }>; } export interface SandboxCheckpointForkInput { sourceThreadId: string; sourceCheckpointId: string; destinationThreadId: string; destinationCheckpointId: string; createdAt: number; writer: SandboxCheckpointWriter; } export interface SandboxCheckpointForkCapability { forkFromCheckpoint: (input: SandboxCheckpointForkInput) => Promise<{ checkpoint: SandboxCheckpoint; }>; } export type ForkCapableSandboxCheckpointStore = SandboxCheckpointStore & SandboxCheckpointForkCapability; export declare function isForkCapableSandboxCheckpointStore(store: SandboxCheckpointStore): store is ForkCapableSandboxCheckpointStore; /** * Proof that the caller holds the writer lease of a thread. Each write sends * it. The store compares all three fields with the current lease. */ export interface SandboxCheckpointWriter { /** The thread that this lease guards. */ threadId: string; /** A new random value for each `acquireWriter` call. */ ownerToken: string; /** * Goes up by at least 1 for each new lease of the thread. A write with an * older fence throws `SandboxCheckpointWriterLostError`. */ fence: number; } /** The lease that `acquireWriter` returns. */ export interface SandboxCheckpointWriterLease extends SandboxCheckpointWriter { /** * Epoch ms (store clock) when the lease ends. At or after this time, writes * with it throw `SandboxCheckpointWriterLostError`, and another caller can * take a new lease. */ expiresAt: number; /** Call `renew` after this many ms. It is less than the lease duration. */ renewAfterMs: number; /** * Moves `expiresAt` to now plus the lease duration. Throws * `SandboxCheckpointWriterLostError` when the lease expired or was replaced. */ renew: () => Promise<{ expiresAt: number; }>; /** * Ends the lease. It does nothing when the lease is not the current one * (a newer lease replaced it). It does not throw. */ release: () => Promise<void>; } export interface SandboxCheckpointStoreOptions { now?: () => number; leaseDurationMs?: number; renewAfterMs?: number; } export type SandboxCheckpointErrorCode = 'SANDBOX_SNAPSHOT_STALE_HEAD' | 'SANDBOX_SNAPSHOT_PARENT_MISMATCH' | 'SANDBOX_SNAPSHOT_DUPLICATE_ID' | 'SANDBOX_SNAPSHOT_NOT_HEAD' | 'SANDBOX_SNAPSHOT_WRITER_CONFLICT' | 'SANDBOX_SNAPSHOT_WRITER_LOST' | 'SANDBOX_SNAPSHOT_INVALID_ID' | 'SANDBOX_SNAPSHOT_INVALID_ENTRY' | 'SANDBOX_SNAPSHOT_CHECKPOINT_NOT_FOUND' | 'SANDBOX_SNAPSHOT_ATOMIC_FORK_REQUIRED' | 'SANDBOX_SNAPSHOT_FORK_SOURCE_NOT_FOUND' | 'SANDBOX_SNAPSHOT_FORK_SOURCE_THREAD_MISMATCH' | 'SANDBOX_SNAPSHOT_FORK_DESTINATION_NOT_EMPTY'; export declare class SandboxCheckpointError extends Error { readonly code: SandboxCheckpointErrorCode; constructor(code: SandboxCheckpointErrorCode, message: string); } export declare class SandboxCheckpointConflictError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointDuplicateIdError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointInvalidIdError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointInvalidEntryError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointParentMismatchError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointNotHeadError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointWriterConflictError extends SandboxCheckpointError { constructor(message: string); } export declare class SandboxCheckpointWriterLostError extends SandboxCheckpointError { constructor(message: string); } export declare function defineSandboxCheckpointStore(store: SandboxCheckpointStore): SandboxCheckpointStore; /** * Checks the `files` of a checkpoint before a store keeps it. * Throws `SandboxCheckpointInvalidEntryError` for a bad entry. */ export declare function validateEntries(checkpoint: SandboxCheckpoint): void; export declare class InMemorySandboxCheckpointStore implements SandboxCheckpointStore { private readonly state; private readonly now; private readonly leaseDurationMs; private readonly renewAfterMs; constructor(options?: SandboxCheckpointStoreOptions); get(id: string): Promise<SandboxCheckpoint | null>; list(threadId: string): Promise<Array<SandboxCheckpoint>>; getHead(threadId: string): Promise<string | null>; append(input: { checkpoint: SandboxCheckpoint; expectedHeadId: string | null; writer: SandboxCheckpointWriter; }): Promise<{ headId: string; }>; deleteHead(input: { threadId: string; checkpointId: string; writer: SandboxCheckpointWriter; }): Promise<void>; deleteCheckpoints(input: { threadId: string; keep: number; writer: SandboxCheckpointWriter; }): Promise<{ deleted: string[]; }>; private releaseReferences; acquireWriter(threadId: string): Promise<SandboxCheckpointWriterLease>; private assertWriter; listBlobReferences(): Promise<Array<{ key: string; references: number; }>>; }