@tanstack/ai-isolate-daytona 1.0.0 → 1.1.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.
package/README.md CHANGED
@@ -33,7 +33,7 @@ pnpm add @tanstack/ai-isolate-daytona @tanstack/ai-code-mode
33
33
  If you use the official Daytona SDK to create sandboxes, install it in your app too:
34
34
 
35
35
  ```bash
36
- pnpm add @daytona/sdk
36
+ pnpm add @daytona/sdk@^0.231.1
37
37
  ```
38
38
 
39
39
  ## Usage
@@ -41,8 +41,11 @@ pnpm add @daytona/sdk
41
41
  ```typescript
42
42
  import { Daytona } from '@daytona/sdk'
43
43
  import { createCodeMode } from '@tanstack/ai-code-mode'
44
+ import type { CodeModeTool } from '@tanstack/ai-code-mode'
44
45
  import { createDaytonaIsolateDriver } from '@tanstack/ai-isolate-daytona'
45
46
 
47
+ declare const myServerTool: CodeModeTool
48
+
46
49
  const daytona = new Daytona()
47
50
  const sandbox = await daytona.create({ language: 'typescript' })
48
51
 
package/dist/esm/index.js CHANGED
@@ -1,2 +1 @@
1
- import { createDaytonaIsolateDriver } from "./isolate-driver.js";
2
- export { createDaytonaIsolateDriver };
1
+ export { createDaytonaIsolateDriver } from "./isolate-driver.js";
@@ -1,6 +1,6 @@
1
1
  import { DAYTONA_RESULT_MARKER, wrapCode } from "./wrap-code.js";
2
2
  import { randomUUID } from "node:crypto";
3
- //#region src/isolate-driver.ts
3
+ // src/isolate-driver.ts
4
4
  var TOOL_CALL_ID = /^tc_(0|[1-9]\d*)$/;
5
5
  function bindingsToSchemas(bindings) {
6
6
  return Object.entries(bindings).map(([name, binding]) => ({
@@ -63,15 +63,21 @@ function hasOwn(object, key) {
63
63
  function toolCallIdFor(index) {
64
64
  return `tc_${index}`;
65
65
  }
66
- async function withTimeout(promise, milliseconds) {
66
+ /** Resolves `undefined` when `milliseconds` pass or `signal` aborts first. */
67
+ async function withTimeout(promise, milliseconds, signal) {
67
68
  let timer;
69
+ let onAbort;
68
70
  const timeout = new Promise((resolve) => {
69
71
  timer = setTimeout(resolve, milliseconds);
72
+ onAbort = () => resolve(void 0);
73
+ if (signal?.aborted) onAbort();
74
+ else signal?.addEventListener("abort", onAbort, { once: true });
70
75
  });
71
76
  try {
72
77
  return await Promise.race([promise, timeout]);
73
78
  } finally {
74
79
  if (timer !== void 0) clearTimeout(timer);
80
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
75
81
  }
76
82
  }
77
83
  function readStringArray(value, fieldName) {
@@ -205,6 +211,17 @@ var DaytonaIsolateContext = class {
205
211
  logs
206
212
  };
207
213
  }
214
+ abortedResult(signal, logs) {
215
+ const reason = signal.reason;
216
+ return {
217
+ success: false,
218
+ error: {
219
+ name: "AbortError",
220
+ message: reason instanceof Error ? reason.message : "Execution was aborted"
221
+ },
222
+ logs
223
+ };
224
+ }
208
225
  isDisposed() {
209
226
  return this.disposed;
210
227
  }
@@ -217,7 +234,12 @@ var DaytonaIsolateContext = class {
217
234
  const remainingMs = deadlineMs - Date.now();
218
235
  return remainingMs > 0 ? remainingMs : void 0;
219
236
  }
220
- async execute(code) {
237
+ /**
238
+ * `options.signal` stops the wait and any later tool round. The Daytona
239
+ * SDK cannot cancel a `codeRun`, so a started run ends at its own timeout.
240
+ */
241
+ async execute(code, options) {
242
+ const signal = options?.signal;
221
243
  if (this.isDisposed()) return this.disposedResult([]);
222
244
  const tools = bindingsToSchemas(this.bindings);
223
245
  let toolResults;
@@ -227,11 +249,13 @@ var DaytonaIsolateContext = class {
227
249
  const deadlineMs = Date.now() + this.timeoutMs;
228
250
  for (;;) try {
229
251
  if (this.isDisposed()) return this.disposedResult(allLogs);
252
+ if (signal?.aborted) return this.abortedResult(signal, allLogs);
230
253
  const remainingCodeRunMs = this.remainingTimeoutMs(deadlineMs);
231
254
  if (remainingCodeRunMs === void 0) return this.timeoutResult(allLogs);
232
255
  const resultMarker = createResultMarker();
233
256
  const wrappedCode = wrapCode(code, tools, toolResults, resultMarker);
234
- const response = await withTimeout(this.sandbox.process.codeRun(wrappedCode, void 0, timeoutMsToSeconds(remainingCodeRunMs)), remainingCodeRunMs);
257
+ const response = await withTimeout(this.sandbox.process.codeRun(wrappedCode, void 0, timeoutMsToSeconds(remainingCodeRunMs)), remainingCodeRunMs, signal);
258
+ if (signal?.aborted) return this.abortedResult(signal, allLogs);
235
259
  if (response === void 0) return this.timeoutResult(allLogs);
236
260
  const result = parseExecutionEnvelope(outputFromCodeRun(response), resultMarker);
237
261
  if (result.status === "error") return {
@@ -270,7 +294,8 @@ var DaytonaIsolateContext = class {
270
294
  if (this.isDisposed()) return this.disposedResult(allLogs);
271
295
  const remainingToolMs = this.remainingTimeoutMs(deadlineMs);
272
296
  if (remainingToolMs === void 0) return this.timeoutResult(allLogs);
273
- const batchEntries = await withTimeout(Promise.all(result.toolCalls.map((toolCall) => executeToolCall(this.bindings, toolCall))), remainingToolMs);
297
+ const batchEntries = await withTimeout(Promise.all(result.toolCalls.map((toolCall) => executeToolCall(this.bindings, toolCall))), remainingToolMs, signal);
298
+ if (signal?.aborted) return this.abortedResult(signal, allLogs);
274
299
  if (batchEntries === void 0) return this.timeoutResult(allLogs);
275
300
  if (this.isDisposed()) return this.disposedResult(allLogs);
276
301
  if (this.remainingTimeoutSeconds(deadlineMs) === void 0) return this.timeoutResult(allLogs);
@@ -305,7 +330,6 @@ function createDaytonaIsolateDriver(config) {
305
330
  return Promise.resolve(new DaytonaIsolateContext(sandbox, isolateConfig.bindings, timeoutMs, maxToolRounds));
306
331
  } };
307
332
  }
308
- //#endregion
309
333
  export { createDaytonaIsolateDriver };
310
334
 
311
335
  //# sourceMappingURL=isolate-driver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"isolate-driver.js","names":[],"sources":["../../src/isolate-driver.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { DAYTONA_RESULT_MARKER, wrapCode } from './wrap-code'\nimport type {\n ExecutionResult,\n IsolateConfig,\n IsolateContext,\n IsolateDriver,\n NormalizedError,\n ToolBinding,\n} from '@tanstack/ai-code-mode'\nimport type {\n DaytonaCodeRunResponse,\n DaytonaExecutionEnvelope,\n DaytonaExecutionError,\n DaytonaSandboxLike,\n ToolCallRequest,\n ToolResultPayload,\n ToolSchema,\n} from './types'\n\nconst TOOL_CALL_ID = /^tc_(0|[1-9]\\d*)$/\n\nexport interface DaytonaIsolateDriverConfig {\n /**\n * Caller-owned Daytona SDK sandbox or any object with a compatible\n * `process.codeRun`. Context disposal prevents further use of this sandbox,\n * but sandbox creation and cleanup stay with the caller.\n */\n sandbox: DaytonaSandboxLike\n\n /**\n * Default total execution timeout in milliseconds (default: 30000).\n * Each Daytona `codeRun` receives the remaining budget as whole seconds.\n */\n timeout?: number\n\n /**\n * Maximum number of tool callback rounds (default: 10).\n */\n maxToolRounds?: number\n}\n\nfunction bindingsToSchemas(\n bindings: Record<string, ToolBinding>,\n): Array<ToolSchema> {\n return Object.entries(bindings).map(([name, binding]) => ({\n name,\n description: binding.description,\n inputSchema: binding.inputSchema,\n }))\n}\n\nfunction normalizeError(error: unknown): DaytonaExecutionError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack !== undefined ? { stack: error.stack } : {}),\n }\n }\n\n if (typeof error === 'object' && error !== null) {\n const record = error as Record<string, unknown>\n return {\n name: typeof record.name === 'string' ? record.name : 'Error',\n message: typeof record.message === 'string' ? record.message : 'Error',\n }\n }\n\n return { name: 'Error', message: String(error) }\n}\n\nfunction toNormalizedError(error: DaytonaExecutionError): NormalizedError {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack !== undefined ? { stack: error.stack } : {}),\n }\n}\n\nfunction timeoutMsToSeconds(timeout: number): number {\n return Math.ceil(timeout / 1000)\n}\n\nfunction createResultMarker(): string {\n return `${DAYTONA_RESULT_MARKER}:${randomUUID()}:`\n}\n\nfunction validateTimeoutMs(timeout: number, fieldName: string): number {\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new Error(`${fieldName} must be a finite positive number`)\n }\n return timeout\n}\n\nfunction validateMaxToolRounds(maxToolRounds: number): number {\n if (\n !Number.isFinite(maxToolRounds) ||\n !Number.isInteger(maxToolRounds) ||\n maxToolRounds < 0\n ) {\n throw new Error('maxToolRounds must be a finite non-negative integer')\n }\n return maxToolRounds\n}\n\nfunction outputFromCodeRun(response: DaytonaCodeRunResponse): string {\n const stdout = response.artifacts?.stdout\n if (stdout !== undefined) {\n return stdout\n }\n if (response.result !== undefined) {\n return response.result\n }\n return ''\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction hasOwn<T extends object>(object: T, key: PropertyKey): key is keyof T {\n return Object.prototype.hasOwnProperty.call(object, key)\n}\n\nfunction toolCallIdFor(index: number): string {\n return `tc_${index}`\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n milliseconds: number,\n): Promise<T | undefined> {\n let timer: number | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(resolve, milliseconds)\n })\n\n try {\n return await Promise.race([promise, timeout])\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n }\n}\n\nfunction readStringArray(value: unknown, fieldName: string): Array<string> {\n if (!Array.isArray(value)) {\n throw new Error(`Daytona envelope field '${fieldName}' must be an array`)\n }\n if (!value.every((item): item is string => typeof item === 'string')) {\n throw new Error(\n `Daytona envelope field '${fieldName}' must contain only strings`,\n )\n }\n return value\n}\n\nfunction readExecutionError(\n value: unknown,\n fieldName: string,\n): DaytonaExecutionError {\n if (!isRecord(value)) {\n throw new Error(`Daytona envelope field '${fieldName}' must be an object`)\n }\n\n const { name, message, stack } = value\n if (typeof name !== 'string' || typeof message !== 'string') {\n throw new Error(\n `Daytona envelope field '${fieldName}' must include string name and message`,\n )\n }\n\n return {\n name,\n message,\n ...(typeof stack === 'string' ? { stack } : {}),\n }\n}\n\nfunction readToolCalls(value: unknown): Array<ToolCallRequest> {\n if (!Array.isArray(value)) {\n throw new Error(\"Daytona envelope field 'toolCalls' must be an array\")\n }\n\n const seenIds = new Set<string>()\n\n return value.map((item) => {\n if (!isRecord(item)) {\n throw new Error('Daytona tool call must be an object')\n }\n\n const { id, name, args } = item\n if (typeof id !== 'string' || typeof name !== 'string') {\n throw new Error('Daytona tool call must include string id and name')\n }\n if (!TOOL_CALL_ID.test(id)) {\n throw new Error(`Invalid Daytona tool call id: ${id}`)\n }\n if (seenIds.has(id)) {\n throw new Error(`Duplicate Daytona tool call id: ${id}`)\n }\n\n seenIds.add(id)\n return { id, name, args }\n })\n}\n\nfunction assertNewToolCallId(\n toolResults: Record<string, ToolResultPayload>,\n id: string,\n): void {\n if (hasOwn(toolResults, id)) {\n throw new Error(`Daytona tool call id already has a cached result: ${id}`)\n }\n}\n\nfunction assertExpectedToolCalls(\n toolCalls: Array<ToolCallRequest>,\n nextToolCallIndex: number,\n toolResults: Record<string, ToolResultPayload>,\n): void {\n if (toolCalls.length === 0) {\n throw new Error('Daytona need_tools response must include tool calls')\n }\n\n toolCalls.forEach((toolCall, index) => {\n assertNewToolCallId(toolResults, toolCall.id)\n\n const expectedId = toolCallIdFor(nextToolCallIndex + index)\n if (toolCall.id !== expectedId) {\n throw new Error(\n `Daytona tool call ids must be contiguous from ${expectedId}; received ${toolCall.id}`,\n )\n }\n })\n}\n\nasync function executeToolCall(\n bindings: Record<string, ToolBinding>,\n toolCall: ToolCallRequest,\n): Promise<[string, ToolResultPayload]> {\n const binding = hasOwn(bindings, toolCall.name)\n ? bindings[toolCall.name]\n : undefined\n\n if (!binding) {\n return [\n toolCall.id,\n {\n success: false,\n error: `Unknown tool: ${toolCall.name}`,\n },\n ]\n }\n\n try {\n const value = await binding.execute(toolCall.args)\n return [toolCall.id, { success: true, value }]\n } catch (toolError) {\n const error = normalizeError(toolError)\n return [\n toolCall.id,\n {\n success: false,\n error: error.message,\n },\n ]\n }\n}\n\nfunction parseExecutionEnvelope(\n output: string,\n resultMarker: string,\n): DaytonaExecutionEnvelope {\n const markerLine = output\n .split(/\\r?\\n/)\n .reverse()\n .find((line) => line.startsWith(resultMarker))\n\n if (!markerLine) {\n throw new Error('Daytona codeRun output did not include Code Mode marker')\n }\n\n const jsonText = markerLine.slice(resultMarker.length)\n const parsed: unknown = JSON.parse(jsonText)\n\n if (!isRecord(parsed) || typeof parsed.status !== 'string') {\n throw new Error('Daytona codeRun marker did not contain a valid envelope')\n }\n\n if (parsed.status === 'done') {\n if (typeof parsed.success !== 'boolean') {\n throw new Error(\"Daytona envelope field 'success' must be a boolean\")\n }\n\n if (parsed.success) {\n if (parsed.error !== undefined) {\n throw new Error('Daytona success envelope must not include error')\n }\n\n return {\n status: 'done',\n success: true,\n value: parsed.value,\n logs: readStringArray(parsed.logs, 'logs'),\n }\n }\n\n if (parsed.value !== undefined) {\n throw new Error('Daytona failure envelope must not include value')\n }\n\n return {\n status: 'done',\n success: false,\n error: readExecutionError(parsed.error, 'error'),\n logs: readStringArray(parsed.logs, 'logs'),\n }\n }\n\n if (parsed.status === 'need_tools') {\n return {\n status: 'need_tools',\n toolCalls: readToolCalls(parsed.toolCalls),\n logs: readStringArray(parsed.logs, 'logs'),\n }\n }\n\n if (parsed.status === 'error') {\n return {\n status: 'error',\n error: readExecutionError(parsed.error, 'error'),\n }\n }\n\n throw new Error(`Unknown Daytona execution status: ${parsed.status}`)\n}\n\nclass DaytonaIsolateContext implements IsolateContext {\n private disposed = false\n\n constructor(\n private readonly sandbox: DaytonaSandboxLike,\n private readonly bindings: Record<string, ToolBinding>,\n private readonly timeoutMs: number,\n private readonly maxToolRounds: number,\n ) {}\n\n private disposedResult<T>(logs: Array<string>): ExecutionResult<T> {\n return {\n success: false,\n error: {\n name: 'DisposedError',\n message: 'Context has been disposed',\n },\n logs,\n }\n }\n\n private timeoutResult<T>(logs: Array<string>): ExecutionResult<T> {\n return {\n success: false,\n error: {\n name: 'TimeoutError',\n message: `Exceeded Daytona execution timeout (${this.timeoutMs}ms)`,\n },\n logs,\n }\n }\n\n private isDisposed(): boolean {\n return this.disposed\n }\n\n private remainingTimeoutSeconds(deadlineMs: number): number | undefined {\n const remainingMs = deadlineMs - Date.now()\n if (remainingMs <= 0) {\n return undefined\n }\n return timeoutMsToSeconds(remainingMs)\n }\n\n private remainingTimeoutMs(deadlineMs: number): number | undefined {\n const remainingMs = deadlineMs - Date.now()\n return remainingMs > 0 ? remainingMs : undefined\n }\n\n async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {\n if (this.isDisposed()) {\n return this.disposedResult([])\n }\n\n const tools = bindingsToSchemas(this.bindings)\n let toolResults: Record<string, ToolResultPayload> | undefined\n let allLogs: Array<string> = []\n let toolRounds = 0\n let nextToolCallIndex = 0\n const deadlineMs = Date.now() + this.timeoutMs\n\n for (;;) {\n try {\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n\n const remainingCodeRunMs = this.remainingTimeoutMs(deadlineMs)\n if (remainingCodeRunMs === undefined) {\n return this.timeoutResult(allLogs)\n }\n\n const resultMarker = createResultMarker()\n const wrappedCode = wrapCode(code, tools, toolResults, resultMarker)\n const response = await withTimeout(\n this.sandbox.process.codeRun(\n wrappedCode,\n undefined,\n timeoutMsToSeconds(remainingCodeRunMs),\n ),\n remainingCodeRunMs,\n )\n if (response === undefined) {\n return this.timeoutResult(allLogs)\n }\n const output = outputFromCodeRun(response)\n const result = parseExecutionEnvelope(output, resultMarker)\n\n if (result.status === 'error') {\n return {\n success: false,\n error: toNormalizedError(result.error),\n logs: allLogs,\n }\n }\n\n if (result.status === 'done') {\n allLogs = result.logs\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n if (!result.success) {\n return {\n success: false,\n error: toNormalizedError(result.error),\n logs: allLogs,\n }\n }\n\n return {\n success: true,\n value: result.value as T,\n logs: allLogs,\n }\n }\n\n allLogs = result.logs\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n\n if (toolRounds >= this.maxToolRounds) {\n return {\n success: false,\n error: {\n name: 'MaxRoundsExceeded',\n message: `Exceeded maximum tool callback rounds (${this.maxToolRounds})`,\n },\n logs: allLogs,\n }\n }\n\n const cachedToolResults = { ...(toolResults ?? {}) }\n assertExpectedToolCalls(\n result.toolCalls,\n nextToolCallIndex,\n cachedToolResults,\n )\n toolRounds++\n nextToolCallIndex += result.toolCalls.length\n\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n\n const remainingToolMs = this.remainingTimeoutMs(deadlineMs)\n if (remainingToolMs === undefined) {\n return this.timeoutResult(allLogs)\n }\n const batchEntries = await withTimeout(\n Promise.all(\n result.toolCalls.map((toolCall) =>\n executeToolCall(this.bindings, toolCall),\n ),\n ),\n remainingToolMs,\n )\n if (batchEntries === undefined) {\n return this.timeoutResult(allLogs)\n }\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n if (this.remainingTimeoutSeconds(deadlineMs) === undefined) {\n return this.timeoutResult(allLogs)\n }\n const batchResults: Record<string, ToolResultPayload> = {}\n for (const [id, payload] of batchEntries) {\n batchResults[id] = payload\n }\n toolResults = { ...cachedToolResults, ...batchResults }\n } catch (error) {\n const normalized = normalizeError(error)\n return {\n success: false,\n error: {\n name: 'DaytonaExecutionError',\n message: `Failed to execute code in Daytona sandbox: ${normalized.message}`,\n },\n logs: allLogs,\n }\n }\n }\n }\n\n dispose(): Promise<void> {\n this.disposed = true\n return Promise.resolve()\n }\n}\n\nexport function createDaytonaIsolateDriver(\n config: DaytonaIsolateDriverConfig,\n): IsolateDriver {\n const sandbox = config.sandbox\n const defaultTimeoutMs = validateTimeoutMs(config.timeout ?? 30000, 'timeout')\n const maxToolRounds = validateMaxToolRounds(config.maxToolRounds ?? 10)\n\n return {\n createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {\n const timeoutMs = validateTimeoutMs(\n isolateConfig.timeout ?? defaultTimeoutMs,\n 'timeout',\n )\n return Promise.resolve(\n new DaytonaIsolateContext(\n sandbox,\n isolateConfig.bindings,\n timeoutMs,\n maxToolRounds,\n ),\n )\n },\n }\n}\n"],"mappings":";;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Aa,MAAM;GAErB,cAAc;IAAE,GAAG;IAAmB,GAAG;GAAa;EACxD,SAAS,OAAO;GAEd,OAAO;IACL,SAAS;IACT,OAAO;KACL,MAAM;KACN,SAAS,8CALM,eAAe,KAKyB,CAAA,CAAW;IACpE;IACA,MAAM;GACR;EACF;CAEJ;CAEA,UAAyB;EACvB,KAAK,WAAW;EAChB,OAAO,QAAQ,QAAQ;CACzB;AACF;AAEA,SAAgB,2BACd,QACe;CACf,MAAM,UAAU,OAAO;CACvB,MAAM,mBAAmB,kBAAkB,OAAO,WAAW,KAAO,SAAS;CAC7E,MAAM,gBAAgB,sBAAsB,OAAO,iBAAiB,EAAE;CAEtE,OAAO,EACL,cAAc,eAAuD;EACnE,MAAM,YAAY,kBAChB,cAAc,WAAW,kBACzB,SACF;EACA,OAAO,QAAQ,QACb,IAAI,sBACF,SACA,cAAc,UACd,WACA,aACF,CACF;CACF,EACF;AACF"}
1
+ {"version":3,"file":"isolate-driver.js","names":[],"sources":["../../src/isolate-driver.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { DAYTONA_RESULT_MARKER, wrapCode } from './wrap-code'\nimport type {\n ExecutionResult,\n IsolateConfig,\n IsolateContext,\n IsolateDriver,\n NormalizedError,\n ToolBinding,\n} from '@tanstack/ai-code-mode'\nimport type {\n DaytonaCodeRunResponse,\n DaytonaExecutionEnvelope,\n DaytonaExecutionError,\n DaytonaSandboxLike,\n ToolCallRequest,\n ToolResultPayload,\n ToolSchema,\n} from './types'\n\nconst TOOL_CALL_ID = /^tc_(0|[1-9]\\d*)$/\n\nexport interface DaytonaIsolateDriverConfig {\n /**\n * Caller-owned Daytona SDK sandbox or any object with a compatible\n * `process.codeRun`. Context disposal prevents further use of this sandbox,\n * but sandbox creation and cleanup stay with the caller.\n */\n sandbox: DaytonaSandboxLike\n\n /**\n * Default total execution timeout in milliseconds (default: 30000).\n * Each Daytona `codeRun` receives the remaining budget as whole seconds.\n */\n timeout?: number\n\n /**\n * Maximum number of tool callback rounds (default: 10).\n */\n maxToolRounds?: number\n}\n\nfunction bindingsToSchemas(\n bindings: Record<string, ToolBinding>,\n): Array<ToolSchema> {\n return Object.entries(bindings).map(([name, binding]) => ({\n name,\n description: binding.description,\n inputSchema: binding.inputSchema,\n }))\n}\n\nfunction normalizeError(error: unknown): DaytonaExecutionError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack !== undefined ? { stack: error.stack } : {}),\n }\n }\n\n if (typeof error === 'object' && error !== null) {\n const record = error as Record<string, unknown>\n return {\n name: typeof record.name === 'string' ? record.name : 'Error',\n message: typeof record.message === 'string' ? record.message : 'Error',\n }\n }\n\n return { name: 'Error', message: String(error) }\n}\n\nfunction toNormalizedError(error: DaytonaExecutionError): NormalizedError {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack !== undefined ? { stack: error.stack } : {}),\n }\n}\n\nfunction timeoutMsToSeconds(timeout: number): number {\n return Math.ceil(timeout / 1000)\n}\n\nfunction createResultMarker(): string {\n return `${DAYTONA_RESULT_MARKER}:${randomUUID()}:`\n}\n\nfunction validateTimeoutMs(timeout: number, fieldName: string): number {\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new Error(`${fieldName} must be a finite positive number`)\n }\n return timeout\n}\n\nfunction validateMaxToolRounds(maxToolRounds: number): number {\n if (\n !Number.isFinite(maxToolRounds) ||\n !Number.isInteger(maxToolRounds) ||\n maxToolRounds < 0\n ) {\n throw new Error('maxToolRounds must be a finite non-negative integer')\n }\n return maxToolRounds\n}\n\nfunction outputFromCodeRun(response: DaytonaCodeRunResponse): string {\n const stdout = response.artifacts?.stdout\n if (stdout !== undefined) {\n return stdout\n }\n if (response.result !== undefined) {\n return response.result\n }\n return ''\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction hasOwn<T extends object>(object: T, key: PropertyKey): key is keyof T {\n return Object.prototype.hasOwnProperty.call(object, key)\n}\n\nfunction toolCallIdFor(index: number): string {\n return `tc_${index}`\n}\n\n/** Resolves `undefined` when `milliseconds` pass or `signal` aborts first. */\nasync function withTimeout<T>(\n promise: Promise<T>,\n milliseconds: number,\n signal: AbortSignal | undefined,\n): Promise<T | undefined> {\n let timer: number | undefined\n let onAbort: (() => void) | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(resolve, milliseconds)\n onAbort = () => resolve(undefined)\n // `promise` started before this point and can abort the signal itself.\n if (signal?.aborted) onAbort()\n else signal?.addEventListener('abort', onAbort, { once: true })\n })\n\n try {\n return await Promise.race([promise, timeout])\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n if (onAbort) signal?.removeEventListener('abort', onAbort)\n }\n}\n\nfunction readStringArray(value: unknown, fieldName: string): Array<string> {\n if (!Array.isArray(value)) {\n throw new Error(`Daytona envelope field '${fieldName}' must be an array`)\n }\n if (!value.every((item): item is string => typeof item === 'string')) {\n throw new Error(\n `Daytona envelope field '${fieldName}' must contain only strings`,\n )\n }\n return value\n}\n\nfunction readExecutionError(\n value: unknown,\n fieldName: string,\n): DaytonaExecutionError {\n if (!isRecord(value)) {\n throw new Error(`Daytona envelope field '${fieldName}' must be an object`)\n }\n\n const { name, message, stack } = value\n if (typeof name !== 'string' || typeof message !== 'string') {\n throw new Error(\n `Daytona envelope field '${fieldName}' must include string name and message`,\n )\n }\n\n return {\n name,\n message,\n ...(typeof stack === 'string' ? { stack } : {}),\n }\n}\n\nfunction readToolCalls(value: unknown): Array<ToolCallRequest> {\n if (!Array.isArray(value)) {\n throw new Error(\"Daytona envelope field 'toolCalls' must be an array\")\n }\n\n const seenIds = new Set<string>()\n\n return value.map((item) => {\n if (!isRecord(item)) {\n throw new Error('Daytona tool call must be an object')\n }\n\n const { id, name, args } = item\n if (typeof id !== 'string' || typeof name !== 'string') {\n throw new Error('Daytona tool call must include string id and name')\n }\n if (!TOOL_CALL_ID.test(id)) {\n throw new Error(`Invalid Daytona tool call id: ${id}`)\n }\n if (seenIds.has(id)) {\n throw new Error(`Duplicate Daytona tool call id: ${id}`)\n }\n\n seenIds.add(id)\n return { id, name, args }\n })\n}\n\nfunction assertNewToolCallId(\n toolResults: Record<string, ToolResultPayload>,\n id: string,\n): void {\n if (hasOwn(toolResults, id)) {\n throw new Error(`Daytona tool call id already has a cached result: ${id}`)\n }\n}\n\nfunction assertExpectedToolCalls(\n toolCalls: Array<ToolCallRequest>,\n nextToolCallIndex: number,\n toolResults: Record<string, ToolResultPayload>,\n): void {\n if (toolCalls.length === 0) {\n throw new Error('Daytona need_tools response must include tool calls')\n }\n\n toolCalls.forEach((toolCall, index) => {\n assertNewToolCallId(toolResults, toolCall.id)\n\n const expectedId = toolCallIdFor(nextToolCallIndex + index)\n if (toolCall.id !== expectedId) {\n throw new Error(\n `Daytona tool call ids must be contiguous from ${expectedId}; received ${toolCall.id}`,\n )\n }\n })\n}\n\nasync function executeToolCall(\n bindings: Record<string, ToolBinding>,\n toolCall: ToolCallRequest,\n): Promise<[string, ToolResultPayload]> {\n const binding = hasOwn(bindings, toolCall.name)\n ? bindings[toolCall.name]\n : undefined\n\n if (!binding) {\n return [\n toolCall.id,\n {\n success: false,\n error: `Unknown tool: ${toolCall.name}`,\n },\n ]\n }\n\n try {\n const value = await binding.execute(toolCall.args)\n return [toolCall.id, { success: true, value }]\n } catch (toolError) {\n const error = normalizeError(toolError)\n return [\n toolCall.id,\n {\n success: false,\n error: error.message,\n },\n ]\n }\n}\n\nfunction parseExecutionEnvelope(\n output: string,\n resultMarker: string,\n): DaytonaExecutionEnvelope {\n const markerLine = output\n .split(/\\r?\\n/)\n .reverse()\n .find((line) => line.startsWith(resultMarker))\n\n if (!markerLine) {\n throw new Error('Daytona codeRun output did not include Code Mode marker')\n }\n\n const jsonText = markerLine.slice(resultMarker.length)\n const parsed: unknown = JSON.parse(jsonText)\n\n if (!isRecord(parsed) || typeof parsed.status !== 'string') {\n throw new Error('Daytona codeRun marker did not contain a valid envelope')\n }\n\n if (parsed.status === 'done') {\n if (typeof parsed.success !== 'boolean') {\n throw new Error(\"Daytona envelope field 'success' must be a boolean\")\n }\n\n if (parsed.success) {\n if (parsed.error !== undefined) {\n throw new Error('Daytona success envelope must not include error')\n }\n\n return {\n status: 'done',\n success: true,\n value: parsed.value,\n logs: readStringArray(parsed.logs, 'logs'),\n }\n }\n\n if (parsed.value !== undefined) {\n throw new Error('Daytona failure envelope must not include value')\n }\n\n return {\n status: 'done',\n success: false,\n error: readExecutionError(parsed.error, 'error'),\n logs: readStringArray(parsed.logs, 'logs'),\n }\n }\n\n if (parsed.status === 'need_tools') {\n return {\n status: 'need_tools',\n toolCalls: readToolCalls(parsed.toolCalls),\n logs: readStringArray(parsed.logs, 'logs'),\n }\n }\n\n if (parsed.status === 'error') {\n return {\n status: 'error',\n error: readExecutionError(parsed.error, 'error'),\n }\n }\n\n throw new Error(`Unknown Daytona execution status: ${parsed.status}`)\n}\n\nclass DaytonaIsolateContext implements IsolateContext {\n private disposed = false\n\n constructor(\n private readonly sandbox: DaytonaSandboxLike,\n private readonly bindings: Record<string, ToolBinding>,\n private readonly timeoutMs: number,\n private readonly maxToolRounds: number,\n ) {}\n\n private disposedResult<T>(logs: Array<string>): ExecutionResult<T> {\n return {\n success: false,\n error: {\n name: 'DisposedError',\n message: 'Context has been disposed',\n },\n logs,\n }\n }\n\n private timeoutResult<T>(logs: Array<string>): ExecutionResult<T> {\n return {\n success: false,\n error: {\n name: 'TimeoutError',\n message: `Exceeded Daytona execution timeout (${this.timeoutMs}ms)`,\n },\n logs,\n }\n }\n\n private abortedResult<T>(\n signal: AbortSignal,\n logs: Array<string>,\n ): ExecutionResult<T> {\n const reason: unknown = signal.reason\n return {\n success: false,\n error: {\n name: 'AbortError',\n message:\n reason instanceof Error ? reason.message : 'Execution was aborted',\n },\n logs,\n }\n }\n\n private isDisposed(): boolean {\n return this.disposed\n }\n\n private remainingTimeoutSeconds(deadlineMs: number): number | undefined {\n const remainingMs = deadlineMs - Date.now()\n if (remainingMs <= 0) {\n return undefined\n }\n return timeoutMsToSeconds(remainingMs)\n }\n\n private remainingTimeoutMs(deadlineMs: number): number | undefined {\n const remainingMs = deadlineMs - Date.now()\n return remainingMs > 0 ? remainingMs : undefined\n }\n\n /**\n * `options.signal` stops the wait and any later tool round. The Daytona\n * SDK cannot cancel a `codeRun`, so a started run ends at its own timeout.\n */\n async execute<T = unknown>(\n code: string,\n options?: { signal?: AbortSignal },\n ): Promise<ExecutionResult<T>> {\n const signal = options?.signal\n if (this.isDisposed()) {\n return this.disposedResult([])\n }\n\n const tools = bindingsToSchemas(this.bindings)\n let toolResults: Record<string, ToolResultPayload> | undefined\n let allLogs: Array<string> = []\n let toolRounds = 0\n let nextToolCallIndex = 0\n const deadlineMs = Date.now() + this.timeoutMs\n\n for (;;) {\n try {\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n if (signal?.aborted) return this.abortedResult(signal, allLogs)\n\n const remainingCodeRunMs = this.remainingTimeoutMs(deadlineMs)\n if (remainingCodeRunMs === undefined) {\n return this.timeoutResult(allLogs)\n }\n\n const resultMarker = createResultMarker()\n const wrappedCode = wrapCode(code, tools, toolResults, resultMarker)\n const response = await withTimeout(\n this.sandbox.process.codeRun(\n wrappedCode,\n undefined,\n timeoutMsToSeconds(remainingCodeRunMs),\n ),\n remainingCodeRunMs,\n signal,\n )\n if (signal?.aborted) return this.abortedResult(signal, allLogs)\n if (response === undefined) {\n return this.timeoutResult(allLogs)\n }\n const output = outputFromCodeRun(response)\n const result = parseExecutionEnvelope(output, resultMarker)\n\n if (result.status === 'error') {\n return {\n success: false,\n error: toNormalizedError(result.error),\n logs: allLogs,\n }\n }\n\n if (result.status === 'done') {\n allLogs = result.logs\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n if (!result.success) {\n return {\n success: false,\n error: toNormalizedError(result.error),\n logs: allLogs,\n }\n }\n\n return {\n success: true,\n value: result.value as T,\n logs: allLogs,\n }\n }\n\n allLogs = result.logs\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n\n if (toolRounds >= this.maxToolRounds) {\n return {\n success: false,\n error: {\n name: 'MaxRoundsExceeded',\n message: `Exceeded maximum tool callback rounds (${this.maxToolRounds})`,\n },\n logs: allLogs,\n }\n }\n\n const cachedToolResults = { ...(toolResults ?? {}) }\n assertExpectedToolCalls(\n result.toolCalls,\n nextToolCallIndex,\n cachedToolResults,\n )\n toolRounds++\n nextToolCallIndex += result.toolCalls.length\n\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n\n const remainingToolMs = this.remainingTimeoutMs(deadlineMs)\n if (remainingToolMs === undefined) {\n return this.timeoutResult(allLogs)\n }\n const batchEntries = await withTimeout(\n Promise.all(\n result.toolCalls.map((toolCall) =>\n executeToolCall(this.bindings, toolCall),\n ),\n ),\n remainingToolMs,\n signal,\n )\n if (signal?.aborted) return this.abortedResult(signal, allLogs)\n if (batchEntries === undefined) {\n return this.timeoutResult(allLogs)\n }\n if (this.isDisposed()) {\n return this.disposedResult(allLogs)\n }\n if (this.remainingTimeoutSeconds(deadlineMs) === undefined) {\n return this.timeoutResult(allLogs)\n }\n const batchResults: Record<string, ToolResultPayload> = {}\n for (const [id, payload] of batchEntries) {\n batchResults[id] = payload\n }\n toolResults = { ...cachedToolResults, ...batchResults }\n } catch (error) {\n const normalized = normalizeError(error)\n return {\n success: false,\n error: {\n name: 'DaytonaExecutionError',\n message: `Failed to execute code in Daytona sandbox: ${normalized.message}`,\n },\n logs: allLogs,\n }\n }\n }\n }\n\n dispose(): Promise<void> {\n this.disposed = true\n return Promise.resolve()\n }\n}\n\nexport function createDaytonaIsolateDriver(\n config: DaytonaIsolateDriverConfig,\n): IsolateDriver {\n const sandbox = config.sandbox\n const defaultTimeoutMs = validateTimeoutMs(config.timeout ?? 30000, 'timeout')\n const maxToolRounds = validateMaxToolRounds(config.maxToolRounds ?? 10)\n\n return {\n createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {\n const timeoutMs = validateTimeoutMs(\n isolateConfig.timeout ?? defaultTimeoutMs,\n 'timeout',\n )\n return Promise.resolve(\n new DaytonaIsolateContext(\n sandbox,\n isolateConfig.bindings,\n timeoutMs,\n maxToolRounds,\n ),\n )\n },\n }\n}\n"],"mappings":";;;AAoBA,IAAM,eAAe;AAsBrB,SAAS,kBACP,UACmB;CACnB,OAAO,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK,CAAC,MAAM,cAAc;EACxD;EACA,aAAa,QAAQ;EACrB,aAAa,QAAQ;CACvB,EAAE;AACJ;AAEA,SAAS,eAAe,OAAuC;CAC7D,IAAI,iBAAiB,OACnB,OAAO;EACL,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,GAAI,MAAM,UAAU,KAAA,IAAY,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;CAC5D;CAGF,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC/C,MAAM,SAAS;EACf,OAAO;GACL,MAAM,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO;GACtD,SAAS,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;EACjE;CACF;CAEA,OAAO;EAAE,MAAM;EAAS,SAAS,OAAO,KAAK;CAAE;AACjD;AAEA,SAAS,kBAAkB,OAA+C;CACxE,OAAO;EACL,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,GAAI,MAAM,UAAU,KAAA,IAAY,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;CAC5D;AACF;AAEA,SAAS,mBAAmB,SAAyB;CACnD,OAAO,KAAK,KAAK,UAAU,GAAI;AACjC;AAEA,SAAS,qBAA6B;CACpC,OAAO,GAAG,sBAAsB,GAAG,WAAW,EAAE;AAClD;AAEA,SAAS,kBAAkB,SAAiB,WAA2B;CACrE,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,WAAW,GAC1C,MAAM,IAAI,MAAM,GAAG,UAAU,kCAAkC;CAEjE,OAAO;AACT;AAEA,SAAS,sBAAsB,eAA+B;CAC5D,IACE,CAAC,OAAO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,SACA,cAAc,UACd,WACA,aACF,CACF;CACF,EACF;AACF"}
@@ -1,4 +1,4 @@
1
- //#region src/wrap-code.ts
1
+ // src/wrap-code.ts
2
2
  var DAYTONA_RESULT_MARKER = "__TANSTACK_AI_CODE_MODE_RESULT__";
3
3
  var VALID_TOOL_NAME = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
4
4
  var RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([
@@ -194,7 +194,6 @@ function wrapCode(code, tools, toolResults, resultMarker = DAYTONA_RESULT_MARKER
194
194
  });
195
195
  `;
