@tanstack/ai-sandbox 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +26 -0
  2. package/dist/esm/checkpoint-store.d.ts +147 -0
  3. package/dist/esm/checkpoint-store.js +267 -0
  4. package/dist/esm/checkpoint-store.js.map +1 -0
  5. package/dist/esm/contracts.d.ts +19 -0
  6. package/dist/esm/index.d.ts +11 -1
  7. package/dist/esm/index.js +12 -7
  8. package/dist/esm/memory-snapshot-types.d.ts +129 -0
  9. package/dist/esm/memory-snapshots.d.ts +6 -0
  10. package/dist/esm/memory-snapshots.js +490 -0
  11. package/dist/esm/memory-snapshots.js.map +1 -0
  12. package/dist/esm/middleware.d.ts +33 -1
  13. package/dist/esm/middleware.js +339 -94
  14. package/dist/esm/middleware.js.map +1 -1
  15. package/dist/esm/ngrok.d.ts +1 -1
  16. package/dist/esm/sandbox.d.ts +16 -0
  17. package/dist/esm/sandbox.js +62 -9
  18. package/dist/esm/sandbox.js.map +1 -1
  19. package/dist/esm/snapshot-operations.d.ts +65 -0
  20. package/dist/esm/snapshot-operations.js +317 -0
  21. package/dist/esm/snapshot-operations.js.map +1 -0
  22. package/dist/esm/snapshot-tools.d.ts +185 -0
  23. package/dist/esm/snapshot-tools.js +160 -0
  24. package/dist/esm/snapshot-tools.js.map +1 -0
  25. package/dist/esm/snapshots.d.ts +51 -0
  26. package/dist/esm/snapshots.js +350 -0
  27. package/dist/esm/snapshots.js.map +1 -0
  28. package/dist/esm/testkit/checkpoint-conformance.d.ts +2 -0
  29. package/dist/esm/testkit/checkpoint-conformance.js +453 -0
  30. package/dist/esm/testkit/checkpoint-conformance.js.map +1 -0
  31. package/dist/esm/testkit/checkpoint-fork-conformance.d.ts +18 -0
  32. package/dist/esm/testkit/checkpoint-fork-conformance.js +191 -0
  33. package/dist/esm/testkit/checkpoint-fork-conformance.js.map +1 -0
  34. package/dist/esm/testkit/conformance.d.ts +4 -0
  35. package/dist/esm/testkit/conformance.js +3 -1
  36. package/dist/esm/testkit/conformance.js.map +1 -1
  37. package/package.json +8 -3
  38. package/skills/ai-sandbox/SKILL.md +96 -8
  39. package/src/checkpoint-store.ts +652 -0
  40. package/src/contracts.ts +12 -0
  41. package/src/index.ts +56 -0
  42. package/src/memory-snapshot-types.ts +167 -0
  43. package/src/memory-snapshots.ts +936 -0
  44. package/src/middleware.ts +610 -160
  45. package/src/sandbox.ts +107 -6
  46. package/src/snapshot-operations.ts +540 -0
  47. package/src/snapshot-tools.ts +208 -0
  48. package/src/snapshots.ts +711 -0
  49. package/src/testkit/checkpoint-conformance.ts +472 -0
  50. package/src/testkit/checkpoint-fork-conformance.ts +299 -0
  51. package/src/testkit/conformance.ts +7 -0
