Open History to see the last commit
1import type { SandboxHandle, SandboxFsStat } from './contracts'
2import type {
3 SandboxSnapshotArtifact,
4 SandboxSnapshotEntry,
5} from './checkpoint-store'
6import type { MemoryArtifactRecord as ArtifactRecord } from './memory-snapshot-types'
7
8type SnapshotBlobStore = {
9 get: (key: string) => Promise<{
10 arrayBuffer: () => Promise<ArrayBuffer>
11 } | null>
12 head: (key: string) => Promise<unknown>
13 put: (key: string, body: Uint8Array) => Promise<unknown>
14}
15
16export interface SandboxSnapshotPolicy {
17 /** Exact workspace projection hash, when known. */
18 workspaceHash?: string
19 include?: (path: string, kind: 'file' | 'dir') => boolean
20 exclude?: (path: string, kind: 'file' | 'dir') => boolean
21 redact?: (input: {
22 path: string
23 bytes: Uint8Array
24 resolvedSecrets: Readonly<Record<string, string>>
25 }) => Uint8Array
26}
27
28export interface SandboxSnapshotBundle {
29 blobs: SnapshotBlobStore
30 /** Internal resolved workspace root. */
31 workspaceRoot?: string
32 /** Internal persistence stores used to capture immutable artifact bytes. */
33 artifacts?: {
34 listForThread: (threadId: string) => Promise<ReadonlyArray<ArtifactRecord>>
35 }
36}
37
38export type SandboxSnapshotErrorCode =
39 | 'SANDBOX_SNAPSHOT_INVALID_TOOL_INPUT'
40 | 'SANDBOX_SNAPSHOT_MISSING_SANDBOX'
41 | 'SANDBOX_SNAPSHOT_MISSING_INSTANCES'
42 | 'SANDBOX_SNAPSHOT_MISSING_PERSISTENCE_STORES'
43 | 'SANDBOX_SNAPSHOT_MISSING_REUSABLE_SANDBOX'
44 | 'SANDBOX_SNAPSHOT_REUSE_NONE'
45 | 'SANDBOX_SNAPSHOT_MISSING_CHECKPOINT'
46 | 'SANDBOX_SNAPSHOT_MISSING_CHECKPOINT_ARTIFACT'
47 | 'SANDBOX_SNAPSHOT_FOREIGN_CHECKPOINT_ARTIFACT'
48 | 'SANDBOX_SNAPSHOT_INVALID_ARTIFACT_BYTES'
49 | 'SANDBOX_SNAPSHOT_FORK_UNAVAILABLE'
50 | 'SANDBOX_SNAPSHOT_INVALID_PATH'
51 | 'SANDBOX_SNAPSHOT_INVALID_WORKSPACE'
52 | 'SANDBOX_SNAPSHOT_LSTAT_REQUIRED'
53 | 'SANDBOX_SNAPSHOT_UNSUPPORTED_ENTRY'
54 | 'SANDBOX_SNAPSHOT_MISSING_BLOB'
55 | 'SANDBOX_SNAPSHOT_INVALID_BLOB'
56 | 'SANDBOX_SNAPSHOT_ARTIFACT_SUPPORT_REQUIRED'
57 | 'SANDBOX_SNAPSHOT_MISSING_ARTIFACT_BLOB'
58
59export class SandboxSnapshotError extends Error {
60 readonly code: SandboxSnapshotErrorCode
61 constructor(code: SandboxSnapshotErrorCode, message: string) {
62 super(message)
63 this.name = 'SandboxSnapshotError'
64 this.code = code
65 }
66}
67
68const DEFAULT_ROOT = '/workspace'
69const PROJECTED_SKILL_ROOTS = new Set(['.claude', '.codex', '.grok'])
70
71function isFrameworkGeneratedSymlinkPath(path: string): boolean {
72 if (path === 'CLAUDE.md' || path === 'GEMINI.md') return true
73 const segments = path.split('/')
74 return (
75 segments.length === 3 &&
76 PROJECTED_SKILL_ROOTS.has(segments[0] ?? '') &&
77 segments[1] === 'skills'
78 )
79}
80
81function defaultExcluded(path: string, workspaceHash?: string): boolean {
82 const segments = path.split('/')
83 return (
84 isFrameworkGeneratedSymlinkPath(path) ||
85 segments.some(
86 (segment) =>
87 segment === '.git' ||
88 segment === 'node_modules' ||
89 segment.startsWith('.env'),
90 ) ||
91 (workspaceHash !== undefined &&
92 segments[0] === `.tanstack-projected-${workspaceHash}`)
93 )
94}
95
96function isProtectedPath(path: string, workspaceHash?: string): boolean {
97 return (
98 workspaceHash !== undefined &&
99 path.split('/')[0] === `.tanstack-projected-${workspaceHash}`
100 )
101}
102
103const FILE_BLOB_KEY = /^sandbox-files\/sha256\/[0-9a-f]{64}$/
104
105export function defaultSandboxSnapshotPolicy(
106 workspaceHash?: string,
107): SandboxSnapshotPolicy {
108 return {
109 workspaceHash,
110 exclude: (path) => defaultExcluded(path, workspaceHash),
111 }
112}
113
114/**
115 * Keep default exclusions unless the caller passed `exclude`.
116 * `include` or `redact` alone must not capture `.env`, `.git`, or
117 * `node_modules`.
118 */
119export function resolveSandboxSnapshotPolicy(
120 supplied: SandboxSnapshotPolicy | undefined,
121 workspaceHash?: string,
122): SandboxSnapshotPolicy {
123 const defaults = defaultSandboxSnapshotPolicy(
124 workspaceHash ?? supplied?.workspaceHash,
125 )
126 if (supplied === undefined) return defaults
127 const include = supplied.include
128 const exclude = supplied.exclude
129 const redact = supplied.redact
130 const suppliedWorkspaceHash = supplied.workspaceHash
131 return {
132 ...(suppliedWorkspaceHash === undefined
133 ? {}
134 : { workspaceHash: suppliedWorkspaceHash }),
135 ...(workspaceHash === undefined ? {} : { workspaceHash }),
136 ...(include === undefined ? {} : { include }),
137 exclude: exclude ?? defaults.exclude,
138 ...(redact === undefined ? {} : { redact }),
139 }
140}
141
142function normalize(path: string): string {
143 if (path.includes('\\'))
144 throw new SandboxSnapshotError(
145 'SANDBOX_SNAPSHOT_INVALID_PATH',
146 `Unsafe snapshot path '${path}'`,
147 )
148 const value = path
149 if (
150 !value ||
151 value.includes('\0') ||
152 value.startsWith('/') ||
153 /^[A-Za-z]:/.test(value) ||
154 value.endsWith('/')
155 )
156 throw new SandboxSnapshotError(
157 'SANDBOX_SNAPSHOT_INVALID_PATH',
158 `Unsafe snapshot path '${path}'`,
159 )
160 const parts = value.split('/')
161 if (
162 parts.some((part) => !part || part === '.' || part === '..') ||
163 parts.join('/') !== value
164 )
165 throw new SandboxSnapshotError(
166 'SANDBOX_SNAPSHOT_INVALID_PATH',
167 `Unsafe snapshot path '${path}'`,
168 )
169 return value
170}
171
172function childPath(
173 parent: string,
174 child: { name: string; path: string },
175): { absolute: string; relative: string } {
176 if (
177 !child.name ||
178 child.name.includes('/') ||
179 child.name.includes('\\') ||
180 child.name.includes('\0') ||
181 child.name === '.' ||
182 child.name === '..'
183 )
184 throw new SandboxSnapshotError(
185 'SANDBOX_SNAPSHOT_INVALID_WORKSPACE',
186 `Invalid workspace entry '${child.name}'`,
187 )
188 const absolute = `${parent}/${child.name}`
189 if (child.path !== absolute)
190 throw new SandboxSnapshotError(
191 'SANDBOX_SNAPSHOT_INVALID_WORKSPACE',
192 `Invalid workspace entry path '${child.path}'`,
193 )
194 return { absolute, relative: child.name }
195}
196
197function lstat(
198 handle: SandboxHandle,
199 path: string,
200): Promise<SandboxFsStat | undefined> {
201 if (!handle.fs.lstat)
202 throw new SandboxSnapshotError(
203 'SANDBOX_SNAPSHOT_LSTAT_REQUIRED',
204 'Snapshot operations require fs.lstat',
205 )
206 return handle.fs.lstat(path)
207}
208
209function assertSupported(stat: SandboxFsStat, path: string): void {
210 if (
211 stat.type === 'symlink' ||
212 stat.type === 'other' ||
213 (stat.type === 'file' && (stat.mode & 0o111) !== 0)
214 )
215 throw new SandboxSnapshotError(
216 'SANDBOX_SNAPSHOT_UNSUPPORTED_ENTRY',
217 `Unsupported entry '${path}'`,
218 )
219}
220
221function included(
222 path: string,
223 kind: 'file' | 'dir',
224 policy: SandboxSnapshotPolicy,
225): boolean {
226 if (policy.exclude?.(path, kind)) return false
227 return kind === 'dir' ? true : (policy.include?.(path, kind) ?? true)
228}
229
230async function hash(bytes: Uint8Array): Promise<string> {
231 // TypeScript requires an ArrayBuffer-backed view; Uint8Array can also use SharedArrayBuffer.
232 const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(bytes))
233 return Array.from(new Uint8Array(digest), (byte) =>
234 byte.toString(16).padStart(2, '0'),
235 ).join('')
236}
237
238async function putIfAbsent(
239 blobs: SnapshotBlobStore,
240 bytes: Uint8Array,
241 keys: Map<string, string>,
242): Promise<{ key: string; size: number }> {
243 const key = `sandbox-files/sha256/${await hash(bytes)}`
244 if (!keys.has(key)) {
245 if (!(await blobs.head(key))) await blobs.put(key, bytes)
246 keys.set(key, key)
247 }
248 return { key, size: bytes.byteLength }
249}
250
251async function redactBytes(
252 bytes: Uint8Array,
253 resolvedSecrets: Readonly<Record<string, string>>,
254): Promise<Uint8Array> {
255 const output = bytes.slice()
256 const redacted = new Uint8Array(bytes.length)
257 const secrets = Object.values(resolvedSecrets)
258 .filter(Boolean)
259 .map((secret) => new TextEncoder().encode(secret))
260 .sort((a, b) => b.length - a.length || compareBytes(a, b))
261 for (const needle of secrets) {
262 if (!needle.length || needle.length > bytes.length) continue
263 for (let start = 0; start <= bytes.length - needle.length; start++) {
264 let match = true
265 for (let index = 0; index < needle.length; index++)
266 if (bytes[start + index] !== needle[index]) {
267 match = false
268 break
269 }
270 if (!match) continue
271 if (match) redacted.fill(1, start, start + needle.length)
272 }
273 }
274 for (let index = 0; index < output.length; index++)
275 if (redacted[index]) output[index] = 0
276 return output
277}
278
279export async function captureSandboxFiles(
280 handle: SandboxHandle,
281 bundle: SandboxSnapshotBundle,
282 suppliedPolicy: SandboxSnapshotPolicy = defaultSandboxSnapshotPolicy(),
283 resolvedSecrets: Readonly<Record<string, string>> = {},
284): Promise<{ files: Array<SandboxSnapshotEntry> }> {
285 const policy = resolveSandboxSnapshotPolicy(
286 suppliedPolicy,
287 suppliedPolicy.workspaceHash,
288 )
289 if (!handle.fs.lstat)
290 throw new SandboxSnapshotError(
291 'SANDBOX_SNAPSHOT_LSTAT_REQUIRED',
292 'Snapshot capture requires fs.lstat',
293 )
294 const rootPath = bundle.workspaceRoot ?? DEFAULT_ROOT
295 const root = await lstat(handle, rootPath)
296 if (!root || root.type !== 'dir')
297 throw new SandboxSnapshotError(
298 'SANDBOX_SNAPSHOT_INVALID_WORKSPACE',
299 'Snapshot workspace is missing or is not a directory',
300 )
301 assertSupported(root, rootPath)
302 const files: Array<SandboxSnapshotEntry> = []
303 const destinationKeys = new Map<string, string>()
304 const walk = async (absolute: string, relative: string): Promise<boolean> => {
305 const stat = await lstat(handle, absolute)
306 if (!stat)
307 throw new SandboxSnapshotError(
308 'SANDBOX_SNAPSHOT_INVALID_WORKSPACE',
309 `Snapshot entry disappeared '${relative}'`,
310 )
311 assertSupported(stat, relative)
312 if (stat.type !== 'file' && stat.type !== 'dir')
313 throw new SandboxSnapshotError(
314 'SANDBOX_SNAPSHOT_UNSUPPORTED_ENTRY',
315 `Unsupported entry '${relative}'`,
316 )
317 if (
318 relative &&
319 (isProtectedPath(relative, policy.workspaceHash) ||
320 policy.exclude?.(relative, stat.type))
321 )
322 return false
323 if (stat.type === 'file') {
324 const path = normalize(relative)
325 if (policy.include && !policy.include(path, 'file')) return false
326 let bytes = await handle.fs.readBytes(absolute)
327 if (policy.redact) bytes = policy.redact({ path, bytes, resolvedSecrets })
328 bytes = await redactBytes(bytes, resolvedSecrets)
329 const blob = await putIfAbsent(bundle.blobs, bytes, destinationKeys)
330 files.push({ path, kind: 'file', blobKey: blob.key, size: blob.size })
331 return true
332 }
333 const children = await handle.fs.list(absolute)
334 let hasCapturedChild = false
335 for (const child of children) {
336 const childEntry = childPath(absolute, child)
337 const childRelative = relative
338 ? `${relative}/${childEntry.relative}`
339 : childEntry.relative
340 if (
341 isProtectedPath(childRelative, policy.workspaceHash) ||
342 policy.exclude?.(childRelative, child.type)
343 )
344 continue
345 hasCapturedChild =
346 (await walk(childEntry.absolute, childRelative)) || hasCapturedChild
347 }
348 if (
349 relative &&
350 !hasCapturedChild &&
351 (!policy.include || policy.include(relative, 'dir'))
352 )
353 files.push({ path: normalize(relative), kind: 'dir' })
354 return (
355 hasCapturedChild ||
356 (relative !== '' && (!policy.include || policy.include(relative, 'dir')))
357 )
358 }
359 await walk(rootPath, '')
360 files.sort((a, b) => comparePath(a.path, b.path))
361 return { files }
362}
363
364type PlannedEntry = SandboxSnapshotEntry & { path: string }
365type PlannedFile = Extract<PlannedEntry, { kind: 'file' }>
366
367function validateManifest(
368 snapshot: {
369 files: ReadonlyArray<SandboxSnapshotEntry>
370 },
371 policy: SandboxSnapshotPolicy,
372): Array<PlannedEntry> {
373 const paths = new Map<string, PlannedEntry>()
374 for (const entry of snapshot.files) {
375 const path = normalize(entry.path)
376 for (const ancestor of parents(path)) {
377 if (
378 isProtectedPath(ancestor, policy.workspaceHash) ||
379 policy.exclude?.(ancestor, 'dir')
380 )
381 throw new SandboxSnapshotError(
382 'SANDBOX_SNAPSHOT_INVALID_PATH',
383 `Excluded snapshot ancestor '${ancestor}'`,
384 )
385 }
386 if (isProtectedPath(path, policy.workspaceHash))
387 throw new SandboxSnapshotError(
388 'SANDBOX_SNAPSHOT_INVALID_PATH',
389 `Protected snapshot path '${path}'`,
390 )
391 if (
392 !included(path, entry.kind, policy) ||
393 (entry.kind === 'dir' && policy.include?.(path, 'dir') === false)
394 )
395 throw new SandboxSnapshotError(
396 'SANDBOX_SNAPSHOT_INVALID_PATH',
397 `Excluded snapshot path '${path}'`,
398 )
399 if (paths.has(path))
400 throw new SandboxSnapshotError(
401 'SANDBOX_SNAPSHOT_INVALID_PATH',
402 `Duplicate path '${path}'`,
403 )
404 if (entry.kind === 'file') {
405 const { blobKey, size } = entry
406 if (
407 typeof blobKey !== 'string' ||
408 !FILE_BLOB_KEY.test(blobKey) ||
409 typeof size !== 'number' ||
410 !Number.isSafeInteger(size) ||
411 size < 0
412 )
413 throw new SandboxSnapshotError(
414 'SANDBOX_SNAPSHOT_INVALID_PATH',
415 `Invalid file entry '${path}'`,
416 )
417 paths.set(path, { path, kind: 'file', blobKey, size })
418 } else if (entry.kind === 'dir') paths.set(path, { path, kind: 'dir' })
419 else
420 throw new SandboxSnapshotError(
421 'SANDBOX_SNAPSHOT_INVALID_PATH',
422 `Unknown snapshot entry '${path}'`,
423 )
424 }
425 for (const [path] of paths)
426 for (
427 let index = path.indexOf('/');
428 index !== -1;
429 index = path.indexOf('/', index + 1)
430 ) {
431 const parent = paths.get(path.slice(0, index))
432 if (parent?.kind === 'file')
433 throw new SandboxSnapshotError(
434 'SANDBOX_SNAPSHOT_INVALID_PATH',
435 `File ancestor '${parent.path}'`,
436 )
437 }
438 return [...paths.values()]
439}
440
441async function loadBlobs(
442 entries: ReadonlyArray<PlannedEntry>,
443 bundle: SandboxSnapshotBundle,
444): Promise<Map<string, Uint8Array>> {
445 const blobs = new Map<string, Uint8Array>()
446 for (const entry of entries)
447 if (entry.kind === 'file' && !blobs.has(entry.blobKey)) {
448 const object = await bundle.blobs.get(entry.blobKey)
449 if (!object)
450 throw new SandboxSnapshotError(
451 'SANDBOX_SNAPSHOT_MISSING_BLOB',
452 `Missing snapshot blob '${entry.blobKey}'`,
453 )
454 const bytes = new Uint8Array(await object.arrayBuffer())
455 const expectedKey = `sandbox-files/sha256/${await hash(bytes)}`
456 if (entry.blobKey !== expectedKey)
457 throw new SandboxSnapshotError(
458 'SANDBOX_SNAPSHOT_INVALID_BLOB',
459 `Invalid content for snapshot blob '${entry.blobKey}'`,
460 )
461 blobs.set(entry.blobKey, bytes)
462 }
463 for (const entry of entries)
464 if (entry.kind === 'file') {
465 const bytes = blobs.get(entry.blobKey)
466 if (!bytes || bytes.byteLength !== entry.size)
467 throw new SandboxSnapshotError(
468 'SANDBOX_SNAPSHOT_INVALID_BLOB',
469 `Wrong size for snapshot blob '${entry.blobKey}'`,
470 )
471 }
472 return blobs
473}
474
475type CurrentEntry = { path: string; kind: 'file' | 'dir'; protected?: boolean }
476
477async function scanCurrent(
478 handle: SandboxHandle,
479 absolute: string,
480 relative: string,
481 policy: SandboxSnapshotPolicy,
482): Promise<Array<CurrentEntry>> {
483 const stat = await lstat(handle, absolute)
484 if (!stat) return []
485 assertSupported(stat, relative)
486 if (stat.type === 'file') return [{ path: relative, kind: 'file' }]
487 const paths: Array<CurrentEntry> = []
488 for (const child of await handle.fs.list(absolute)) {
489 const childEntry = childPath(absolute, child)
490 const childRelative = relative
491 ? `${relative}/${childEntry.relative}`
492 : childEntry.relative
493 if (isProtectedPath(childRelative, policy.workspaceHash)) {
494 // Preserve the marker and its parent directories without inspecting the
495 // protected tree. The restore planner uses this marker to avoid removing
496 // an ancestor directory that contains it.
497 paths.push({ path: childRelative, kind: 'dir', protected: true })
498 continue
499 }
500 if (!included(childRelative, child.type, policy)) {
501 // Excluded entries are outside the portable snapshot. Keep a protected
502 // marker so removing a parent directory cannot remove them either.
503 paths.push({ path: childRelative, kind: child.type, protected: true })
504 continue
505 }
506 paths.push(
507 ...(await scanCurrent(
508 handle,
509 childEntry.absolute,
510 childRelative,
511 policy,
512 )),
513 )
514 }
515 return relative ? [{ path: relative, kind: 'dir' }, ...paths] : paths
516}
517
518async function scanDestination(
519 handle: SandboxHandle,
520 policy: SandboxSnapshotPolicy,
521 rootPath: string,
522): Promise<Array<CurrentEntry>> {
523 const root = await lstat(handle, rootPath)
524 if (!root || root.type !== 'dir')
525 throw new SandboxSnapshotError(
526 'SANDBOX_SNAPSHOT_INVALID_WORKSPACE',
527 'Snapshot workspace is missing or is not a directory',
528 )
529 assertSupported(root, rootPath)
530 return scanCurrent(handle, rootPath, '', policy)
531}
532
533function parents(path: string): Array<string> {
534 const values: Array<string> = []
535 const parts = path.split('/')
536 for (let length = 1; length < parts.length; length++)
537 values.push(parts.slice(0, length).join('/'))
538 return values
539}
540
541function comparePath(a: string, b: string): number {
542 return compareBytes(new TextEncoder().encode(a), new TextEncoder().encode(b))
543}
544
545function compareBytes(a: Uint8Array, b: Uint8Array): number {
546 for (let i = 0; i < Math.min(a.length, b.length); i++) {
547 const left = a[i]
548 const right = b[i]
549 if (left !== right) return (left ?? 0) - (right ?? 0)
550 }
551 return a.length - b.length
552}
553
554function getRequiredBlob(
555 blobs: ReadonlyMap<string, Uint8Array>,
556 key: string,
557): Uint8Array {
558 const bytes = blobs.get(key)
559 if (!bytes) {
560 throw new SandboxSnapshotError(
561 'SANDBOX_SNAPSHOT_MISSING_BLOB',
562 `Missing snapshot blob '${key}'`,
563 )
564 }
565 return bytes
566}
567
568function depth(path: string): number {
569 return path.split('/').length
570}
571
572function buildRestorePlan(
573 entries: ReadonlyArray<PlannedEntry>,
574 current: ReadonlyArray<CurrentEntry>,
575): {
576 removes: Array<string>
577 mkdirs: Array<string>
578 writes: Array<PlannedFile>
579} {
580 const desired = new Map<string, 'file' | 'dir'>()
581 for (const entry of entries) {
582 desired.set(entry.path, entry.kind)
583 for (const parent of parents(entry.path)) desired.set(parent, 'dir')
584 }
585 const currentKinds = new Map(current.map((entry) => [entry.path, entry.kind]))
586 const candidates = current
587 .filter((entry) => desired.get(entry.path) !== entry.kind)
588 .map((entry) => entry.path)
589 .sort((a, b) => depth(a) - depth(b) || comparePath(a, b))
590 const removes: Array<string> = []
591 for (const path of candidates) {
592 const containsProtectedEntry = current.some(
593 (entry) =>
594 entry.protected &&
595 (entry.path === path || entry.path.startsWith(`${path}/`)),
596 )
597 if (containsProtectedEntry) continue
598 if (removes.some((ancestor) => path.startsWith(`${ancestor}/`))) continue
599 removes.push(path)
600 }
601 const mkdirs = [...desired]
602 .filter(
603 ([path, kind]) => kind === 'dir' && currentKinds.get(path) !== 'dir',
604 )
605 .map(([path]) => path)
606 .sort((a, b) => depth(a) - depth(b) || comparePath(a, b))
607 const writes = entries
608 .filter((entry): entry is PlannedFile => entry.kind === 'file')
609 .sort((a, b) => comparePath(a.path, b.path))
610 return { removes, mkdirs, writes }
611}
612
613export async function restoreSandboxFiles(
614 handle: SandboxHandle,
615 bundle: SandboxSnapshotBundle,
616 snapshot: { files: ReadonlyArray<SandboxSnapshotEntry> },
617 suppliedPolicy: SandboxSnapshotPolicy = defaultSandboxSnapshotPolicy(),
618): Promise<void> {
619 const policy = resolveSandboxSnapshotPolicy(
620 suppliedPolicy,
621 suppliedPolicy.workspaceHash,
622 )
623 if (!handle.fs.lstat)
624 throw new SandboxSnapshotError(
625 'SANDBOX_SNAPSHOT_LSTAT_REQUIRED',
626 'Snapshot restore requires fs.lstat',
627 )
628 const entries = validateManifest(snapshot, policy)
629 const rootPath = bundle.workspaceRoot ?? DEFAULT_ROOT
630 const current = await scanDestination(handle, policy, rootPath)
631 for (const entry of entries) {
632 if (
633 entry.kind === 'file' &&
634 current.some(
635 (currentEntry) =>
636 currentEntry.protected &&
637 currentEntry.path.startsWith(`${entry.path}/`),
638 )
639 )
640 throw new SandboxSnapshotError(
641 'SANDBOX_SNAPSHOT_INVALID_PATH',
642 `Protected current descendant conflicts with '${entry.path}'`,
643 )
644 }
645 const blobs = await loadBlobs(entries, bundle)
646 const plan = buildRestorePlan(entries, current)
647 // Restore is called only while a new sandbox is private to setup. It is not
648 // safe for a caller that allows another process to change the workspace.
649 for (const path of plan.removes) await handle.fs.remove(`${rootPath}/${path}`)
650 for (const path of plan.mkdirs) await handle.fs.mkdir(`${rootPath}/${path}`)
651 for (const entry of plan.writes)
652 await handle.fs.write(
653 `${rootPath}/${entry.path}`,
654 getRequiredBlob(blobs, entry.blobKey),
655 )
656}
657
658export async function captureSandboxArtifacts(
659 bundle: SandboxSnapshotBundle,
660 threadId: string,
661 resolvedSecrets: Readonly<Record<string, string>> = {},
662): Promise<ReadonlyArray<SandboxSnapshotArtifact>> {
663 if (!bundle.artifacts)
664 throw new SandboxSnapshotError(
665 'SANDBOX_SNAPSHOT_ARTIFACT_SUPPORT_REQUIRED',
666 'Snapshot artifact capture requires an artifact store',
667 )
668 const records = await bundle.artifacts.listForThread(threadId)
669 const loaded = new Map<string, Uint8Array>()
670 const destinationKeys = new Map<string, string>()
671 for (const record of records) {
672 const sourceKey = record.blobKey
673 if (loaded.has(sourceKey)) continue
674 const source = await bundle.blobs.get(sourceKey)
675 if (!source)
676 throw new SandboxSnapshotError(
677 'SANDBOX_SNAPSHOT_MISSING_ARTIFACT_BLOB',
678 `Missing artifact source blob '${sourceKey}'`,
679 )
680 loaded.set(sourceKey, new Uint8Array(await source.arrayBuffer()))
681 }
682 const output = []
683 for (const record of records) {
684 const sourceKey = record.blobKey
685 let bytes = getRequiredBlob(loaded, sourceKey)
686 bytes = await redactBytes(bytes, resolvedSecrets)
687 const key = `sandbox-artifacts/sha256/${await hash(bytes)}`
688 if (!destinationKeys.has(key)) {
689 if (!(await bundle.blobs.head(key))) await bundle.blobs.put(key, bytes)
690 destinationKeys.set(key, key)
691 }
692 output.push({
693 artifactId: record.artifactId,
694 name: record.name,
695 mimeType: record.mimeType,
696 size: bytes.byteLength,
697 blobKey: key,
698 createdAt: record.createdAt,
699 })
700 }
701 output.sort(
702 (a, b) =>
703 a.createdAt - b.createdAt || comparePath(a.artifactId, b.artifactId),
704 )
705 return Object.freeze(output.map((artifact) => Object.freeze(artifact)))
706}