196
196
  }
197
- //#endregion
198
197
  export { DAYTONA_RESULT_MARKER, generateToolWrappers, wrapCode };
199
198
 
200
199
  //# sourceMappingURL=wrap-code.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-isolate-daytona",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "Daytona sandbox driver for TanStack AI Code Mode TypeScript execution.",
5
5
  "author": "",
6
6
  "license": "MIT",
@@ -38,12 +38,12 @@
38
38
  "code-execution"
39
39
  ],
40
40
  "peerDependencies": {
41
- "@tanstack/ai-code-mode": "^1.0.0"
41
+ "@tanstack/ai-code-mode": "^1.1.1"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@daytona/sdk": "^0.192.0",
45
- "@vitest/coverage-v8": "4.1.10",
46
- "@tanstack/ai-code-mode": "1.0.0"
45
+ "@vitest/coverage-v8": "4.1.12",
46
+ "@tanstack/ai-code-mode": "1.1.1"
47
47
  },
48
48
  "scripts": {
49
49
  "build": "vite build",
@@ -127,13 +127,20 @@ function toolCallIdFor(index: number): string {
127
127
  return `tc_${index}`
128
128
  }
129
129
 
130
+ /** Resolves `undefined` when `milliseconds` pass or `signal` aborts first. */
130
131
  async function withTimeout<T>(
131
132
  promise: Promise<T>,
132
133
  milliseconds: number,
134
+ signal: AbortSignal | undefined,
133
135
  ): Promise<T | undefined> {
134
136
  let timer: number | undefined
137
+ let onAbort: (() => void) | undefined
135
138
  const timeout = new Promise<undefined>((resolve) => {
136
139
  timer = setTimeout(resolve, milliseconds)
140
+ onAbort = () => resolve(undefined)
141
+ // `promise` started before this point and can abort the signal itself.
142
+ if (signal?.aborted) onAbort()
143
+ else signal?.addEventListener('abort', onAbort, { once: true })
137
144
  })
138
145
 
139
146
  try {
@@ -142,6 +149,7 @@ async function withTimeout<T>(
142
149
  if (timer !== undefined) {
143
150
  clearTimeout(timer)
144
151
  }
152
+ if (onAbort) signal?.removeEventListener('abort', onAbort)
145
153
  }
146
154
  }
147
155
 
@@ -370,6 +378,22 @@ class DaytonaIsolateContext implements IsolateContext {
370
378
  }
371
379
  }
372
380
 
381
+ private abortedResult<T>(
382
+ signal: AbortSignal,
383
+ logs: Array<string>,
384
+ ): ExecutionResult<T> {
385
+ const reason: unknown = signal.reason
386
+ return {
387
+ success: false,
388
+ error: {
389
+ name: 'AbortError',
390
+ message:
391
+ reason instanceof Error ? reason.message : 'Execution was aborted',
392
+ },
393
+ logs,
394
+ }
395
+ }
396
+
373
397
  private isDisposed(): boolean {
374
398
  return this.disposed
375
399
  }
@@ -387,7 +411,15 @@ class DaytonaIsolateContext implements IsolateContext {
387
411
  return remainingMs > 0 ? remainingMs : undefined
388
412
  }
389
413
 
390
- async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {
414
+ /**
415
+ * `options.signal` stops the wait and any later tool round. The Daytona
416
+ * SDK cannot cancel a `codeRun`, so a started run ends at its own timeout.
417
+ */
418
+ async execute<T = unknown>(
419
+ code: string,
420
+ options?: { signal?: AbortSignal },
421
+ ): Promise<ExecutionResult<T>> {
422
+ const signal = options?.signal
391
423
  if (this.isDisposed()) {
392
424
  return this.disposedResult([])
393
425
  }
@@ -404,6 +436,7 @@ class DaytonaIsolateContext implements IsolateContext {
404
436
  if (this.isDisposed()) {
405
437
  return this.disposedResult(allLogs)
406
438
  }
439
+ if (signal?.aborted) return this.abortedResult(signal, allLogs)
407
440
 
408
441
  const remainingCodeRunMs = this.remainingTimeoutMs(deadlineMs)
409
442
  if (remainingCodeRunMs === undefined) {
@@ -419,7 +452,9 @@ class DaytonaIsolateContext implements IsolateContext {
419
452
  timeoutMsToSeconds(remainingCodeRunMs),
420
453
  ),
421
454
  remainingCodeRunMs,
455
+ signal,
422
456
  )
457
+ if (signal?.aborted) return this.abortedResult(signal, allLogs)
423
458
  if (response === undefined) {
424
459
  return this.timeoutResult(allLogs)
425
460
  }
@@ -494,7 +529,9 @@ class DaytonaIsolateContext implements IsolateContext {
494
529
  ),
495
530
  ),
496
531
  remainingToolMs,
532
+ signal,
497
533
  )
534
+ if (signal?.aborted) return this.abortedResult(signal, allLogs)
498
535
  if (batchEntries === undefined) {
499
536
  return this.timeoutResult(allLogs)
500
537
  }