@@ -0,0 +1,129 @@
1
+ import { ModelMessage, RunRecord, RunStatus, RunStore, PersistedArtifactRef, TokenUsage } from '@tanstack/ai';
2
+ export interface MemoryMessageStore {
3
+ loadThread: (threadId: string) => Promise<Array<ModelMessage>>;
4
+ saveThread: (threadId: string, messages: Array<ModelMessage>) => Promise<void>;
5
+ }
6
+ export type MemoryRunRecord = RunRecord;
7
+ export type MemoryRunStore = RunStore;
8
+ export interface MemoryGenerationRunRecord {
9
+ runId: string;
10
+ threadId: string;
11
+ activity: string;
12
+ provider: string;
13
+ model: string;
14
+ status: RunStatus;
15
+ startedAt: number;
16
+ finishedAt?: number;
17
+ error?: {
18
+ message: string;
19
+ code?: string;
20
+ };
21
+ result?: unknown;
22
+ artifacts?: Array<PersistedArtifactRef>;
23
+ usage?: TokenUsage;
24
+ }
25
+ export interface MemoryGenerationRunStore {
26
+ createOrResume: (input: Pick<MemoryGenerationRunRecord, 'runId' | 'threadId' | 'activity' | 'provider' | 'model' | 'startedAt'> & {
27
+ status?: RunStatus;
28
+ }) => Promise<MemoryGenerationRunRecord>;
29
+ update: (runId: string, patch: Partial<Pick<MemoryGenerationRunRecord, 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'>>) => Promise<void>;
30
+ get: (runId: string) => Promise<MemoryGenerationRunRecord | null>;
31
+ findLatestForThread: (threadId: string) => Promise<MemoryGenerationRunRecord | null>;
32
+ }
33
+ export interface MemoryInterruptRecord {
34
+ interruptId: string;
35
+ runId: string;
36
+ threadId: string;
37
+ status: 'pending' | 'resolved' | 'cancelled';
38
+ requestedAt: number;
39
+ resolvedAt?: number;
40
+ payload: Record<string, unknown>;
41
+ response?: unknown;
42
+ }
43
+ export interface MemoryInterruptStore {
44
+ create: (record: Omit<MemoryInterruptRecord, 'status' | 'resolvedAt'>) => Promise<void>;
45
+ resolve: (interruptId: string, response?: unknown) => Promise<void>;
46
+ cancel: (interruptId: string) => Promise<void>;
47
+ get: (interruptId: string) => Promise<MemoryInterruptRecord | null>;
48
+ list: (threadId: string) => Promise<Array<MemoryInterruptRecord>>;
49
+ listPending: (threadId: string) => Promise<Array<MemoryInterruptRecord>>;
50
+ listByRun: (runId: string) => Promise<Array<MemoryInterruptRecord>>;
51
+ listPendingByRun: (runId: string) => Promise<Array<MemoryInterruptRecord>>;
52
+ }
53
+ export interface MemoryMetadataStore {
54
+ get: (namespace: string, key: string) => Promise<unknown | null>;
55
+ set: (namespace: string, key: string, value: unknown) => Promise<void>;
56
+ delete: (namespace: string, key: string) => Promise<void>;
57
+ }
58
+ export interface MemoryArtifactRecord {
59
+ artifactId: string;
60
+ runId: string;
61
+ threadId: string;
62
+ blobKey?: string;
63
+ name: string;
64
+ mimeType: string;
65
+ size: number;
66
+ sourceUrl?: string;
67
+ createdAt: number;
68
+ }
69
+ export interface MemoryArtifactStore {
70
+ save: (record: MemoryArtifactRecord) => Promise<void>;
71
+ get: (artifactId: string) => Promise<MemoryArtifactRecord | null>;
72
+ list: (runId: string) => Promise<Array<MemoryArtifactRecord>>;
73
+ listForThread: (threadId: string) => Promise<Array<MemoryArtifactRecord>>;
74
+ delete: (artifactId: string) => Promise<void>;
75
+ deleteForRun: (runId: string) => Promise<void>;
76
+ }
77
+ export type MemoryBlobBody = ReadableStream<Uint8Array> | ArrayBuffer | ArrayBufferView | string | Blob;
78
+ export interface MemoryBlobRecord {
79
+ key: string;
80
+ size?: number;
81
+ etag?: string;
82
+ contentType?: string;
83
+ customMetadata?: Record<string, string>;
84
+ createdAt?: number;
85
+ updatedAt?: number;
86
+ }
87
+ export interface MemoryBlobStore {
88
+ put: (key: string, body: MemoryBlobBody, options?: {
89
+ contentType?: string;
90
+ customMetadata?: Record<string, string>;
91
+ expectedLength?: number;
92
+ }) => Promise<MemoryBlobRecord>;
93
+ get: (key: string, options?: {
94
+ range?: {
95
+ offset: number;
96
+ length?: number;
97
+ };
98
+ }) => Promise<(MemoryBlobRecord & {
99
+ arrayBuffer: () => Promise<ArrayBuffer>;
100
+ text: () => Promise<string>;
101
+ body?: ReadableStream<Uint8Array>;
102
+ range?: {
103
+ offset: number;
104
+ length: number;
105
+ };
106
+ }) | null>;
107
+ head: (key: string) => Promise<MemoryBlobRecord | null>;
108
+ delete: (key: string) => Promise<void>;
109
+ list: (options?: {
110
+ prefix?: string;
111
+ cursor?: string;
112
+ limit?: number;
113
+ }) => Promise<{
114
+ objects: Array<MemoryBlobRecord>;
115
+ cursor?: string;
116
+ truncated?: boolean;
117
+ }>;
118
+ }
119
+ export interface MemorySnapshotPersistence {
120
+ stores: {
121
+ messages: MemoryMessageStore;
122
+ runs: MemoryRunStore;
123
+ generationRuns: MemoryGenerationRunStore;
124
+ interrupts: MemoryInterruptStore;
125
+ metadata: MemoryMetadataStore;
126
+ artifacts: MemoryArtifactStore;
127
+ blobs: MemoryBlobStore;
128
+ };
129
+ }
@@ -0,0 +1,6 @@
1
+ import { MemorySnapshotPersistence } from './memory-snapshot-types.js';
2
+ import { ForkCapableSandboxCheckpointStore } from './checkpoint-store.js';
3
+ import { CreateSandboxSnapshotsInput, SandboxSnapshots } from './snapshot-operations.js';
4
+ export type MemorySandboxSnapshots = SandboxSnapshots<MemorySnapshotPersistence, ForkCapableSandboxCheckpointStore>;
5
+ export type MemorySandboxSnapshotsOptions = Omit<CreateSandboxSnapshotsInput<MemorySnapshotPersistence, ForkCapableSandboxCheckpointStore>, 'persistence' | 'checkpoints'>;
6
+ export declare function memorySandboxSnapshots(options?: MemorySandboxSnapshotsOptions): Promise<MemorySandboxSnapshots>;
@@ -0,0 +1,490 @@
1
+ import { SandboxCheckpointConflictError, SandboxCheckpointDuplicateIdError, SandboxCheckpointError, SandboxCheckpointInvalidEntryError, SandboxCheckpointInvalidIdError, SandboxCheckpointNotHeadError, SandboxCheckpointParentMismatchError, SandboxCheckpointWriterConflictError, SandboxCheckpointWriterLostError } from "./checkpoint-store.js";
2
+ import { createSandboxSnapshots } from "./snapshot-operations.js";
3
+ //#region src/memory-snapshots.ts
4
+ function resolveBlobRange(size, range) {
5
+ if (!Number.isInteger(range.offset) || range.offset < 0 || range.offset >= size) throw new RangeError(`Blob range offset ${range.offset} is outside the object (size ${size}).`);
6
+ const remaining = size - range.offset;
7
+ if (range.length === void 0) return {
8
+ offset: range.offset,
9
+ length: remaining
10
+ };
11
+ if (!Number.isInteger(range.length) || range.length < 0) throw new RangeError(`Blob range length ${range.length} is not valid.`);
12
+ return {
13
+ offset: range.offset,
14
+ length: Math.min(range.length, remaining)
15
+ };
16
+ }
17
+ var encoder = new TextEncoder();
18
+ var compare = (a, b) => {
19
+ const left = encoder.encode(a);
20
+ const right = encoder.encode(b);
21
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
22
+ const leftByte = left[i];
23
+ const rightByte = right[i];
24
+ if (leftByte !== rightByte) return (leftByte ?? 0) - (rightByte ?? 0);
25
+ }
26
+ return left.length - right.length;
27
+ };
28
+ var clone = (value) => structuredClone(value);
29
+ function hasUnpairedSurrogate(value) {
30
+ for (let index = 0; index < value.length; index++) {
31
+ const code = value.charCodeAt(index);
32
+ if (code >= 55296 && code <= 56319) {
33
+ const next = value.charCodeAt(index + 1);
34
+ if (Number.isNaN(next) || next < 56320 || next > 57343) return true;
35
+ index++;
36
+ } else if (code >= 56320 && code <= 57343) return true;
37
+ }
38
+ return false;
39
+ }
40
+ function assertValidIdentifier(value, label) {
41
+ if (typeof value !== "string" || value.length === 0 || hasUnpairedSurrogate(value)) throw new SandboxCheckpointInvalidIdError(`${label} must be a non-empty well-formed Unicode string`);
42
+ }
43
+ function hasOwn(value, key) {
44
+ return Object.prototype.hasOwnProperty.call(value, key);
45
+ }
46
+ function validateEntries(checkpoint) {
47
+ if (!Array.isArray(checkpoint.files)) throw new SandboxCheckpointInvalidEntryError("Checkpoint files must be an array");
48
+ const paths = /* @__PURE__ */ new Set();
49
+ const kinds = /* @__PURE__ */ new Map();
50
+ for (const entry of checkpoint.files) {
51
+ if (entry === null || typeof entry !== "object") throw new SandboxCheckpointInvalidEntryError("Checkpoint entry must be an object");
52
+ const candidate = entry;
53
+ if (typeof candidate.path !== "string" || candidate.path.length === 0 || candidate.path.includes("\0") || candidate.path.startsWith("/") || candidate.path.startsWith("\\") || /^[A-Za-z]:([\\/]|$)/.test(candidate.path) || candidate.path.includes("\\") || candidate.path.split("/").some((part) => part.length === 0 || part === "." || part === "..")) throw new SandboxCheckpointInvalidEntryError("Checkpoint entry path must be a normalized workspace-relative path");
54
+ const path = candidate.path;
55
+ if (paths.has(path)) throw new SandboxCheckpointInvalidEntryError(`Checkpoint contains duplicate entry path '${path}'`);
56
+ for (let separator = path.indexOf("/"); separator !== -1; separator = path.indexOf("/", separator + 1)) {
57
+ const ancestor = path.slice(0, separator);
58
+ if (kinds.get(ancestor) === "file") throw new SandboxCheckpointInvalidEntryError(`Checkpoint entry '${path}' is beneath file '${ancestor}'`);
59
+ }
60
+ if (candidate.kind === "file" && Array.from(kinds.keys()).some((other) => other.startsWith(`${path}/`))) throw new SandboxCheckpointInvalidEntryError(`Checkpoint file '${path}' is an ancestor of another entry`);
61
+ paths.add(path);
62
+ if (candidate.kind === "file") {
63
+ if (typeof candidate.blobKey !== "string" || candidate.blobKey.length === 0 || hasUnpairedSurrogate(candidate.blobKey) || !/^sandbox-files\/sha256\/[0-9a-f]{64}$/.test(candidate.blobKey)) throw new SandboxCheckpointInvalidEntryError("File entries require a valid content-addressed blobKey");
64
+ if (!hasOwn(candidate, "size") || typeof candidate.size !== "number" || !Number.isSafeInteger(candidate.size) || candidate.size < 0) throw new SandboxCheckpointInvalidEntryError("File entry size must be a non-negative safe integer");
65
+ } else if (candidate.kind === "dir") {
66
+ if (hasOwn(candidate, "blobKey") || hasOwn(candidate, "size")) throw new SandboxCheckpointInvalidEntryError("Directory entries cannot contain file fields");
67
+ } else throw new SandboxCheckpointInvalidEntryError("Checkpoint entry kind must be file or dir");
68
+ kinds.set(path, candidate.kind);
69
+ }
70
+ }
71
+ function validateArtifacts(checkpoint) {
72
+ if (!Array.isArray(checkpoint.artifacts)) throw new SandboxCheckpointInvalidEntryError("Checkpoint artifacts must be an array");
73
+ for (const artifact of checkpoint.artifacts) {
74
+ if (artifact === null || typeof artifact !== "object") throw new SandboxCheckpointInvalidEntryError("Checkpoint artifact must be an object");
75
+ const candidate = artifact;
76
+ if (typeof candidate.artifactId !== "string" || candidate.artifactId.length === 0 || hasUnpairedSurrogate(candidate.artifactId) || typeof candidate.name !== "string" || candidate.name.length === 0 || typeof candidate.mimeType !== "string" || candidate.mimeType.length === 0 || typeof candidate.blobKey !== "string" || candidate.blobKey.length === 0 || hasUnpairedSurrogate(candidate.blobKey) || !/^sandbox-artifacts\/sha256\/[0-9a-f]{64}$/.test(candidate.blobKey) || typeof candidate.size !== "number" || !Number.isSafeInteger(candidate.size) || candidate.size < 0 || typeof candidate.createdAt !== "number" || !Number.isFinite(candidate.createdAt)) throw new SandboxCheckpointInvalidEntryError("Checkpoint artifact has invalid fields");
77
+ }
78
+ }
79
+ function validateCheckpoint(checkpoint) {
80
+ assertValidIdentifier(checkpoint.id, "Checkpoint id");
81
+ assertValidIdentifier(checkpoint.threadId, "Checkpoint thread id");
82
+ if (checkpoint.parentCheckpointId !== null) assertValidIdentifier(checkpoint.parentCheckpointId, "Parent checkpoint id");
83
+ if (!Number.isFinite(checkpoint.createdAt)) throw new SandboxCheckpointInvalidEntryError("Checkpoint createdAt must be a finite number");
84
+ validateEntries(checkpoint);
85
+ validateArtifacts(checkpoint);
86
+ }
87
+ function blobKeys(checkpoint) {
88
+ const keys = /* @__PURE__ */ new Set();
89
+ for (const entry of checkpoint.files) if (entry.kind === "file") keys.add(entry.blobKey);
90
+ for (const artifact of checkpoint.artifacts) keys.add(artifact.blobKey);
91
+ return keys;
92
+ }
93
+ var MemorySnapshotCheckpointStore = class {
94
+ state;
95
+ now = () => Date.now();
96
+ leaseDurationMs = 12e4;
97
+ renewAfterMs = 45e3;
98
+ constructor(state) {
99
+ this.state = state;
100
+ }
101
+ async get(id) {
102
+ assertValidIdentifier(id, "Checkpoint id");
103
+ const checkpoint = this.state.checkpoints.get(id);
104
+ return checkpoint ? clone(checkpoint) : null;
105
+ }
106
+ async list(threadId) {
107
+ assertValidIdentifier(threadId, "Thread id");
108
+ return [...this.state.checkpoints.values()].filter((checkpoint) => checkpoint.threadId === threadId).sort((a, b) => a.createdAt - b.createdAt || compare(a.id, b.id)).map(clone);
109
+ }
110
+ async getHead(threadId) {
111
+ assertValidIdentifier(threadId, "Thread id");
112
+ return this.state.heads.get(threadId) ?? null;
113
+ }
114
+ async append(input) {
115
+ const checkpoint = clone(input.checkpoint);
116
+ const { expectedHeadId, writer } = input;
117
+ assertValidIdentifier(checkpoint.id, "Checkpoint id");
118
+ assertValidIdentifier(checkpoint.threadId, "Checkpoint thread id");
119
+ assertValidIdentifier(writer.threadId, "Writer thread id");
120
+ if (expectedHeadId !== null) assertValidIdentifier(expectedHeadId, "Expected head id");
121
+ if (checkpoint.parentCheckpointId != null) assertValidIdentifier(checkpoint.parentCheckpointId, "Parent checkpoint id");
122
+ if (writer.threadId !== checkpoint.threadId) throw new SandboxCheckpointWriterLostError("Checkpoint writer thread does not match checkpoint thread");
123
+ validateCheckpoint(checkpoint);
124
+ this.assertWriter(writer, checkpoint.threadId);
125
+ if (this.state.checkpoints.has(checkpoint.id)) throw new SandboxCheckpointDuplicateIdError(`Checkpoint '${checkpoint.id}' already exists`);
126
+ const actualHeadId = this.state.heads.get(checkpoint.threadId) ?? null;
127
+ if (actualHeadId !== expectedHeadId) throw new SandboxCheckpointConflictError(`Expected head '${expectedHeadId}', but thread '${checkpoint.threadId}' is at '${actualHeadId}'`);
128
+ const parentCheckpointId = checkpoint.parentCheckpointId ?? null;
129
+ if (parentCheckpointId !== expectedHeadId) throw new SandboxCheckpointParentMismatchError(`Checkpoint '${checkpoint.id}' parent does not match expected head`);
130
+ const stored = {
131
+ ...checkpoint,
132
+ parentCheckpointId
133
+ };
134
+ const keys = blobKeys(stored);
135
+ this.state.checkpoints.set(stored.id, stored);
136
+ this.state.heads.set(stored.threadId, stored.id);
137
+ for (const key of keys) this.state.references.set(key, (this.state.references.get(key) ?? 0) + 1);
138
+ return { headId: stored.id };
139
+ }
140
+ async deleteHead(input) {
141
+ const { threadId, checkpointId, writer } = input;
142
+ assertValidIdentifier(threadId, "Thread id");
143
+ assertValidIdentifier(checkpointId, "Checkpoint id");
144
+ assertValidIdentifier(writer.threadId, "Writer thread id");
145
+ if (writer.threadId !== threadId) throw new SandboxCheckpointWriterLostError("Checkpoint writer thread does not match operation thread");
146
+ this.assertWriter(writer, threadId);
147
+ if ((this.state.heads.get(threadId) ?? null) !== checkpointId) throw new SandboxCheckpointNotHeadError(`Checkpoint '${checkpointId}' is not the current head of thread '${threadId}'`);
148
+ const checkpoint = this.state.checkpoints.get(checkpointId);
149
+ if (!checkpoint) throw new SandboxCheckpointNotHeadError(`Checkpoint '${checkpointId}' does not exist`);
150
+ this.state.checkpoints.delete(checkpointId);
151
+ if (checkpoint.parentCheckpointId) this.state.heads.set(threadId, checkpoint.parentCheckpointId);
152
+ else this.state.heads.delete(threadId);
153
+ for (const key of blobKeys(checkpoint)) {
154
+ const references = (this.state.references.get(key) ?? 0) - 1;
155
+ if (references > 0) this.state.references.set(key, references);
156
+ else this.state.references.delete(key);
157
+ }
158
+ }
159
+ async acquireWriter(threadId) {
160
+ assertValidIdentifier(threadId, "Thread id");
161
+ const current = this.state.writers.get(threadId);
162
+ if (current && current.expiresAt > this.now()) throw new SandboxCheckpointWriterConflictError(`Thread '${threadId}' already has an active checkpoint writer`);
163
+ const fence = (this.state.fences.get(threadId) ?? 0) + 1;
164
+ this.state.fences.set(threadId, fence);
165
+ const ownerToken = globalThis.crypto.randomUUID();
166
+ const lease = {
167
+ threadId,
168
+ ownerToken,
169
+ fence,
170
+ expiresAt: this.now() + this.leaseDurationMs
171
+ };
172
+ this.state.writers.set(threadId, lease);
173
+ return {
174
+ ...lease,
175
+ get expiresAt() {
176
+ return lease.expiresAt;
177
+ },
178
+ renewAfterMs: this.renewAfterMs,
179
+ renew: async () => {
180
+ this.assertWriter(lease, threadId);
181
+ lease.expiresAt = this.now() + this.leaseDurationMs;
182
+ return { expiresAt: lease.expiresAt };
183
+ },
184
+ release: async () => {
185
+ const currentLease = this.state.writers.get(threadId);
186
+ if (currentLease?.ownerToken === ownerToken && currentLease.fence === fence) this.state.writers.delete(threadId);
187
+ }
188
+ };
189
+ }
190
+ async listBlobReferences() {
191
+ return [...this.state.references.entries()].sort(([a], [b]) => compare(a, b)).map(([key, references]) => ({
192
+ key,
193
+ references
194
+ }));
195
+ }
196
+ async forkFromCheckpoint(input) {
197
+ const sourceThreadId = input.sourceThreadId;
198
+ const sourceCheckpointId = input.sourceCheckpointId;
199
+ const destinationThreadId = input.destinationThreadId;
200
+ const destinationCheckpointId = input.destinationCheckpointId;
201
+ const createdAt = input.createdAt;
202
+ const suppliedWriter = input.writer;
203
+ const writer = {
204
+ threadId: suppliedWriter.threadId,
205
+ ownerToken: suppliedWriter.ownerToken,
206
+ fence: suppliedWriter.fence
207
+ };
208
+ assertValidIdentifier(sourceThreadId, "Source thread id");
209
+ assertValidIdentifier(sourceCheckpointId, "Source checkpoint id");
210
+ assertValidIdentifier(destinationThreadId, "Destination thread id");
211
+ assertValidIdentifier(destinationCheckpointId, "Destination checkpoint id");
212
+ assertValidIdentifier(writer.threadId, "Writer thread id");
213
+ if (!Number.isFinite(createdAt)) throw new SandboxCheckpointInvalidEntryError("Fork checkpoint createdAt must be a finite number");
214
+ if (sourceThreadId === destinationThreadId) throw new SandboxCheckpointError("SANDBOX_SNAPSHOT_FORK_SOURCE_THREAD_MISMATCH", "Source and destination threads must differ");
215
+ const source = this.state.checkpoints.get(sourceCheckpointId);
216
+ if (!source) throw new SandboxCheckpointError("SANDBOX_SNAPSHOT_FORK_SOURCE_NOT_FOUND", "Source checkpoint was not found");
217
+ if (source.threadId !== sourceThreadId) throw new SandboxCheckpointError("SANDBOX_SNAPSHOT_FORK_SOURCE_THREAD_MISMATCH", "Source checkpoint belongs to another thread");
218
+ if (writer.threadId !== destinationThreadId) throw new SandboxCheckpointWriterLostError("Checkpoint writer thread does not match destination thread");
219
+ this.assertWriter(writer, destinationThreadId);
220
+ this.assertDestinationEmpty(destinationThreadId, destinationCheckpointId);
221
+ const stagedCheckpoint = clone({
222
+ id: destinationCheckpointId,
223
+ threadId: destinationThreadId,
224
+ parentCheckpointId: null,
225
+ createdAt,
226
+ reason: "fork-root",
227
+ files: source.files,
228
+ conversation: source.conversation,
229
+ artifacts: source.artifacts
230
+ });
231
+ validateCheckpoint(stagedCheckpoint);
232
+ const stagedTranscript = clone([...stagedCheckpoint.conversation]);
233
+ const result = { checkpoint: clone(stagedCheckpoint) };
234
+ const stagedReferences = [...blobKeys(stagedCheckpoint)].map((key) => ({
235
+ key,
236
+ references: (this.state.references.get(key) ?? 0) + 1
237
+ }));
238
+ this.assertWriter(writer, destinationThreadId);
239
+ this.assertDestinationEmpty(destinationThreadId, destinationCheckpointId);
240
+ this.state.messages.set(stagedCheckpoint.threadId, stagedTranscript);
241
+ this.state.checkpoints.set(stagedCheckpoint.id, stagedCheckpoint);
242
+ this.state.heads.set(stagedCheckpoint.threadId, stagedCheckpoint.id);
243
+ for (const reference of stagedReferences) this.state.references.set(reference.key, reference.references);
244
+ return result;
245
+ }
246
+ assertDestinationEmpty(destinationThreadId, destinationCheckpointId) {
247
+ if (this.state.messages.has(destinationThreadId) || [...this.state.runs.values()].some((value) => value.threadId === destinationThreadId) || [...this.state.generations.values()].some((value) => value.threadId === destinationThreadId) || [...this.state.interrupts.values()].some((value) => value.threadId === destinationThreadId) || [...this.state.artifacts.values()].some((value) => value.threadId === destinationThreadId) || [...this.state.checkpoints.values()].some((value) => value.threadId === destinationThreadId) || this.state.heads.has(destinationThreadId) || this.state.checkpoints.has(destinationCheckpointId)) throw new SandboxCheckpointError("SANDBOX_SNAPSHOT_FORK_DESTINATION_NOT_EMPTY", "Destination thread is not empty");
248
+ }
249
+ assertWriter(writer, threadId) {
250
+ const current = this.state.writers.get(threadId);
251
+ if (!current || current.ownerToken !== writer.ownerToken || current.fence !== writer.fence || current.expiresAt <= this.now()) throw new SandboxCheckpointWriterLostError(`Checkpoint writer lease for thread '${threadId}' is no longer current`);
252
+ }
253
+ };
254
+ async function bodyBytes(body) {
255
+ if (typeof body === "string") return encoder.encode(body);
256
+ if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0));
257
+ if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength));
258
+ if (typeof Blob !== "undefined" && body instanceof Blob) return new Uint8Array(await body.arrayBuffer());
259
+ if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) {
260
+ const reader = body.getReader();
261
+ const parts = [];
262
+ try {
263
+ for (;;) {
264
+ const next = await reader.read();
265
+ if (next.done) break;
266
+ parts.push(new Uint8Array(next.value));
267
+ }
268
+ } finally {
269
+ reader.releaseLock();
270
+ }
271
+ const result = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
272
+ let offset = 0;
273
+ for (const part of parts) {
274
+ result.set(part, offset);
275
+ offset += part.byteLength;
276
+ }
277
+ return result;
278
+ }
279
+ throw new TypeError("Unsupported blob body.");
280
+ }
281
+ async function memorySandboxSnapshots(options = {}) {
282
+ const { persistence, checkpoints } = await createMemorySandboxSnapshots();
283
+ return createSandboxSnapshots({
284
+ persistence,
285
+ checkpoints,
286
+ ...options
287
+ });
288
+ }
289
+ async function createMemorySandboxSnapshots() {
290
+ const messages = /* @__PURE__ */ new Map();
291
+ const runs = /* @__PURE__ */ new Map();
292
+ const generations = /* @__PURE__ */ new Map();
293
+ const interrupts = /* @__PURE__ */ new Map();
294
+ const metadata = /* @__PURE__ */ new Map();
295
+ const artifacts = /* @__PURE__ */ new Map();
296
+ const blobs = /* @__PURE__ */ new Map();
297
+ const state = {
298
+ messages,
299
+ runs,
300
+ generations,
301
+ interrupts,
302
+ metadata,
303
+ artifacts,
304
+ blobs,
305
+ checkpoints: /* @__PURE__ */ new Map(),
306
+ heads: /* @__PURE__ */ new Map(),
307
+ writers: /* @__PURE__ */ new Map(),
308
+ fences: /* @__PURE__ */ new Map(),
309
+ references: /* @__PURE__ */ new Map()
310
+ };
311
+ let etag = 0;
312
+ return {
313
+ persistence: { stores: {
314
+ messages: {
315
+ loadThread: async (threadId) => messages.get(threadId)?.slice() ?? [],
316
+ saveThread: async (threadId, value) => {
317
+ messages.set(threadId, value.slice());
318
+ }
319
+ },
320
+ runs: {
321
+ createOrResume: async (input) => {
322
+ const existing = runs.get(input.runId);
323
+ if (existing) return existing;
324
+ const record = {
325
+ ...input,
326
+ status: input.status ?? "running"
327
+ };
328
+ runs.set(record.runId, record);
329
+ return record;
330
+ },
331
+ update: async (runId, patch) => {
332
+ const value = runs.get(runId);
333
+ if (value) runs.set(runId, {
334
+ ...value,
335
+ ...patch
336
+ });
337
+ },
338
+ get: async (runId) => runs.get(runId) ?? null,
339
+ findActiveRun: async (threadId) => [...runs.values()].filter((run) => run.threadId === threadId && run.status === "running").sort((a, b) => b.startedAt - a.startedAt)[0] ?? null,
340
+ listByThread: async (threadId) => [...runs.values()].filter((run) => run.threadId === threadId).sort((a, b) => a.startedAt - b.startedAt),
341
+ listReclaimable: async (input) => [...runs.values()].filter((run) => run.status === "running" && run.detachedSince !== void 0 && run.detachedSince <= input.now - input.ttlMs)
342
+ },
343
+ generationRuns: {
344
+ createOrResume: async (input) => {
345
+ const value = generations.get(input.runId) ?? {
346
+ ...input,
347
+ status: input.status ?? "running"
348
+ };
349
+ generations.set(input.runId, value);
350
+ return value;
351
+ },
352
+ update: async (runId, patch) => {
353
+ const value = generations.get(runId);
354
+ if (value) generations.set(runId, {
355
+ ...value,
356
+ ...patch
357
+ });
358
+ },
359
+ get: async (runId) => generations.get(runId) ?? null,
360
+ findLatestForThread: async (threadId) => [...generations.values()].filter((run) => run.threadId === threadId).sort((a, b) => b.startedAt - a.startedAt)[0] ?? null
361
+ },
362
+ interrupts: {
363
+ create: async (record) => {
364
+ if (!interrupts.has(record.interruptId)) interrupts.set(record.interruptId, {
365
+ ...record,
366
+ status: "pending"
367
+ });
368
+ },
369
+ resolve: async (id, response) => {
370
+ const value = interrupts.get(id);
371
+ if (value) interrupts.set(id, {
372
+ ...value,
373
+ status: "resolved",
374
+ resolvedAt: Date.now(),
375
+ response
376
+ });
377
+ },
378
+ cancel: async (id) => {
379
+ const value = interrupts.get(id);
380
+ if (value) interrupts.set(id, {
381
+ ...value,
382
+ status: "cancelled",
383
+ resolvedAt: Date.now()
384
+ });
385
+ },
386
+ get: async (id) => interrupts.get(id) ?? null,
387
+ list: async (threadId) => [...interrupts.values()].filter((value) => value.threadId === threadId).sort((a, b) => a.requestedAt - b.requestedAt),
388
+ listPending: async (threadId) => [...interrupts.values()].filter((value) => value.threadId === threadId && value.status === "pending").sort((a, b) => a.requestedAt - b.requestedAt),
389
+ listByRun: async (runId) => [...interrupts.values()].filter((value) => value.runId === runId).sort((a, b) => a.requestedAt - b.requestedAt),
390
+ listPendingByRun: async (runId) => [...interrupts.values()].filter((value) => value.runId === runId && value.status === "pending").sort((a, b) => a.requestedAt - b.requestedAt)
391
+ },
392
+ metadata: {
393
+ get: async (namespace, key) => {
394
+ const bucket = metadata.get(namespace);
395
+ return bucket?.has(key) ? bucket.get(key) : null;
396
+ },
397
+ set: async (namespace, key, value) => {
398
+ let bucket = metadata.get(namespace);
399
+ if (!bucket) {
400
+ bucket = /* @__PURE__ */ new Map();
401
+ metadata.set(namespace, bucket);
402
+ }
403
+ bucket.set(key, value);
404
+ },
405
+ delete: async (namespace, key) => {
406
+ metadata.get(namespace)?.delete(key);
407
+ }
408
+ },
409
+ artifacts: {
410
+ save: async (value) => {
411
+ artifacts.set(value.artifactId, { ...value });
412
+ },
413
+ get: async (id) => artifacts.get(id) ?? null,
414
+ list: async (runId) => [...artifacts.values()].filter((value) => value.runId === runId).sort((a, b) => a.createdAt - b.createdAt || compare(a.artifactId, b.artifactId)),
415
+ listForThread: async (threadId) => [...artifacts.values()].filter((value) => value.threadId === threadId).sort((a, b) => a.createdAt - b.createdAt || compare(a.artifactId, b.artifactId)),
416
+ delete: async (id) => {
417
+ artifacts.delete(id);
418
+ },
419
+ deleteForRun: async (runId) => {
420
+ for (const [id, value] of artifacts) if (value.runId === runId) artifacts.delete(id);
421
+ }
422
+ },
423
+ blobs: {
424
+ put: async (key, body, putOptions) => {
425
+ const bytes = await bodyBytes(body);
426
+ const now = Date.now();
427
+ const record = {
428
+ key,
429
+ size: bytes.byteLength,
430
+ etag: String(++etag),
431
+ contentType: putOptions?.contentType ?? (typeof Blob !== "undefined" && body instanceof Blob ? body.type || void 0 : void 0),
432
+ customMetadata: putOptions?.customMetadata ? { ...putOptions.customMetadata } : void 0,
433
+ createdAt: blobs.get(key)?.record.createdAt ?? now,
434
+ updatedAt: now
435
+ };
436
+ blobs.set(key, {
437
+ record,
438
+ bytes: new Uint8Array(bytes)
439
+ });
440
+ return clone(record);
441
+ },
442
+ get: async (key, getOptions) => {
443
+ const value = blobs.get(key);
444
+ if (!value) return null;
445
+ const range = getOptions?.range ? resolveBlobRange(value.bytes.byteLength, getOptions.range) : {
446
+ offset: 0,
447
+ length: value.bytes.byteLength
448
+ };
449
+ const bytes = value.bytes.slice(range.offset, range.offset + range.length);
450
+ return {
451
+ ...clone(value.record),
452
+ ...getOptions?.range ? { range } : {},
453
+ body: new Blob([bytes]).stream(),
454
+ arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
455
+ text: async () => new TextDecoder().decode(bytes)
456
+ };
457
+ },
458
+ head: async (key) => clone(blobs.get(key)?.record ?? null),
459
+ delete: async (key) => {
460
+ blobs.delete(key);
461
+ },
462
+ list: async (listOptions) => {
463
+ const keys = [...blobs.keys()].filter((key) => key.startsWith(listOptions?.prefix ?? "")).filter((key) => listOptions?.cursor === void 0 || key > listOptions.cursor).sort();
464
+ if (listOptions?.limit === 0) return {
465
+ objects: [],
466
+ truncated: false
467
+ };
468
+ const page = listOptions?.limit === void 0 ? keys : keys.slice(0, listOptions.limit);
469
+ const truncated = listOptions?.limit !== void 0 && keys.length > page.length;
470
+ return {
471
+ objects: clone(page.map((key) => {
472
+ const value = blobs.get(key);
473
+ if (!value) throw new Error(`Missing blob for listed key: ${key}`);
474
+ return value.record;
475
+ })),
476
+ ...truncated ? {
477
+ cursor: page.at(-1),
478
+ truncated: true
479
+ } : {}
480
+ };
481
+ }
482
+ }
483
+ } },
484
+ checkpoints: new MemorySnapshotCheckpointStore(state)
485
+ };
486
+ }
487
+ //#endregion
488
+ export { memorySandboxSnapshots };
489
+
490
+ //# sourceMappingURL=memory-snapshots.js.map