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

isolate-driver.ts

555 lines14.4 KB

1import { randomUUID } from 'node:crypto'
2import { DAYTONA_RESULT_MARKER, wrapCode } from './wrap-code'
3import type {
4 ExecutionResult,
5 IsolateConfig,
6 IsolateContext,
7 IsolateDriver,
8 NormalizedError,
9 ToolBinding,
10} from '@tanstack/ai-code-mode'
11import type {
12 DaytonaCodeRunResponse,
13 DaytonaExecutionEnvelope,
14 DaytonaExecutionError,
15 DaytonaSandboxLike,
16 ToolCallRequest,
17 ToolResultPayload,
18 ToolSchema,
19} from './types'
20​
21const TOOL_CALL_ID = /^tc_(0|[1-9]\d*)$/
22​
23export interface DaytonaIsolateDriverConfig {
24 /**
25 * Caller-owned Daytona SDK sandbox or any object with a compatible
26 * `process.codeRun`. Context disposal prevents further use of this sandbox,
27 * but sandbox creation and cleanup stay with the caller.
28 */
29 sandbox: DaytonaSandboxLike
30​
31 /**
32 * Default total execution timeout in milliseconds (default: 30000).
33 * Each Daytona `codeRun` receives the remaining budget as whole seconds.
34 */
35 timeout?: number
36​
37 /**
38 * Maximum number of tool callback rounds (default: 10).
39 */
40 maxToolRounds?: number
42​
43function bindingsToSchemas(
44 bindings: Record<string, ToolBinding>,
45): Array<ToolSchema> {
46 return Object.entries(bindings).map(([name, binding]) => ({
47 name,
48 description: binding.description,
49 inputSchema: binding.inputSchema,
50 }))
52​
53function normalizeError(error: unknown): DaytonaExecutionError {
54 if (error instanceof Error) {
55 return {
56 name: error.name,
57 message: error.message,
58 ...(error.stack !== undefined ? { stack: error.stack } : {}),
59 }
60 }
61​
62 if (typeof error === 'object' && error !== null) {
63 const record = error as Record<string, unknown>
64 return {
65 name: typeof record.name === 'string' ? record.name : 'Error',
66 message: typeof record.message === 'string' ? record.message : 'Error',
67 }
68 }
69​
70 return { name: 'Error', message: String(error) }
72​
73function toNormalizedError(error: DaytonaExecutionError): NormalizedError {
74 return {
75 name: error.name,
76 message: error.message,
77 ...(error.stack !== undefined ? { stack: error.stack } : {}),
78 }
80​
81function timeoutMsToSeconds(timeout: number): number {
82 return Math.ceil(timeout / 1000)
84​
85function createResultMarker(): string {
86 return `${DAYTONA_RESULT_MARKER}:${randomUUID()}:`
88​
89function validateTimeoutMs(timeout: number, fieldName: string): number {
90 if (!Number.isFinite(timeout) || timeout <= 0) {
91 throw new Error(`${fieldName} must be a finite positive number`)
92 }
93 return timeout
95​
96function validateMaxToolRounds(maxToolRounds: number): number {
97 if (
98 !Number.isFinite(maxToolRounds) ||
99 !Number.isInteger(maxToolRounds) ||
100 maxToolRounds < 0
101 ) {
102 throw new Error('maxToolRounds must be a finite non-negative integer')
103 }
104 return maxToolRounds
106​
107function outputFromCodeRun(response: DaytonaCodeRunResponse): string {
108 const stdout = response.artifacts?.stdout
109 if (stdout !== undefined) {
110 return stdout
111 }
112 if (response.result !== undefined) {
113 return response.result
114 }
115 return ''
117​
118function isRecord(value: unknown): value is Record<string, unknown> {
119 return typeof value === 'object' && value !== null
121​
122function hasOwn<T extends object>(object: T, key: PropertyKey): key is keyof T {
123 return Object.prototype.hasOwnProperty.call(object, key)
125​
126function toolCallIdFor(index: number): string {
127 return `tc_${index}`
129​
130async function withTimeout<T>(
131 promise: Promise<T>,
132 milliseconds: number,
133): Promise<T | undefined> {
134 let timer: number | undefined
135 const timeout = new Promise<undefined>((resolve) => {
136 timer = setTimeout(resolve, milliseconds)
137 })
138​
139 try {
140 return await Promise.race([promise, timeout])
141 } finally {
142 if (timer !== undefined) {
143 clearTimeout(timer)
144 }
145 }
147​
148function readStringArray(value: unknown, fieldName: string): Array<string> {
149 if (!Array.isArray(value)) {
150 throw new Error(`Daytona envelope field '${fieldName}' must be an array`)
151 }
152 if (!value.every((item): item is string => typeof item === 'string')) {
153 throw new Error(
154 `Daytona envelope field '${fieldName}' must contain only strings`,
155 )
156 }
157 return value
159​
160function readExecutionError(
161 value: unknown,
162 fieldName: string,
163): DaytonaExecutionError {
164 if (!isRecord(value)) {
165 throw new Error(`Daytona envelope field '${fieldName}' must be an object`)
166 }
167​
168 const { name, message, stack } = value
169 if (typeof name !== 'string' || typeof message !== 'string') {
170 throw new Error(
171 `Daytona envelope field '${fieldName}' must include string name and message`,
172 )
173 }
174​
175 return {
176 name,
177 message,
178 ...(typeof stack === 'string' ? { stack } : {}),
179 }
181​
182function readToolCalls(value: unknown): Array<ToolCallRequest> {
183 if (!Array.isArray(value)) {
184 throw new Error("Daytona envelope field 'toolCalls' must be an array")
185 }
186​
187 const seenIds = new Set<string>()
188​
189 return value.map((item) => {
190 if (!isRecord(item)) {
191 throw new Error('Daytona tool call must be an object')
192 }
193​
194 const { id, name, args } = item
195 if (typeof id !== 'string' || typeof name !== 'string') {
196 throw new Error('Daytona tool call must include string id and name')
197 }
198 if (!TOOL_CALL_ID.test(id)) {
199 throw new Error(`Invalid Daytona tool call id: ${id}`)
200 }
201 if (seenIds.has(id)) {
202 throw new Error(`Duplicate Daytona tool call id: ${id}`)
203 }
204​
205 seenIds.add(id)
206 return { id, name, args }
207 })
209​
210function assertNewToolCallId(
211 toolResults: Record<string, ToolResultPayload>,
212 id: string,
213): void {
214 if (hasOwn(toolResults, id)) {
215 throw new Error(`Daytona tool call id already has a cached result: ${id}`)
216 }
218​
219function assertExpectedToolCalls(
220 toolCalls: Array<ToolCallRequest>,
221 nextToolCallIndex: number,
222 toolResults: Record<string, ToolResultPayload>,
223): void {
224 if (toolCalls.length === 0) {
225 throw new Error('Daytona need_tools response must include tool calls')
226 }
227​
228 toolCalls.forEach((toolCall, index) => {
229 assertNewToolCallId(toolResults, toolCall.id)
230​
231 const expectedId = toolCallIdFor(nextToolCallIndex + index)
232 if (toolCall.id !== expectedId) {
233 throw new Error(
234 `Daytona tool call ids must be contiguous from ${expectedId}; received ${toolCall.id}`,
235 )
236 }
237 })
239​
240async function executeToolCall(
241 bindings: Record<string, ToolBinding>,
242 toolCall: ToolCallRequest,
243): Promise<[string, ToolResultPayload]> {
244 const binding = hasOwn(bindings, toolCall.name)
245 ? bindings[toolCall.name]
246 : undefined
247​
248 if (!binding) {
249 return [
250 toolCall.id,
251 {
252 success: false,
253 error: `Unknown tool: ${toolCall.name}`,
254 },
255 ]
256 }
257​
258 try {
259 const value = await binding.execute(toolCall.args)
260 return [toolCall.id, { success: true, value }]
261 } catch (toolError) {
262 const error = normalizeError(toolError)
263 return [
264 toolCall.id,
265 {
266 success: false,
267 error: error.message,
268 },
269 ]
270 }
272​
273function parseExecutionEnvelope(
274 output: string,
275 resultMarker: string,
276): DaytonaExecutionEnvelope {
277 const markerLine = output
278 .split(/\r?\n/)
279 .reverse()
280 .find((line) => line.startsWith(resultMarker))
281​
282 if (!markerLine) {
283 throw new Error('Daytona codeRun output did not include Code Mode marker')
284 }
285​
286 const jsonText = markerLine.slice(resultMarker.length)
287 const parsed: unknown = JSON.parse(jsonText)
288​
289 if (!isRecord(parsed) || typeof parsed.status !== 'string') {
290 throw new Error('Daytona codeRun marker did not contain a valid envelope')
291 }
292​
293 if (parsed.status === 'done') {
294 if (typeof parsed.success !== 'boolean') {
295 throw new Error("Daytona envelope field 'success' must be a boolean")
296 }
297​
298 if (parsed.success) {
299 if (parsed.error !== undefined) {
300 throw new Error('Daytona success envelope must not include error')
301 }
302​
303 return {
304 status: 'done',
305 success: true,
306 value: parsed.value,
307 logs: readStringArray(parsed.logs, 'logs'),
308 }
309 }
310​
311 if (parsed.value !== undefined) {
312 throw new Error('Daytona failure envelope must not include value')
313 }
314​
315 return {
316 status: 'done',
317 success: false,
318 error: readExecutionError(parsed.error, 'error'),
319 logs: readStringArray(parsed.logs, 'logs'),
320 }
321 }
322​
323 if (parsed.status === 'need_tools') {
324 return {
325 status: 'need_tools',
326 toolCalls: readToolCalls(parsed.toolCalls),
327 logs: readStringArray(parsed.logs, 'logs'),
328 }
329 }
330​
331 if (parsed.status === 'error') {
332 return {
333 status: 'error',
334 error: readExecutionError(parsed.error, 'error'),
335 }
336 }
337​
338 throw new Error(`Unknown Daytona execution status: ${parsed.status}`)
340​
341class DaytonaIsolateContext implements IsolateContext {
342 private disposed = false
343​
344 constructor(
345 private readonly sandbox: DaytonaSandboxLike,
346 private readonly bindings: Record<string, ToolBinding>,
347 private readonly timeoutMs: number,
348 private readonly maxToolRounds: number,
349 ) {}
350​
351 private disposedResult<T>(logs: Array<string>): ExecutionResult<T> {
352 return {
353 success: false,
354 error: {
355 name: 'DisposedError',
356 message: 'Context has been disposed',
357 },
358 logs,
359 }
360 }
361​
362 private timeoutResult<T>(logs: Array<string>): ExecutionResult<T> {
363 return {
364 success: false,
365 error: {
366 name: 'TimeoutError',
367 message: `Exceeded Daytona execution timeout (${this.timeoutMs}ms)`,
368 },
369 logs,
370 }
371 }
372​
373 private isDisposed(): boolean {
374 return this.disposed
375 }
376​
377 private remainingTimeoutSeconds(deadlineMs: number): number | undefined {
378 const remainingMs = deadlineMs - Date.now()
379 if (remainingMs <= 0) {
380 return undefined
381 }
382 return timeoutMsToSeconds(remainingMs)
383 }
384​
385 private remainingTimeoutMs(deadlineMs: number): number | undefined {
386 const remainingMs = deadlineMs - Date.now()
387 return remainingMs > 0 ? remainingMs : undefined
388 }
389​
390 async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {
391 if (this.isDisposed()) {
392 return this.disposedResult([])
393 }
394​
395 const tools = bindingsToSchemas(this.bindings)
396 let toolResults: Record<string, ToolResultPayload> | undefined
397 let allLogs: Array<string> = []
398 let toolRounds = 0
399 let nextToolCallIndex = 0
400 const deadlineMs = Date.now() + this.timeoutMs
401​
402 for (;;) {
403 try {
404 if (this.isDisposed()) {
405 return this.disposedResult(allLogs)
406 }
407​
408 const remainingCodeRunMs = this.remainingTimeoutMs(deadlineMs)
409 if (remainingCodeRunMs === undefined) {
410 return this.timeoutResult(allLogs)
411 }
412​
413 const resultMarker = createResultMarker()
414 const wrappedCode = wrapCode(code, tools, toolResults, resultMarker)
415 const response = await withTimeout(
416 this.sandbox.process.codeRun(
417 wrappedCode,
418 undefined,
419 timeoutMsToSeconds(remainingCodeRunMs),
420 ),
421 remainingCodeRunMs,
422 )
423 if (response === undefined) {
424 return this.timeoutResult(allLogs)
425 }
426 const output = outputFromCodeRun(response)
427 const result = parseExecutionEnvelope(output, resultMarker)
428​
429 if (result.status === 'error') {
430 return {
431 success: false,
432 error: toNormalizedError(result.error),
433 logs: allLogs,
434 }
435 }
436​
437 if (result.status === 'done') {
438 allLogs = result.logs
439 if (this.isDisposed()) {
440 return this.disposedResult(allLogs)
441 }
442 if (!result.success) {
443 return {
444 success: false,
445 error: toNormalizedError(result.error),
446 logs: allLogs,
447 }
448 }
449​
450 return {
451 success: true,
452 value: result.value as T,
453 logs: allLogs,
454 }
455 }
456​
457 allLogs = result.logs
458 if (this.isDisposed()) {
459 return this.disposedResult(allLogs)
460 }
461​
462 if (toolRounds >= this.maxToolRounds) {
463 return {
464 success: false,
465 error: {
466 name: 'MaxRoundsExceeded',
467 message: `Exceeded maximum tool callback rounds (${this.maxToolRounds})`,
468 },
469 logs: allLogs,
470 }
471 }
472​
473 const cachedToolResults = { ...(toolResults ?? {}) }
474 assertExpectedToolCalls(
475 result.toolCalls,
476 nextToolCallIndex,
477 cachedToolResults,
478 )
479 toolRounds++
480 nextToolCallIndex += result.toolCalls.length
481​
482 if (this.isDisposed()) {
483 return this.disposedResult(allLogs)
484 }
485​
486 const remainingToolMs = this.remainingTimeoutMs(deadlineMs)
487 if (remainingToolMs === undefined) {
488 return this.timeoutResult(allLogs)
489 }
490 const batchEntries = await withTimeout(
491 Promise.all(
492 result.toolCalls.map((toolCall) =>
493 executeToolCall(this.bindings, toolCall),
494 ),
495 ),
496 remainingToolMs,
497 )
498 if (batchEntries === undefined) {
499 return this.timeoutResult(allLogs)
500 }
501 if (this.isDisposed()) {
502 return this.disposedResult(allLogs)
503 }
504 if (this.remainingTimeoutSeconds(deadlineMs) === undefined) {
505 return this.timeoutResult(allLogs)
506 }
507 const batchResults: Record<string, ToolResultPayload> = {}
508 for (const [id, payload] of batchEntries) {
509 batchResults[id] = payload
510 }
511 toolResults = { ...cachedToolResults, ...batchResults }
512 } catch (error) {
513 const normalized = normalizeError(error)
514 return {
515 success: false,
516 error: {
517 name: 'DaytonaExecutionError',
518 message: `Failed to execute code in Daytona sandbox: ${normalized.message}`,
519 },
520 logs: allLogs,
521 }
522 }
523 }
524 }
525​
526 dispose(): Promise<void> {
527 this.disposed = true
528 return Promise.resolve()
529 }
531​
532export function createDaytonaIsolateDriver(
533 config: DaytonaIsolateDriverConfig,
534): IsolateDriver {
535 const sandbox = config.sandbox
536 const defaultTimeoutMs = validateTimeoutMs(config.timeout ?? 30000, 'timeout')
537 const maxToolRounds = validateMaxToolRounds(config.maxToolRounds ?? 10)
538​
539 return {
540 createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
541 const timeoutMs = validateTimeoutMs(
542 isolateConfig.timeout ?? defaultTimeoutMs,
543 'timeout',
544 )
545 return Promise.resolve(
546 new DaytonaIsolateContext(
547 sandbox,
548 isolateConfig.bindings,
549 timeoutMs,
550 maxToolRounds,
551 ),
552 )
553 },
554 }