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

api.sandbox-durability.ts

170 lines5.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { EventType, chat } from '@tanstack/ai'
3import { InMemoryLockStore, withLocks } from '@tanstack/ai/locks'
4import {
5 InMemorySandboxInstanceStore,
6 defineSandbox,
7 defineWorkspace,
8 withSandbox,
9} from '@tanstack/ai-sandbox'
10import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
11import type { SandboxHandle, SandboxProvider } from '@tanstack/ai-sandbox'
12​
13/**
14 * Server-side sandbox instance durability harness.
15 *
16 * Proves that a durable `SandboxInstanceStore` (module-singleton stand-in for a
17 * BYO backend) makes resume durable ACROSS independent runs: each POST is a
18 * fresh `chat()` with a brand-new middleware context; the only shared state is
19 * the instance store. A second run for the same `threadId` must RESUME the
20 * sandbox the first run created.
21 *
22 * Wired as production apps do: `withLocks` plus the instance store handed
23 * straight to `withSandbox`. No chat persistence required.
24 *
25 * Provider-free: fixed AG-UI stream + fake sandbox provider (exempt from aimock).
26 */
27​
28const instanceStore = new InMemorySandboxInstanceStore()
29const locks = new InMemoryLockStore()
30​
31/** Per compound sandbox key — isolates concurrent / leftover threads. */
32const createCountByKey = new Map<string, number>()
33const resumeCountByKey = new Map<string, number>()
34​
35function bump(map: Map<string, number>, key: string): void {
36 map.set(key, (map.get(key) ?? 0) + 1)
38​
39function fakeHandle(id: string): SandboxHandle {
40 return {
41 id,
42 provider: 'fake',
43 capabilities: {
44 fs: true,
45 exec: true,
46 env: true,
47 ports: false,
48 backgroundProcesses: false,
49 writableStdin: false,
50 killableProcesses: false,
51 snapshots: false,
52 networkPolicy: false,
53 durableFilesystem: false,
54 fork: false,
55 },
56 fs: {
57 read: () => Promise.resolve(''),
58 readBytes: () => Promise.resolve(new Uint8Array()),
59 write: () => Promise.resolve(),
60 list: () => Promise.resolve([]),
61 mkdir: () => Promise.resolve(),
62 remove: () => Promise.resolve(),
63 rename: () => Promise.resolve(),
64 exists: () => Promise.resolve(false),
65 },
66 git: {
67 clone: () => Promise.resolve(),
68 status: () => Promise.resolve(''),
69 add: () => Promise.resolve(),
70 commit: () => Promise.resolve(),
71 push: () => Promise.resolve(),
72 pull: () => Promise.resolve(),
73 branch: () => Promise.resolve('main'),
74 },
75 process: {
76 exec: () => Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
77 spawn: () => Promise.reject(new Error('not supported')),
78 },
79 ports: { connect: () => Promise.reject(new Error('not supported')) },
80 env: { set: () => Promise.resolve() },
81 destroy: () => Promise.resolve(),
82 }
84​
85const provider: SandboxProvider = {
86 name: 'fake',
87 capabilities: () => fakeHandle('probe').capabilities,
88 create: (input) => {
89 const id = input.id ?? 'fake-sandbox'
90 bump(createCountByKey, id)
91 return Promise.resolve(fakeHandle(id))
92 },
93 resume: (input) => {
94 bump(resumeCountByKey, input.id)
95 return Promise.resolve(fakeHandle(input.id))
96 },
97 destroy: () => Promise.resolve(),
99​
100const sandbox = defineSandbox({
101 id: 'durable',
102 provider,
103 workspace: defineWorkspace({ source: { type: 'none' } }),
104 fileEvents: false,
105})
106​
107function fixedRun(threadId: string, runId: string): AsyncIterable<StreamChunk> {
108 return (async function* () {
109 yield { type: EventType.RUN_STARTED, threadId, runId, timestamp: 1 }
110 yield {
111 type: EventType.RUN_FINISHED,
112 threadId,
113 runId,
114 finishReason: 'stop',
115 timestamp: 1,
116 }
117 })()
119​
120const adapter: AnyTextAdapter = {
121 kind: 'text',
122 name: 'fixed',
123 model: 'test-model',
124 '~types': {},
125 chatStream: ({ runId, threadId }: { runId: string; threadId: string }) =>
126 fixedRun(threadId, runId),
127 structuredOutput: () => Promise.resolve({ data: {}, rawText: '{}' }),
128} as unknown as AnyTextAdapter
129​
130function stringField(body: unknown, key: string): string | undefined {
131 if (typeof body !== 'object' || body === null || !(key in body)) {
132 return undefined
133 }
134 const value: unknown = (body as Record<string, unknown>)[key]
135 return typeof value === 'string' ? value : undefined
137​
138export const Route = createFileRoute('/api/sandbox-durability')({
139 server: {
140 handlers: {
141 POST: async ({ request }) => {
142 const body: unknown = await request.json()
143 const threadId = stringField(body, 'threadId') ?? 'sandbox-thread'
144 const runId = stringField(body, 'runId') ?? crypto.randomUUID()
145​
146 const stream = chat({
147 adapter,
148 messages: [{ role: 'user', content: 'go' }],
149 runId,
150 threadId,
151 middleware: [
152 withLocks(locks),
153 withSandbox(sandbox, { instances: instanceStore }),
154 ],
155 })
156 for await (const _ of stream) void _
157​
158 const key = sandbox.key({ threadId, runId })
159 const record = await instanceStore.get(key)
160 const countKey = record?.providerSandboxId ?? key
161 return Response.json({
162 create: createCountByKey.get(countKey) ?? 0,
163 resume: resumeCountByKey.get(countKey) ?? 0,
164 providerSandboxId: record?.providerSandboxId ?? null,
165 latestRunId: record?.latestRunId ?? null,
166 })
167 },
168 },
169 },
170})