@tanstack/ai-isolate-daytona 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,555 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { DAYTONA_RESULT_MARKER, wrapCode } from './wrap-code'
3
+ import type {
4
+ ExecutionResult,
5
+ IsolateConfig,
6
+ IsolateContext,
7
+ IsolateDriver,
8
+ NormalizedError,
9
+ ToolBinding,
10
+ } from '@tanstack/ai-code-mode'
11
+ import type {
12
+ DaytonaCodeRunResponse,
13
+ DaytonaExecutionEnvelope,
14
+ DaytonaExecutionError,
15
+ DaytonaSandboxLike,
16
+ ToolCallRequest,
17
+ ToolResultPayload,
18
+ ToolSchema,
19
+ } from './types'
20
+
21
+ const TOOL_CALL_ID = /^tc_(0|[1-9]\d*)$/
22
+
23
+ export 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
41
+ }
42
+
43
+ function 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
+ }))
51
+ }
52
+
53
+ function 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) }
71
+ }
72
+
73
+ function toNormalizedError(error: DaytonaExecutionError): NormalizedError {
74
+ return {
75
+ name: error.name,
76
+ message: error.message,
77
+ ...(error.stack !== undefined ? { stack: error.stack } : {}),
78
+ }
79
+ }
80
+
81
+ function timeoutMsToSeconds(timeout: number): number {
82
+ return Math.ceil(timeout / 1000)
83
+ }
84
+
85
+ function createResultMarker(): string {
86
+ return `${DAYTONA_RESULT_MARKER}:${randomUUID()}:`
87
+ }
88
+
89
+ function 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
94
+ }
95
+
96
+ function 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
105
+ }
106
+
107
+ function 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 ''
116
+ }
117
+
118
+ function isRecord(value: unknown): value is Record<string, unknown> {
119
+ return typeof value === 'object' && value !== null
120
+ }
121
+
122
+ function hasOwn<T extends object>(object: T, key: PropertyKey): key is keyof T {
123
+ return Object.prototype.hasOwnProperty.call(object, key)
124
+ }
125
+
126
+ function toolCallIdFor(index: number): string {
127
+ return `tc_${index}`
128
+ }
129
+
130
+ async 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
+ }
146
+ }
147
+
148
+ function 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
158
+ }
159
+
160
+ function 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
+ }
180
+ }
181
+
182
+ function 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
+ })
208
+ }
209
+
210
+ function 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
+ }
217
+ }
218
+
219
+ function 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
+ })
238
+ }
239
+
240
+ async 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
+ }
271
+ }
272
+
273
+ function 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}`)
339
+ }
340
+
341
+ class 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
+ }
530
+ }
531
+
532
+ export 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
+ }
555
+ }
package/src/types.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Structural Daytona process/code-run types plus the host/sandbox protocol.
3
+ */
4
+
5
+ export interface DaytonaCodeRunArtifacts {
6
+ stdout?: string | undefined
7
+ }
8
+
9
+ export interface DaytonaCodeRunResponse {
10
+ exitCode?: number | undefined
11
+ result?: string | undefined
12
+ artifacts?: DaytonaCodeRunArtifacts | undefined
13
+ }
14
+
15
+ export interface DaytonaCodeRunParams {
16
+ argv?: Array<string> | undefined
17
+ env?: Record<string, string> | undefined
18
+ }
19
+
20
+ export interface DaytonaProcessLike {
21
+ codeRun: (
22
+ code: string,
23
+ params?: DaytonaCodeRunParams,
24
+ timeoutSeconds?: number,
25
+ ) => Promise<DaytonaCodeRunResponse>
26
+ }
27
+
28
+ export interface DaytonaSandboxLike {
29
+ process: DaytonaProcessLike
30
+ }
31
+
32
+ export interface ToolSchema {
33
+ name: string
34
+ description: string
35
+ inputSchema: Record<string, unknown>
36
+ }
37
+
38
+ export interface ToolCallRequest {
39
+ id: string
40
+ name: string
41
+ args: unknown
42
+ }
43
+
44
+ export type ToolResultPayload =
45
+ | {
46
+ success: true
47
+ value?: unknown
48
+ error?: never
49
+ }
50
+ | {
51
+ success: false
52
+ error: string
53
+ value?: never
54
+ }
55
+
56
+ export interface DaytonaExecutionError {
57
+ name: string
58
+ message: string
59
+ stack?: string | undefined
60
+ }
61
+
62
+ export type DaytonaExecutionEnvelope =
63
+ | {
64
+ status: 'done'
65
+ success: true
66
+ value?: unknown
67
+ error?: never
68
+ logs: Array<string>
69
+ }
70
+ | {
71
+ status: 'done'
72
+ success: false
73
+ error: DaytonaExecutionError
74
+ value?: never
75
+ logs: Array<string>
76
+ }
77
+ | {
78
+ status: 'need_tools'
79
+ toolCalls: Array<ToolCallRequest>
80
+ logs: Array<string>
81
+ }
82
+ | {
83
+ status: 'error'
84
+ error: DaytonaExecutionError
85
+ }