Open History to see the last commit
1import type { ModelMessage } from '@tanstack/ai'
2import type {
3 MemoryArtifactRecord as ArtifactRecord,
4 MemoryBlobBody as BlobBody,
5 MemoryBlobRecord as BlobRecord,
6 MemoryGenerationRunRecord as GenerationRunRecord,
7 MemoryInterruptRecord as InterruptRecord,
8 MemoryRunRecord as RunRecord,
9 MemorySnapshotPersistence,
10} from './memory-snapshot-types'
11import {
12 SandboxCheckpointConflictError,
13 SandboxCheckpointDuplicateIdError,
14 SandboxCheckpointError,
15 SandboxCheckpointInvalidEntryError,
16 SandboxCheckpointInvalidIdError,
17 SandboxCheckpointNotHeadError,
18 SandboxCheckpointParentMismatchError,
19 SandboxCheckpointWriterConflictError,
20 SandboxCheckpointWriterLostError,
21} from './checkpoint-store'
22import type {
23 ForkCapableSandboxCheckpointStore,
24 SandboxCheckpoint,
25 SandboxCheckpointWriter,
26 SandboxCheckpointWriterLease,
27 SandboxCheckpointForkInput,
28} from './checkpoint-store'
29import { createSandboxSnapshots } from './snapshot-operations'
30import type {
31 CreateSandboxSnapshotsInput,
32 SandboxSnapshots,
33} from './snapshot-operations'
34
35type BlobGetOptions = { range?: { offset: number; length?: number } }
36
37function resolveBlobRange(
38 size: number,
39 range: { offset: number; length?: number },
40): { offset: number; length: number } {
41 if (
42 !Number.isInteger(range.offset) ||
43 range.offset < 0 ||
44 range.offset >= size
45 ) {
46 throw new RangeError(
47 `Blob range offset ${range.offset} is outside the object (size ${size}).`,
48 )
49 }
50 const remaining = size - range.offset
51 if (range.length === undefined) {
52 return { offset: range.offset, length: remaining }
53 }
54 if (!Number.isInteger(range.length) || range.length < 0) {
55 throw new RangeError(`Blob range length ${range.length} is not valid.`)
56 }
57 return {
58 offset: range.offset,
59 length: Math.min(range.length, remaining),
60 }
61}
62
63export type MemorySandboxSnapshots = SandboxSnapshots<
64 MemorySnapshotPersistence,
65 ForkCapableSandboxCheckpointStore
66>
67
68export type MemorySandboxSnapshotsOptions = Omit<
69 CreateSandboxSnapshotsInput<
70 MemorySnapshotPersistence,
71 ForkCapableSandboxCheckpointStore
72 >,
73 'persistence' | 'checkpoints'
74>
75
76const encoder = new TextEncoder()
77const compare = (a: string, b: string) => {
78 const left = encoder.encode(a)
79 const right = encoder.encode(b)
80 for (let i = 0; i < Math.min(left.length, right.length); i++) {
81 const leftByte = left[i]
82 const rightByte = right[i]
83 if (leftByte !== rightByte) return (leftByte ?? 0) - (rightByte ?? 0)
84 }
85 return left.length - right.length
86}
87const clone = <T>(value: T): T => structuredClone(value)
88
89interface MemoryCheckpointState {
90 checkpoints: Map<string, SandboxCheckpoint>
91 heads: Map<string, string>
92 writers: Map<string, { ownerToken: string; fence: number; expiresAt: number }>
93 fences: Map<string, number>
94 references: Map<string, number>
95}
96
97interface MemorySnapshotState extends MemoryCheckpointState {
98 messages: Map<string, Array<ModelMessage>>
99 runs: Map<string, RunRecord>
100 generations: Map<string, GenerationRunRecord>
101 interrupts: Map<string, InterruptRecord>
102 metadata: Map<string, Map<string, unknown>>
103 artifacts: Map<string, ArtifactRecord>
104 blobs: Map<string, { record: BlobRecord; bytes: Uint8Array }>
105}
106
107function hasUnpairedSurrogate(value: string): boolean {
108 for (let index = 0; index < value.length; index++) {
109 const code = value.charCodeAt(index)
110 if (code >= 0xd800 && code <= 0xdbff) {
111 const next = value.charCodeAt(index + 1)
112 if (Number.isNaN(next) || next < 0xdc00 || next > 0xdfff) return true
113 index++
114 } else if (code >= 0xdc00 && code <= 0xdfff) {
115 return true
116 }
117 }
118 return false
119}
120
121function assertValidIdentifier(
122 value: unknown,
123 label: string,
124): asserts value is string {
125 if (
126 typeof value !== 'string' ||
127 value.length === 0 ||
128 hasUnpairedSurrogate(value)
129 ) {
130 throw new SandboxCheckpointInvalidIdError(
131 `${label} must be a non-empty well-formed Unicode string`,
132 )
133 }
134}
135
136function hasOwn(value: object, key: string): boolean {
137 return Object.prototype.hasOwnProperty.call(value, key)
138}
139
140function validateEntries(checkpoint: SandboxCheckpoint): void {
141 if (!Array.isArray(checkpoint.files)) {
142 throw new SandboxCheckpointInvalidEntryError(
143 'Checkpoint files must be an array',
144 )
145 }
146 const paths = new Set<string>()
147 const kinds = new Map<string, 'file' | 'dir'>()
148 for (const entry of checkpoint.files as ReadonlyArray<unknown>) {
149 if (entry === null || typeof entry !== 'object') {
150 throw new SandboxCheckpointInvalidEntryError(
151 'Checkpoint entry must be an object',
152 )
153 }
154 const candidate = entry as Record<string, unknown>
155 if (
156 typeof candidate.path !== 'string' ||
157 candidate.path.length === 0 ||
158 candidate.path.includes('\0') ||
159 candidate.path.startsWith('/') ||
160 candidate.path.startsWith('\\') ||
161 /^[A-Za-z]:([\\/]|$)/.test(candidate.path) ||
162 candidate.path.includes('\\') ||
163 candidate.path
164 .split('/')
165 .some((part) => part.length === 0 || part === '.' || part === '..')
166 ) {
167 throw new SandboxCheckpointInvalidEntryError(
168 'Checkpoint entry path must be a normalized workspace-relative path',
169 )
170 }
171 const path = candidate.path
172 if (paths.has(path)) {
173 throw new SandboxCheckpointInvalidEntryError(
174 `Checkpoint contains duplicate entry path '${path}'`,
175 )
176 }
177 for (
178 let separator = path.indexOf('/');
179 separator !== -1;
180 separator = path.indexOf('/', separator + 1)
181 ) {
182 const ancestor = path.slice(0, separator)
183 if (kinds.get(ancestor) === 'file') {
184 throw new SandboxCheckpointInvalidEntryError(
185 `Checkpoint entry '${path}' is beneath file '${ancestor}'`,
186 )
187 }
188 }
189 if (
190 candidate.kind === 'file' &&
191 Array.from(kinds.keys()).some((other) => other.startsWith(`${path}/`))
192 ) {
193 throw new SandboxCheckpointInvalidEntryError(
194 `Checkpoint file '${path}' is an ancestor of another entry`,
195 )
196 }
197 paths.add(path)
198 if (candidate.kind === 'file') {
199 if (
200 typeof candidate.blobKey !== 'string' ||
201 candidate.blobKey.length === 0 ||
202 hasUnpairedSurrogate(candidate.blobKey) ||
203 !/^sandbox-files\/sha256\/[0-9a-f]{64}$/.test(candidate.blobKey)
204 ) {
205 throw new SandboxCheckpointInvalidEntryError(
206 'File entries require a valid content-addressed blobKey',
207 )
208 }
209 if (
210 !hasOwn(candidate, 'size') ||
211 typeof candidate.size !== 'number' ||
212 !Number.isSafeInteger(candidate.size) ||
213 candidate.size < 0
214 ) {
215 throw new SandboxCheckpointInvalidEntryError(
216 'File entry size must be a non-negative safe integer',
217 )
218 }
219 } else if (candidate.kind === 'dir') {
220 if (hasOwn(candidate, 'blobKey') || hasOwn(candidate, 'size')) {
221 throw new SandboxCheckpointInvalidEntryError(
222 'Directory entries cannot contain file fields',
223 )
224 }
225 } else {
226 throw new SandboxCheckpointInvalidEntryError(
227 'Checkpoint entry kind must be file or dir',
228 )
229 }
230 kinds.set(path, candidate.kind)
231 }
232}
233
234function validateArtifacts(checkpoint: SandboxCheckpoint): void {
235 if (!Array.isArray(checkpoint.artifacts)) {
236 throw new SandboxCheckpointInvalidEntryError(
237 'Checkpoint artifacts must be an array',
238 )
239 }
240 for (const artifact of checkpoint.artifacts as ReadonlyArray<unknown>) {
241 if (artifact === null || typeof artifact !== 'object') {
242 throw new SandboxCheckpointInvalidEntryError(
243 'Checkpoint artifact must be an object',
244 )
245 }
246 const candidate = artifact as Record<string, unknown>
247 if (
248 typeof candidate.artifactId !== 'string' ||
249 candidate.artifactId.length === 0 ||
250 hasUnpairedSurrogate(candidate.artifactId) ||
251 typeof candidate.name !== 'string' ||
252 candidate.name.length === 0 ||
253 typeof candidate.mimeType !== 'string' ||
254 candidate.mimeType.length === 0 ||
255 typeof candidate.blobKey !== 'string' ||
256 candidate.blobKey.length === 0 ||
257 hasUnpairedSurrogate(candidate.blobKey) ||
258 !/^sandbox-artifacts\/sha256\/[0-9a-f]{64}$/.test(candidate.blobKey) ||
259 typeof candidate.size !== 'number' ||
260 !Number.isSafeInteger(candidate.size) ||
261 candidate.size < 0 ||
262 typeof candidate.createdAt !== 'number' ||
263 !Number.isFinite(candidate.createdAt)
264 ) {
265 throw new SandboxCheckpointInvalidEntryError(
266 'Checkpoint artifact has invalid fields',
267 )
268 }
269 }
270}
271
272function validateCheckpoint(checkpoint: SandboxCheckpoint): void {
273 assertValidIdentifier(checkpoint.id, 'Checkpoint id')
274 assertValidIdentifier(checkpoint.threadId, 'Checkpoint thread id')
275 if (checkpoint.parentCheckpointId !== null) {
276 assertValidIdentifier(checkpoint.parentCheckpointId, 'Parent checkpoint id')
277 }
278 if (!Number.isFinite(checkpoint.createdAt)) {
279 throw new SandboxCheckpointInvalidEntryError(
280 'Checkpoint createdAt must be a finite number',
281 )
282 }
283 validateEntries(checkpoint)
284 validateArtifacts(checkpoint)
285}
286
287function blobKeys(checkpoint: SandboxCheckpoint): Set<string> {
288 const keys = new Set<string>()
289 for (const entry of checkpoint.files) {
290 if (entry.kind === 'file') keys.add(entry.blobKey)
291 }
292 for (const artifact of checkpoint.artifacts) keys.add(artifact.blobKey)
293 return keys
294}
295
296class MemorySnapshotCheckpointStore implements ForkCapableSandboxCheckpointStore {
297 private readonly now = () => Date.now()
298 private readonly leaseDurationMs = 120_000
299 private readonly renewAfterMs = 45_000
300
301 constructor(private readonly state: MemorySnapshotState) {}
302
303 async get(id: string): Promise<SandboxCheckpoint | null> {
304 assertValidIdentifier(id, 'Checkpoint id')
305 const checkpoint = this.state.checkpoints.get(id)
306 return checkpoint ? clone(checkpoint) : null
307 }
308
309 async list(threadId: string): Promise<Array<SandboxCheckpoint>> {
310 assertValidIdentifier(threadId, 'Thread id')
311 return [...this.state.checkpoints.values()]
312 .filter((checkpoint) => checkpoint.threadId === threadId)
313 .sort((a, b) => a.createdAt - b.createdAt || compare(a.id, b.id))
314 .map(clone)
315 }
316
317 async getHead(threadId: string): Promise<string | null> {
318 assertValidIdentifier(threadId, 'Thread id')
319 return this.state.heads.get(threadId) ?? null
320 }
321
322 async append(input: {
323 checkpoint: SandboxCheckpoint
324 expectedHeadId: string | null
325 writer: SandboxCheckpointWriter
326 }): Promise<{ headId: string }> {
327 const checkpoint = clone(input.checkpoint)
328 const { expectedHeadId, writer } = input
329 assertValidIdentifier(checkpoint.id, 'Checkpoint id')
330 assertValidIdentifier(checkpoint.threadId, 'Checkpoint thread id')
331 assertValidIdentifier(writer.threadId, 'Writer thread id')
332 if (expectedHeadId !== null) {
333 assertValidIdentifier(expectedHeadId, 'Expected head id')
334 }
335 if (checkpoint.parentCheckpointId != null) {
336 assertValidIdentifier(
337 checkpoint.parentCheckpointId,
338 'Parent checkpoint id',
339 )
340 }
341 if (writer.threadId !== checkpoint.threadId) {
342 throw new SandboxCheckpointWriterLostError(
343 'Checkpoint writer thread does not match checkpoint thread',
344 )
345 }
346 validateCheckpoint(checkpoint)
347
348 // Re-check live state after staging because cloning caller data may
349 // re-enter append and advance this thread's head.
350 this.assertWriter(writer, checkpoint.threadId)
351 if (this.state.checkpoints.has(checkpoint.id)) {
352 throw new SandboxCheckpointDuplicateIdError(
353 `Checkpoint '${checkpoint.id}' already exists`,
354 )
355 }
356 const actualHeadId = this.state.heads.get(checkpoint.threadId) ?? null
357 if (actualHeadId !== expectedHeadId) {
358 throw new SandboxCheckpointConflictError(
359 `Expected head '${expectedHeadId}', but thread '${checkpoint.threadId}' is at '${actualHeadId}'`,
360 )
361 }
362 const parentCheckpointId = checkpoint.parentCheckpointId ?? null
363 if (parentCheckpointId !== expectedHeadId) {
364 throw new SandboxCheckpointParentMismatchError(
365 `Checkpoint '${checkpoint.id}' parent does not match expected head`,
366 )
367 }
368 const stored = { ...checkpoint, parentCheckpointId }
369 const keys = blobKeys(stored)
370 this.state.checkpoints.set(stored.id, stored)
371 this.state.heads.set(stored.threadId, stored.id)
372 for (const key of keys) {
373 this.state.references.set(key, (this.state.references.get(key) ?? 0) + 1)
374 }
375 return { headId: stored.id }
376 }
377
378 async deleteHead(input: {
379 threadId: string
380 checkpointId: string
381 writer: SandboxCheckpointWriter
382 }): Promise<void> {
383 const { threadId, checkpointId, writer } = input
384 assertValidIdentifier(threadId, 'Thread id')
385 assertValidIdentifier(checkpointId, 'Checkpoint id')
386 assertValidIdentifier(writer.threadId, 'Writer thread id')
387 if (writer.threadId !== threadId) {
388 throw new SandboxCheckpointWriterLostError(
389 'Checkpoint writer thread does not match operation thread',
390 )
391 }
392 this.assertWriter(writer, threadId)
393 if ((this.state.heads.get(threadId) ?? null) !== checkpointId) {
394 throw new SandboxCheckpointNotHeadError(
395 `Checkpoint '${checkpointId}' is not the current head of thread '${threadId}'`,
396 )
397 }
398 const checkpoint = this.state.checkpoints.get(checkpointId)
399 if (!checkpoint) {
400 throw new SandboxCheckpointNotHeadError(
401 `Checkpoint '${checkpointId}' does not exist`,
402 )
403 }
404 this.state.checkpoints.delete(checkpointId)
405 if (checkpoint.parentCheckpointId) {
406 this.state.heads.set(threadId, checkpoint.parentCheckpointId)
407 } else {
408 this.state.heads.delete(threadId)
409 }
410 for (const key of blobKeys(checkpoint)) {
411 const references = (this.state.references.get(key) ?? 0) - 1
412 if (references > 0) this.state.references.set(key, references)
413 else this.state.references.delete(key)
414 }
415 }
416
417 async acquireWriter(threadId: string): Promise<SandboxCheckpointWriterLease> {
418 assertValidIdentifier(threadId, 'Thread id')
419 const current = this.state.writers.get(threadId)
420 if (current && current.expiresAt > this.now()) {
421 throw new SandboxCheckpointWriterConflictError(
422 `Thread '${threadId}' already has an active checkpoint writer`,
423 )
424 }
425 const fence = (this.state.fences.get(threadId) ?? 0) + 1
426 this.state.fences.set(threadId, fence)
427 const ownerToken = globalThis.crypto.randomUUID()
428 const lease = {
429 threadId,
430 ownerToken,
431 fence,
432 expiresAt: this.now() + this.leaseDurationMs,
433 }
434 this.state.writers.set(threadId, lease)
435 return {
436 ...lease,
437 get expiresAt() {
438 return lease.expiresAt
439 },
440 renewAfterMs: this.renewAfterMs,
441 renew: async () => {
442 this.assertWriter(lease, threadId)
443 lease.expiresAt = this.now() + this.leaseDurationMs
444 return { expiresAt: lease.expiresAt }
445 },
446 release: async () => {
447 const currentLease = this.state.writers.get(threadId)
448 if (
449 currentLease?.ownerToken === ownerToken &&
450 currentLease.fence === fence
451 ) {
452 this.state.writers.delete(threadId)
453 }
454 },
455 }
456 }
457
458 async listBlobReferences(): Promise<
459 Array<{ key: string; references: number }>
460 > {
461 return [...this.state.references.entries()]
462 .sort(([a], [b]) => compare(a, b))
463 .map(([key, references]) => ({ key, references }))
464 }
465
466 async forkFromCheckpoint(
467 input: SandboxCheckpointForkInput,
468 ): Promise<{ checkpoint: SandboxCheckpoint }> {
469 const sourceThreadId = input.sourceThreadId
470 const sourceCheckpointId = input.sourceCheckpointId
471 const destinationThreadId = input.destinationThreadId
472 const destinationCheckpointId = input.destinationCheckpointId
473 const createdAt = input.createdAt
474 const suppliedWriter = input.writer
475 const writer: SandboxCheckpointWriter = {
476 threadId: suppliedWriter.threadId,
477 ownerToken: suppliedWriter.ownerToken,
478 fence: suppliedWriter.fence,
479 }
480
481 assertValidIdentifier(sourceThreadId, 'Source thread id')
482 assertValidIdentifier(sourceCheckpointId, 'Source checkpoint id')
483 assertValidIdentifier(destinationThreadId, 'Destination thread id')
484 assertValidIdentifier(destinationCheckpointId, 'Destination checkpoint id')
485 assertValidIdentifier(writer.threadId, 'Writer thread id')
486 if (!Number.isFinite(createdAt)) {
487 throw new SandboxCheckpointInvalidEntryError(
488 'Fork checkpoint createdAt must be a finite number',
489 )
490 }
491 if (sourceThreadId === destinationThreadId) {
492 throw new SandboxCheckpointError(
493 'SANDBOX_SNAPSHOT_FORK_SOURCE_THREAD_MISMATCH',
494 'Source and destination threads must differ',
495 )
496 }
497 const source = this.state.checkpoints.get(sourceCheckpointId)
498 if (!source) {
499 throw new SandboxCheckpointError(
500 'SANDBOX_SNAPSHOT_FORK_SOURCE_NOT_FOUND',
501 'Source checkpoint was not found',
502 )
503 }
504 if (source.threadId !== sourceThreadId) {
505 throw new SandboxCheckpointError(
506 'SANDBOX_SNAPSHOT_FORK_SOURCE_THREAD_MISMATCH',
507 'Source checkpoint belongs to another thread',
508 )
509 }
510 if (writer.threadId !== destinationThreadId) {
511 throw new SandboxCheckpointWriterLostError(
512 'Checkpoint writer thread does not match destination thread',
513 )
514 }
515 this.assertWriter(writer, destinationThreadId)
516 this.assertDestinationEmpty(destinationThreadId, destinationCheckpointId)
517
518 const stagedCheckpoint: SandboxCheckpoint = clone({
519 id: destinationCheckpointId,
520 threadId: destinationThreadId,
521 parentCheckpointId: null,
522 createdAt,
523 reason: 'fork-root',
524 files: source.files,
525 conversation: source.conversation,
526 artifacts: source.artifacts,
527 })
528 validateCheckpoint(stagedCheckpoint)
529 const stagedTranscript = clone([...stagedCheckpoint.conversation])
530 const result = { checkpoint: clone(stagedCheckpoint) }
531 const stagedReferences = [...blobKeys(stagedCheckpoint)].map((key) => ({
532 key,
533 references: (this.state.references.get(key) ?? 0) + 1,
534 }))
535
536 // Cloning can invoke user-defined getters. Revalidate immediately before
537 // the synchronous publication block so a reentrant save is never lost.
538 this.assertWriter(writer, destinationThreadId)
539 this.assertDestinationEmpty(destinationThreadId, destinationCheckpointId)
540
541 this.state.messages.set(stagedCheckpoint.threadId, stagedTranscript)
542 this.state.checkpoints.set(stagedCheckpoint.id, stagedCheckpoint)
543 this.state.heads.set(stagedCheckpoint.threadId, stagedCheckpoint.id)
544 for (const reference of stagedReferences) {
545 this.state.references.set(reference.key, reference.references)
546 }
547 return result
548 }
549
550 private assertDestinationEmpty(
551 destinationThreadId: string,
552 destinationCheckpointId: string,
553 ): void {
554 if (
555 this.state.messages.has(destinationThreadId) ||
556 [...this.state.runs.values()].some(
557 (value) => value.threadId === destinationThreadId,
558 ) ||
559 [...this.state.generations.values()].some(
560 (value) => value.threadId === destinationThreadId,
561 ) ||
562 [...this.state.interrupts.values()].some(
563 (value) => value.threadId === destinationThreadId,
564 ) ||
565 [...this.state.artifacts.values()].some(
566 (value) => value.threadId === destinationThreadId,
567 ) ||
568 [...this.state.checkpoints.values()].some(
569 (value) => value.threadId === destinationThreadId,
570 ) ||
571 this.state.heads.has(destinationThreadId) ||
572 this.state.checkpoints.has(destinationCheckpointId)
573 ) {
574 throw new SandboxCheckpointError(
575 'SANDBOX_SNAPSHOT_FORK_DESTINATION_NOT_EMPTY',
576 'Destination thread is not empty',
577 )
578 }
579 }
580
581 private assertWriter(
582 writer: SandboxCheckpointWriter,
583 threadId: string,
584 ): void {
585 const current = this.state.writers.get(threadId)
586 if (
587 !current ||
588 current.ownerToken !== writer.ownerToken ||
589 current.fence !== writer.fence ||
590 current.expiresAt <= this.now()
591 ) {
592 throw new SandboxCheckpointWriterLostError(
593 `Checkpoint writer lease for thread '${threadId}' is no longer current`,
594 )
595 }
596 }
597}
598
599async function bodyBytes(body: BlobBody): Promise<Uint8Array> {
600 if (typeof body === 'string') return encoder.encode(body)
601 if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0))
602 if (ArrayBuffer.isView(body))
603 return new Uint8Array(
604 body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),
605 )
606 if (typeof Blob !== 'undefined' && body instanceof Blob)
607 return new Uint8Array(await body.arrayBuffer())
608 if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {
609 const reader = body.getReader()
610 const parts: Array<Uint8Array> = []
611 try {
612 for (;;) {
613 const next = await reader.read()
614 if (next.done) break
615 parts.push(new Uint8Array(next.value))
616 }
617 } finally {
618 reader.releaseLock()
619 }
620 const result = new Uint8Array(
621 parts.reduce((total, part) => total + part.byteLength, 0),
622 )
623 let offset = 0
624 for (const part of parts) {
625 result.set(part, offset)
626 offset += part.byteLength
627 }
628 return result
629 }
630 throw new TypeError('Unsupported blob body.')
631}
632
633export async function memorySandboxSnapshots(
634 options: MemorySandboxSnapshotsOptions = {},
635): Promise<MemorySandboxSnapshots> {
636 const { persistence, checkpoints } = await createMemorySandboxSnapshots()
637 return createSandboxSnapshots({
638 persistence,
639 checkpoints,
640 ...options,
641 })
642}
643
644async function createMemorySandboxSnapshots(): Promise<{
645 persistence: MemorySnapshotPersistence
646 checkpoints: ForkCapableSandboxCheckpointStore
647}> {
648 const messages = new Map<string, Array<ModelMessage>>()
649 const runs = new Map<string, RunRecord>()
650 const generations = new Map<string, GenerationRunRecord>()
651 const interrupts = new Map<string, InterruptRecord>()
652 const metadata = new Map<string, Map<string, unknown>>()
653 const artifacts = new Map<string, ArtifactRecord>()
654 const blobs = new Map<string, { record: BlobRecord; bytes: Uint8Array }>()
655 const state: MemorySnapshotState = {
656 messages,
657 runs,
658 generations,
659 interrupts,
660 metadata,
661 artifacts,
662 blobs,
663 checkpoints: new Map(),
664 heads: new Map(),
665 writers: new Map(),
666 fences: new Map(),
667 references: new Map(),
668 }
669 let etag = 0
670 const persistence: MemorySnapshotPersistence = {
671 stores: {
672 messages: {
673 loadThread: async (threadId: string) =>
674 messages.get(threadId)?.slice() ?? [],
675 saveThread: async (threadId: string, value: Array<ModelMessage>) => {
676 messages.set(threadId, value.slice())
677 },
678 },
679 runs: {
680 createOrResume: async (input: {
681 runId: string
682 threadId: string
683 status?: RunRecord['status']
684 startedAt: number
685 parentRunId?: string
686 subagentRunId?: string
687 name?: string
688 }) => {
689 const existing = runs.get(input.runId)
690 if (existing) return existing
691 const record: RunRecord = {
692 ...input,
693 status: input.status ?? 'running',
694 }
695 runs.set(record.runId, record)
696 return record
697 },
698 update: async (runId: string, patch: Partial<RunRecord>) => {
699 const value = runs.get(runId)
700 if (value) runs.set(runId, { ...value, ...patch })
701 },
702 get: async (runId: string) => runs.get(runId) ?? null,
703 findActiveRun: async (threadId: string) =>
704 [...runs.values()]
705 .filter(
706 (run) => run.threadId === threadId && run.status === 'running',
707 )
708 .sort((a, b) => b.startedAt - a.startedAt)[0] ?? null,
709 listByThread: async (threadId: string) =>
710 [...runs.values()]
711 .filter((run) => run.threadId === threadId)
712 .sort((a, b) => a.startedAt - b.startedAt),
713 listByParentRun: async (parentRunId: string) =>
714 [...runs.values()]
715 .filter((run) => run.parentRunId === parentRunId)
716 .sort((a, b) => a.startedAt - b.startedAt),
717 listReclaimable: async (input: { now: number; ttlMs: number }) =>
718 [...runs.values()].filter(
719 (run) =>
720 run.status === 'running' &&
721 run.detachedSince !== undefined &&
722 run.detachedSince <= input.now - input.ttlMs,
723 ),
724 },
725 generationRuns: {
726 createOrResume: async (
727 input: Pick<
728 GenerationRunRecord,
729 | 'runId'
730 | 'threadId'
731 | 'activity'
732 | 'provider'
733 | 'model'
734 | 'startedAt'
735 > & { status?: GenerationRunRecord['status'] },
736 ) => {
737 const value = generations.get(input.runId) ?? {
738 ...input,
739 status: input.status ?? 'running',
740 }
741 generations.set(input.runId, value)
742 return value
743 },
744 update: async (runId: string, patch: Partial<GenerationRunRecord>) => {
745 const value = generations.get(runId)
746 if (value) generations.set(runId, { ...value, ...patch })
747 },
748 get: async (runId: string) => generations.get(runId) ?? null,
749 findLatestForThread: async (threadId: string) =>
750 [...generations.values()]
751 .filter((run) => run.threadId === threadId)
752 .sort((a, b) => b.startedAt - a.startedAt)[0] ?? null,
753 },
754 interrupts: {
755 create: async (
756 record: Omit<InterruptRecord, 'status' | 'resolvedAt'>,
757 ) => {
758 if (!interrupts.has(record.interruptId))
759 interrupts.set(record.interruptId, { ...record, status: 'pending' })
760 },
761 resolve: async (id: string, response?: unknown) => {
762 const value = interrupts.get(id)
763 if (value)
764 interrupts.set(id, {
765 ...value,
766 status: 'resolved',
767 resolvedAt: Date.now(),
768 response,
769 })
770 },
771 cancel: async (id: string) => {
772 const value = interrupts.get(id)
773 if (value)
774 interrupts.set(id, {
775 ...value,
776 status: 'cancelled',
777 resolvedAt: Date.now(),
778 })
779 },
780 get: async (id: string) => interrupts.get(id) ?? null,
781 list: async (threadId: string) =>
782 [...interrupts.values()]
783 .filter((value) => value.threadId === threadId)
784 .sort((a, b) => a.requestedAt - b.requestedAt),
785 listPending: async (threadId: string) =>
786 [...interrupts.values()]
787 .filter(
788 (value) =>
789 value.threadId === threadId && value.status === 'pending',
790 )
791 .sort((a, b) => a.requestedAt - b.requestedAt),
792 listByRun: async (runId: string) =>
793 [...interrupts.values()]
794 .filter((value) => value.runId === runId)
795 .sort((a, b) => a.requestedAt - b.requestedAt),
796 listPendingByRun: async (runId: string) =>
797 [...interrupts.values()]
798 .filter(
799 (value) => value.runId === runId && value.status === 'pending',
800 )
801 .sort((a, b) => a.requestedAt - b.requestedAt),
802 },
803 metadata: {
804 get: async (namespace: string, key: string) => {
805 const bucket = metadata.get(namespace)
806 return bucket?.has(key) ? bucket.get(key) : null
807 },
808 set: async (namespace: string, key: string, value: unknown) => {
809 let bucket = metadata.get(namespace)
810 if (!bucket) {
811 bucket = new Map()
812 metadata.set(namespace, bucket)
813 }
814 bucket.set(key, value)
815 },
816 delete: async (namespace: string, key: string) => {
817 metadata.get(namespace)?.delete(key)
818 },
819 },
820 artifacts: {
821 save: async (value: ArtifactRecord) => {
822 artifacts.set(value.artifactId, { ...value })
823 },
824 get: async (id: string) => artifacts.get(id) ?? null,
825 list: async (runId: string) =>
826 [...artifacts.values()]
827 .filter((value) => value.runId === runId)
828 .sort(
829 (a, b) =>
830 a.createdAt - b.createdAt ||
831 compare(a.artifactId, b.artifactId),
832 ),
833
834 listForThread: async (threadId: string) =>
835 [...artifacts.values()]
836 .filter((value) => value.threadId === threadId)
837 .sort(
838 (a, b) =>
839 a.createdAt - b.createdAt ||
840 compare(a.artifactId, b.artifactId),
841 ),
842
843 delete: async (id: string) => {
844 artifacts.delete(id)
845 },
846 deleteForRun: async (runId: string) => {
847 for (const [id, value] of artifacts)
848 if (value.runId === runId) artifacts.delete(id)
849 },
850 },
851 blobs: {
852 put: async (
853 key: string,
854 body: BlobBody,
855 putOptions?: {
856 contentType?: string
857 customMetadata?: Record<string, string>
858 },
859 ) => {
860 const bytes = await bodyBytes(body)
861 const now = Date.now()
862 const record: BlobRecord = {
863 key,
864 size: bytes.byteLength,
865 etag: String(++etag),
866 contentType:
867 putOptions?.contentType ??
868 (typeof Blob !== 'undefined' && body instanceof Blob
869 ? body.type || undefined
870 : undefined),
871 customMetadata: putOptions?.customMetadata
872 ? { ...putOptions.customMetadata }
873 : undefined,
874 createdAt: blobs.get(key)?.record.createdAt ?? now,
875 updatedAt: now,
876 }
877 blobs.set(key, { record, bytes: new Uint8Array(bytes) })
878 return clone(record)
879 },
880 get: async (key: string, getOptions?: BlobGetOptions) => {
881 const value = blobs.get(key)
882 if (!value) return null
883 const range = getOptions?.range
884 ? resolveBlobRange(value.bytes.byteLength, getOptions.range)
885 : { offset: 0, length: value.bytes.byteLength }
886 const bytes = value.bytes.slice(
887 range.offset,
888 range.offset + range.length,
889 )
890 return {
891 ...clone(value.record),
892 ...(getOptions?.range ? { range } : {}),
893 body: new Blob([bytes]).stream(),
894 arrayBuffer: async () =>
895 bytes.buffer.slice(
896 bytes.byteOffset,
897 bytes.byteOffset + bytes.byteLength,
898 ),
899 text: async () => new TextDecoder().decode(bytes),
900 }
901 },
902 head: async (key: string) => clone(blobs.get(key)?.record ?? null),
903 delete: async (key: string) => {
904 blobs.delete(key)
905 },
906 list: async (listOptions?: {
907 prefix?: string
908 cursor?: string
909 limit?: number
910 }) => {
911 const keys = [...blobs.keys()]
912 .filter((key) => key.startsWith(listOptions?.prefix ?? ''))
913 .filter(
914 (key) =>
915 listOptions?.cursor === undefined || key > listOptions.cursor,
916 )
917 .sort()
918 if (listOptions?.limit === 0) return { objects: [], truncated: false }
919 const page =
920 listOptions?.limit === undefined
921 ? keys
922 : keys.slice(0, listOptions.limit)
923 const truncated =
924 listOptions?.limit !== undefined && keys.length > page.length
925 const objects = page.map((key) => {
926 const value = blobs.get(key)
927 if (!value) throw new Error(`Missing blob for listed key: ${key}`)
928 return value.record
929 })
930 return {
931 objects: clone(objects),
932 ...(truncated ? { cursor: page.at(-1), truncated: true } : {}),
933 }
934 },
935 },
936 },
937 }
938 const checkpointStore = new MemorySnapshotCheckpointStore(state)
939 return {
940 persistence,
941 checkpoints: checkpointStore,
942 }
943}