Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.sandbox-file-persistence.ts

458 lines13.9 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { EventType, chat } from '@tanstack/ai'
3import {
4 InMemorySandboxInstanceStore,
5 defineSandbox,
6 defineWorkspace,
7 memorySandboxSnapshots,
8 withSandbox,
9} from '@tanstack/ai-sandbox'
10import { withPersistence } from '@tanstack/ai-persistence'
11import type {
12 DefaultMessageMetadataByModality,
13 StreamChunk,
14 TextAdapter,
15 TextOptions,
16} from '@tanstack/ai'
17import type {
18 SandboxCapabilities,
19 SandboxCheckpoint,
20 SandboxFsStat,
21 SandboxHandle,
22 SandboxProvider,
23} from '@tanstack/ai-sandbox'
24​
25const capabilities: SandboxCapabilities = {
26 fs: true,
27 exec: true,
28 env: true,
29 ports: false,
30 backgroundProcesses: false,
31 writableStdin: false,
32 killableProcesses: false,
33 snapshots: false,
34 networkPolicy: false,
35 durableFilesystem: false,
36 fork: false,
38​
39type WorkspaceEntry = { kind: 'dir' } | { kind: 'file'; content: string }
40​
41type SnapshotValue = SandboxCheckpoint | null
42​
43function sameValue(left: SnapshotValue, right: SnapshotValue): boolean {
44 if (!left || !right) return left === right
45 return (
46 left.id === right.id &&
47 left.threadId === right.threadId &&
48 left.parentCheckpointId === right.parentCheckpointId &&
49 left.createdAt === right.createdAt &&
50 left.reason === right.reason &&
51 left.label === right.label &&
52 left.sourceRunId === right.sourceRunId &&
53 left.files.length === right.files.length &&
54 left.files.every((entry, index) => {
55 const other = right.files[index]
56 return (
57 other !== undefined &&
58 entry.path === other.path &&
59 entry.kind === other.kind &&
60 (entry.kind !== 'file' ||
61 (other.kind === 'file' &&
62 entry.blobKey === other.blobKey &&
63 entry.size === other.size))
64 )
65 }) &&
66 left.conversation.length === right.conversation.length &&
67 left.conversation.every(
68 (message, index) =>
69 message.role === right.conversation[index]?.role &&
70 message.content === right.conversation[index]?.content,
71 ) &&
72 left.artifacts.length === right.artifacts.length &&
73 left.artifacts.every((artifact, index) => {
74 const other = right.artifacts[index]
75 return (
76 other !== undefined &&
77 artifact.artifactId === other.artifactId &&
78 artifact.name === other.name &&
79 artifact.mimeType === other.mimeType &&
80 artifact.blobKey === other.blobKey &&
81 artifact.size === other.size &&
82 artifact.createdAt === other.createdAt
83 )
84 })
85 )
87​
88function sameValues(
89 left: ReadonlyArray<SnapshotValue>,
90 right: ReadonlyArray<SnapshotValue>,
91): boolean {
92 return (
93 left.length === right.length &&
94 left.every((value, index) => sameValue(value, right[index]))
95 )
97​
98export function sameSerializableValue(left: unknown, right: unknown): boolean {
99 if (Object.is(left, right)) return true
100 if (typeof left !== typeof right || left === null || right === null)
101 return false
102 if (left instanceof Date || right instanceof Date) {
103 return (
104 left instanceof Date &&
105 right instanceof Date &&
106 left.getTime() === right.getTime()
107 )
108 }
109 if (Array.isArray(left) || Array.isArray(right)) {
110 if (!Array.isArray(left) || !Array.isArray(right)) return false
111 return (
112 left.length === right.length &&
113 left.every((value, index) => sameSerializableValue(value, right[index]))
114 )
115 }
116 if (typeof left !== 'object' || typeof right !== 'object') return false
117 const leftEntries = Object.entries(left).sort(([first], [second]) =>
118 first.localeCompare(second),
119 )
120 const rightEntries = Object.entries(right).sort(([first], [second]) =>
121 first.localeCompare(second),
122 )
123 return (
124 leftEntries.length === rightEntries.length &&
125 leftEntries.every(([key, value], index) => {
126 const other = rightEntries[index]
127 return (
128 other !== undefined &&
129 key === other[0] &&
130 sameSerializableValue(value, other[1])
131 )
132 })
133 )
135​
136export async function forkWithSourceMessageSnapshot<Result>({
137 loadSourceMessages,
138 fork,
139}: {
140 loadSourceMessages: () => Promise<unknown>
141 fork: () => Promise<Result>
142}) {
143 const sourceMessagesBeforeFork = structuredClone(await loadSourceMessages())
144 const result = await fork()
145 const sourceMessagesAfterFork = await loadSourceMessages()
146 return {
147 result,
148 sourceMessagesUnchanged: sameSerializableValue(
149 sourceMessagesBeforeFork,
150 sourceMessagesAfterFork,
151 ),
152 }
154​
155function fileContent(entry: WorkspaceEntry | undefined): string {
156 return entry?.kind === 'file' ? entry.content : ''
158​
159function fakeHandle(
160 id: string,
161 files: Map<string, WorkspaceEntry>,
162): SandboxHandle {
163 const lstat = (path: string): Promise<SandboxFsStat | undefined> => {
164 const entry = files.get(path)
165 if (!entry) return Promise.resolve(undefined)
166 return Promise.resolve(
167 entry.kind === 'dir'
168 ? { type: 'dir', mode: 0o755 }
169 : {
170 type: 'file',
171 mode: 0o644,
172 size: new TextEncoder().encode(entry.content).byteLength,
173 },
174 )
175 }
176 return {
177 id,
178 provider: 'fake',
179 capabilities,
180 fs: {
181 read: async (path) => fileContent(files.get(path)),
182 readBytes: async (path) =>
183 new TextEncoder().encode(fileContent(files.get(path))),
184 write: async (path, value) => {
185 files.set(path, {
186 kind: 'file',
187 content:
188 typeof value === 'string' ? value : new TextDecoder().decode(value),
189 })
190 },
191 list: async (path) => {
192 const prefix = `${path}/`
193 return [...files].flatMap(([entryPath, entry]) => {
194 const name = entryPath.startsWith(prefix)
195 ? entryPath.slice(prefix.length)
196 : ''
197 return name && !name.includes('/')
198 ? [{ name, path: entryPath, type: entry.kind }]
199 : []
200 })
201 },
202 lstat,
203 mkdir: async (path) => {
204 files.set(path, { kind: 'dir' })
205 },
206 remove: async (path) => {
207 files.delete(path)
208 },
209 rename: async () => {},
210 exists: async (path) => files.has(path),
211 },
212 git: {
213 clone: async () => {},
214 status: async () => '',
215 add: async () => {},
216 commit: async () => {},
217 push: async () => {},
218 pull: async () => {},
219 branch: async () => 'main',
220 },
221 process: {
222 exec: async () => ({ stdout: '', stderr: '', exitCode: 0 }),
223 spawn: async () => {
224 throw new Error('not supported')
225 },
226 },
227 ports: {
228 connect: async () => {
229 throw new Error('not supported')
230 },
231 },
232 env: { set: async () => {} },
233 destroy: async () => {},
234 }
236​
237function fixedRun(threadId: string, runId: string): AsyncIterable<StreamChunk> {
238 return (async function* () {
239 yield { type: EventType.RUN_STARTED, threadId, runId, timestamp: 1 }
240 yield {
241 type: EventType.TEXT_MESSAGE_START,
242 threadId,
243 runId,
244 timestamp: 1,
245 messageId: 'automatic-message',
246 role: 'assistant',
247 }
248 yield {
249 type: EventType.TEXT_MESSAGE_CONTENT,
250 threadId,
251 runId,
252 timestamp: 1,
253 messageId: 'automatic-message',
254 delta: 'automatic conversation',
255 }
256 yield {
257 type: EventType.TEXT_MESSAGE_END,
258 threadId,
259 runId,
260 timestamp: 1,
261 messageId: 'automatic-message',
262 }
263 yield {
264 type: EventType.RUN_FINISHED,
265 threadId,
266 runId,
267 finishReason: 'stop',
268 timestamp: 1,
269 }
270 })()
272​
273type FixedAdapter = TextAdapter<
274 'test-model',
275 Record<string, never>,
276 readonly ['text'],
277 DefaultMessageMetadataByModality,
278 readonly [],
279 unknown,
280 unknown
282​
283const adapter: FixedAdapter = {
284 kind: 'text',
285 name: 'fixed',
286 model: 'test-model',
287 '~types': {
288 providerOptions: {},
289 inputModalities: ['text'],
290 messageMetadataByModality: {
291 text: undefined,
292 image: undefined,
293 audio: undefined,
294 video: undefined,
295 document: undefined,
296 },
297 toolCapabilities: [],
298 toolCallMetadata: undefined,
299 systemPromptMetadata: undefined,
300 },
301 chatStream: (options: TextOptions<Record<string, never>>) =>
302 fixedRun(
303 options.threadId ?? 'missing-thread',
304 options.runId ?? 'missing-run',
305 ),
306 structuredOutput: () => Promise.resolve({ data: {}, rawText: '{}' }),
308​
309export const Route = createFileRoute('/api/sandbox-file-persistence')({
310 server: {
311 handlers: {
312 POST: async () => {
313 const threadId = `snapshot-source-${crypto.randomUUID()}`
314 const destinationThreadId = `snapshot-fork-${crypto.randomUUID()}`
315 const sourceFiles = new Map<string, WorkspaceEntry>([
316 ['/workspace', { kind: 'dir' }],
317 ['/workspace/notes.txt', { kind: 'file', content: 'saved file' }],
318 ['/workspace/empty', { kind: 'dir' }],
319 ['/workspace/.env', { kind: 'file', content: 'secret' }],
320 ['/workspace/.git', { kind: 'dir' }],
321 ['/workspace/.git/config', { kind: 'file', content: 'private' }],
322 ])
323 const restoredFiles = new Map<string, WorkspaceEntry>([
324 ['/workspace', { kind: 'dir' }],
325 ])
326 let originalExists = true
327 const provider: SandboxProvider = {
328 name: 'fake',
329 capabilities: () => capabilities,
330 create: async () => fakeHandle('created', restoredFiles),
331 resume: async () =>
332 originalExists ? fakeHandle('original', sourceFiles) : null,
333 destroy: async () => {},
334 }
335 const instances = new InMemorySandboxInstanceStore()
336 const sandbox = defineSandbox({
337 id: 'file-persistence',
338 provider,
339 workspace: defineWorkspace({ source: { type: 'none' } }),
340 fileEvents: false,
341 })
342 const snapshots = await memorySandboxSnapshots({
343 sandbox,
344 instances,
345 })
346 const key = sandbox.key({ threadId, runId: 'save', store: instances })
347 await instances.upsert({
348 key,
349 provider: 'fake',
350 providerSandboxId: 'original',
351 threadId,
352 updatedAt: 1,
353 })
354 await snapshots.persistence.stores.messages.saveThread(threadId, [
355 { role: 'user', content: 'saved conversation' },
356 ])
357 await snapshots.persistence.stores.blobs.put(
358 'artifact-source',
359 'artifact data',
360 )
361 await snapshots.persistence.stores.artifacts.save({
362 artifactId: 'artifact-1',
363 threadId,
364 runId: 'save',
365 name: 'artifact.txt',
366 mimeType: 'text/plain',
367 blobKey: 'artifact-source',
368 size: 13,
369 createdAt: 1,
370 })
371​
372 const saved = await snapshots.save({
373 threadId,
374 runId: 'save',
375 label: 'release-1',
376 })
377 originalExists = false
378 const recovery = chat({
379 adapter,
380 messages: [{ role: 'user', content: 'recover' }],
381 runId: 'recover',
382 threadId,
383 middleware: [
384 withPersistence(snapshots.persistence),
385 withSandbox(sandbox, { instances, snapshots }),
386 ],
387 })
388 for await (const _ of recovery) void _
389 const automaticHeadId = await snapshots.checkpoints.getHead(threadId)
390 if (!automaticHeadId || automaticHeadId === saved.id)
391 throw new Error('Expected a newer automatic checkpoint')
392 const automaticCheckpoint =
393 await snapshots.checkpoints.get(automaticHeadId)
394 if (!automaticCheckpoint)
395 throw new Error('Expected the automatic checkpoint')
396 const artifact = await snapshots.readArtifact({
397 threadId,
398 checkpointId: saved.id,
399 artifactId: 'artifact-1',
400 })
401 const sourceBeforeFork = await snapshots.checkpoints.list(threadId)
402 const { result: fork, sourceMessagesUnchanged } =
403 await forkWithSourceMessageSnapshot({
404 loadSourceMessages: () =>
405 snapshots.persistence.stores.messages.loadThread(threadId),
406 fork: () =>
407 snapshots.fork({
408 threadId,
409 checkpointId: saved.id,
410 destinationThreadId,
411 destinationCheckpointId: 'fork-root',
412 createdAt: 2,
413 }),
414 })
415 const sourceAfterFork = await snapshots.checkpoints.list(threadId)
416 const sourceHeadAfterFork =
417 await snapshots.checkpoints.getHead(threadId)
418 const sourceCheckpointAfterFork =
419 await snapshots.checkpoints.get(automaticHeadId)
420 const readFile = restoredFiles.get('/workspace/notes.txt')
421 return Response.json({
422 namedSave: saved.label,
423 recoveredFiles: readFile?.kind === 'file' ? ['notes.txt'] : [],
424 recoveredFileBytes:
425 readFile?.kind === 'file'
426 ? Array.from(new TextEncoder().encode(readFile.content))
427 : [],
428 recoveredEmptyDirectories:
429 restoredFiles.get('/workspace/empty')?.kind === 'dir'
430 ? ['empty']
431 : [],
432 artifactText: new TextDecoder().decode(artifact.bytes),
433 conversation: saved.conversation,
434 excluded: ['.env', '.git'].filter(
435 (name) =>
436 !saved.files.some(
437 (entry) =>
438 entry.path === name || entry.path.startsWith(`${name}/`),
439 ),
440 ),
441 fork: {
442 selectedCheckpointIsHead: saved.id === automaticHeadId,
443 files: fork.files
444 .filter((entry) => entry.kind === 'file')
445 .map((entry) => entry.path),
446 sourceThreadUnchanged:
447 sameValues(sourceBeforeFork, sourceAfterFork) &&
448 automaticHeadId === sourceHeadAfterFork &&
449 sameValue(automaticCheckpoint, sourceCheckpointAfterFork),
450 sourceMessagesUnchanged,
451 conversation: fork.conversation,
452 },
453 automaticConversation: automaticCheckpoint.conversation,
454 })
455 },
456 },
457 },
458})