@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.
- package/LICENSE +21 -0
- package/README.md +91 -0
- package/dist/esm/index.d.ts +18 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/isolate-driver.d.ts +20 -0
- package/dist/esm/isolate-driver.js +311 -0
- package/dist/esm/isolate-driver.js.map +1 -0
- package/dist/esm/types.d.ts +65 -0
- package/dist/esm/wrap-code.d.ts +4 -0
- package/dist/esm/wrap-code.js +200 -0
- package/dist/esm/wrap-code.js.map +1 -0
- package/package.json +62 -0
- package/src/index.ts +36 -0
- package/src/isolate-driver.ts +555 -0
- package/src/types.ts +85 -0
- package/src/wrap-code.ts +218 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Tanner Linsley
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# @tanstack/ai-isolate-daytona
|
|
2
|
+
|
|
3
|
+
Daytona sandbox driver for TanStack AI Code Mode.
|
|
4
|
+
|
|
5
|
+
This package runs generated JavaScript or TypeScript in a caller-provided Daytona sandbox and keeps TanStack tool implementations in your host process. When generated code calls an `external_*` tool, the sandbox returns a `need_tools` payload, the host executes the matching `ToolBinding.execute` callbacks, and the driver replays the code with accumulated tool results until it completes.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @tanstack/ai-isolate-daytona @tanstack/ai-code-mode
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
If you use the official Daytona SDK to create sandboxes, install it in your app too:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pnpm add @daytona/sdk
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { Daytona } from '@daytona/sdk'
|
|
23
|
+
import { createCodeMode } from '@tanstack/ai-code-mode'
|
|
24
|
+
import { createDaytonaIsolateDriver } from '@tanstack/ai-isolate-daytona'
|
|
25
|
+
|
|
26
|
+
const daytona = new Daytona()
|
|
27
|
+
const sandbox = await daytona.create({ language: 'typescript' })
|
|
28
|
+
|
|
29
|
+
const driver = createDaytonaIsolateDriver({
|
|
30
|
+
sandbox,
|
|
31
|
+
timeout: 30_000,
|
|
32
|
+
maxToolRounds: 10,
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
const { tool, systemPrompt } = createCodeMode({
|
|
36
|
+
driver,
|
|
37
|
+
tools: [myServerTool],
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The driver accepts a structural sandbox object with `sandbox.process.codeRun(...)`; it does not require `@daytona/sdk` as a package dependency.
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
### `createDaytonaIsolateDriver(config)`
|
|
46
|
+
|
|
47
|
+
Creates an isolate driver that delegates Code Mode execution to a Daytona sandbox.
|
|
48
|
+
|
|
49
|
+
- `sandbox` (required): caller-owned object with `process.codeRun(code, params?, timeout?)`
|
|
50
|
+
- `timeout` (optional): total execution timeout across replay rounds, in milliseconds (default: `30000`)
|
|
51
|
+
- `maxToolRounds` (optional): maximum `need_tools` replay rounds per execution (default: `10`)
|
|
52
|
+
|
|
53
|
+
## Requirements
|
|
54
|
+
|
|
55
|
+
- Use a sandbox language/runtime that can execute the JavaScript emitted by Code Mode.
|
|
56
|
+
- Tool inputs and outputs must be JSON-serializable.
|
|
57
|
+
- Sandbox lifecycle, network access, filesystem contents, secrets, and cleanup are owned by your application. Creating a Code Mode context does not create or delete a Daytona sandbox.
|
|
58
|
+
|
|
59
|
+
## How It Works
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
Host process Daytona sandbox
|
|
63
|
+
------------ ---------------
|
|
64
|
+
createCodeMode + tools
|
|
65
|
+
wrap generated code ---------> run with process.codeRun
|
|
66
|
+
execute host tools <--------- need_tools requests
|
|
67
|
+
replay with toolResults ---------> continue execution
|
|
68
|
+
final result/logs <--------- done or error envelope
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The host process talks directly to a Daytona sandbox through `process.codeRun`, while tool execution stays host-owned.
|
|
72
|
+
|
|
73
|
+
## Validation
|
|
74
|
+
|
|
75
|
+
Run the package checks once the implementation files are present:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pnpm --filter @tanstack/ai-isolate-daytona test:lib
|
|
79
|
+
pnpm --filter @tanstack/ai-isolate-daytona test:types
|
|
80
|
+
pnpm --filter @tanstack/ai-isolate-daytona test:eslint
|
|
81
|
+
pnpm --filter @tanstack/ai-isolate-daytona build
|
|
82
|
+
pnpm --filter @tanstack/ai-isolate-daytona test:build
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Live Daytona validation should be gated on explicit credentials and sandbox setup in the implementation tests or a local smoke script.
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
DAYTONA_LIVE_TEST=1 DAYTONA_API_KEY=... pnpm --filter @tanstack/ai-isolate-daytona test:live
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The live suite is skipped unless `DAYTONA_LIVE_TEST=1` and `DAYTONA_API_KEY` are both present.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @tanstack/ai-isolate-daytona
|
|
3
|
+
*
|
|
4
|
+
* Daytona sandbox driver for TanStack AI Code Mode.
|
|
5
|
+
* Execute LLM-generated code inside a caller-provided Daytona sandbox.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { createDaytonaIsolateDriver } from '@tanstack/ai-isolate-daytona'
|
|
10
|
+
*
|
|
11
|
+
* const driver = createDaytonaIsolateDriver({ sandbox })
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @packageDocumentation
|
|
15
|
+
*/
|
|
16
|
+
export { createDaytonaIsolateDriver, type DaytonaIsolateDriverConfig, } from './isolate-driver.js';
|
|
17
|
+
export type { DaytonaCodeRunArtifacts, DaytonaCodeRunParams, DaytonaCodeRunResponse, DaytonaProcessLike, DaytonaSandboxLike, } from './types.js';
|
|
18
|
+
export type { ExecutionResult, IsolateConfig, IsolateContext, IsolateDriver, NormalizedError, } from '@tanstack/ai-code-mode';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { IsolateDriver } from '@tanstack/ai-code-mode';
|
|
2
|
+
import { DaytonaSandboxLike } from './types.js';
|
|
3
|
+
export interface DaytonaIsolateDriverConfig {
|
|
4
|
+
/**
|
|
5
|
+
* Caller-owned Daytona SDK sandbox or any object with a compatible
|
|
6
|
+
* `process.codeRun`. Context disposal prevents further use of this sandbox,
|
|
7
|
+
* but sandbox creation and cleanup stay with the caller.
|
|
8
|
+
*/
|
|
9
|
+
sandbox: DaytonaSandboxLike;
|
|
10
|
+
/**
|
|
11
|
+
* Default total execution timeout in milliseconds (default: 30000).
|
|
12
|
+
* Each Daytona `codeRun` receives the remaining budget as whole seconds.
|
|
13
|
+
*/
|
|
14
|
+
timeout?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Maximum number of tool callback rounds (default: 10).
|
|
17
|
+
*/
|
|
18
|
+
maxToolRounds?: number;
|
|
19
|
+
}
|
|
20
|
+
export declare function createDaytonaIsolateDriver(config: DaytonaIsolateDriverConfig): IsolateDriver;
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { DAYTONA_RESULT_MARKER, wrapCode } from "./wrap-code.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
//#region src/isolate-driver.ts
|
|
4
|
+
var TOOL_CALL_ID = /^tc_(0|[1-9]\d*)$/;
|
|
5
|
+
function bindingsToSchemas(bindings) {
|
|
6
|
+
return Object.entries(bindings).map(([name, binding]) => ({
|
|
7
|
+
name,
|
|
8
|
+
description: binding.description,
|
|
9
|
+
inputSchema: binding.inputSchema
|
|
10
|
+
}));
|
|
11
|
+
}
|
|
12
|
+
function normalizeError(error) {
|
|
13
|
+
if (error instanceof Error) return {
|
|
14
|
+
name: error.name,
|
|
15
|
+
message: error.message,
|
|
16
|
+
...error.stack !== void 0 ? { stack: error.stack } : {}
|
|
17
|
+
};
|
|
18
|
+
if (typeof error === "object" && error !== null) {
|
|
19
|
+
const record = error;
|
|
20
|
+
return {
|
|
21
|
+
name: typeof record.name === "string" ? record.name : "Error",
|
|
22
|
+
message: typeof record.message === "string" ? record.message : "Error"
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
name: "Error",
|
|
27
|
+
message: String(error)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function toNormalizedError(error) {
|
|
31
|
+
return {
|
|
32
|
+
name: error.name,
|
|
33
|
+
message: error.message,
|
|
34
|
+
...error.stack !== void 0 ? { stack: error.stack } : {}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function timeoutMsToSeconds(timeout) {
|
|
38
|
+
return Math.ceil(timeout / 1e3);
|
|
39
|
+
}
|
|
40
|
+
function createResultMarker() {
|
|
41
|
+
return `${DAYTONA_RESULT_MARKER}:${randomUUID()}:`;
|
|
42
|
+
}
|
|
43
|
+
function validateTimeoutMs(timeout, fieldName) {
|
|
44
|
+
if (!Number.isFinite(timeout) || timeout <= 0) throw new Error(`${fieldName} must be a finite positive number`);
|
|
45
|
+
return timeout;
|
|
46
|
+
}
|
|
47
|
+
function validateMaxToolRounds(maxToolRounds) {
|
|
48
|
+
if (!Number.isFinite(maxToolRounds) || !Number.isInteger(maxToolRounds) || maxToolRounds < 0) throw new Error("maxToolRounds must be a finite non-negative integer");
|
|
49
|
+
return maxToolRounds;
|
|
50
|
+
}
|
|
51
|
+
function outputFromCodeRun(response) {
|
|
52
|
+
const stdout = response.artifacts?.stdout;
|
|
53
|
+
if (stdout !== void 0) return stdout;
|
|
54
|
+
if (response.result !== void 0) return response.result;
|
|
55
|
+
return "";
|
|
56
|
+
}
|
|
57
|
+
function isRecord(value) {
|
|
58
|
+
return typeof value === "object" && value !== null;
|
|
59
|
+
}
|
|
60
|
+
function hasOwn(object, key) {
|
|
61
|
+
return Object.prototype.hasOwnProperty.call(object, key);
|
|
62
|
+
}
|
|
63
|
+
function toolCallIdFor(index) {
|
|
64
|
+
return `tc_${index}`;
|
|
65
|
+
}
|
|
66
|
+
async function withTimeout(promise, milliseconds) {
|
|
67
|
+
let timer;
|
|
68
|
+
const timeout = new Promise((resolve) => {
|
|
69
|
+
timer = setTimeout(resolve, milliseconds);
|
|
70
|
+
});
|
|
71
|
+
try {
|
|
72
|
+
return await Promise.race([promise, timeout]);
|
|
73
|
+
} finally {
|
|
74
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function readStringArray(value, fieldName) {
|
|
78
|
+
if (!Array.isArray(value)) throw new Error(`Daytona envelope field '${fieldName}' must be an array`);
|
|
79
|
+
if (!value.every((item) => typeof item === "string")) throw new Error(`Daytona envelope field '${fieldName}' must contain only strings`);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
function readExecutionError(value, fieldName) {
|
|
83
|
+
if (!isRecord(value)) throw new Error(`Daytona envelope field '${fieldName}' must be an object`);
|
|
84
|
+
const { name, message, stack } = value;
|
|
85
|
+
if (typeof name !== "string" || typeof message !== "string") throw new Error(`Daytona envelope field '${fieldName}' must include string name and message`);
|
|
86
|
+
return {
|
|
87
|
+
name,
|
|
88
|
+
message,
|
|
89
|
+
...typeof stack === "string" ? { stack } : {}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function readToolCalls(value) {
|
|
93
|
+
if (!Array.isArray(value)) throw new Error("Daytona envelope field 'toolCalls' must be an array");
|
|
94
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
95
|
+
return value.map((item) => {
|
|
96
|
+
if (!isRecord(item)) throw new Error("Daytona tool call must be an object");
|
|
97
|
+
const { id, name, args } = item;
|
|
98
|
+
if (typeof id !== "string" || typeof name !== "string") throw new Error("Daytona tool call must include string id and name");
|
|
99
|
+
if (!TOOL_CALL_ID.test(id)) throw new Error(`Invalid Daytona tool call id: ${id}`);
|
|
100
|
+
if (seenIds.has(id)) throw new Error(`Duplicate Daytona tool call id: ${id}`);
|
|
101
|
+
seenIds.add(id);
|
|
102
|
+
return {
|
|
103
|
+
id,
|
|
104
|
+
name,
|
|
105
|
+
args
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
function assertNewToolCallId(toolResults, id) {
|
|
110
|
+
if (hasOwn(toolResults, id)) throw new Error(`Daytona tool call id already has a cached result: ${id}`);
|
|
111
|
+
}
|
|
112
|
+
function assertExpectedToolCalls(toolCalls, nextToolCallIndex, toolResults) {
|
|
113
|
+
if (toolCalls.length === 0) throw new Error("Daytona need_tools response must include tool calls");
|
|
114
|
+
toolCalls.forEach((toolCall, index) => {
|
|
115
|
+
assertNewToolCallId(toolResults, toolCall.id);
|
|
116
|
+
const expectedId = toolCallIdFor(nextToolCallIndex + index);
|
|
117
|
+
if (toolCall.id !== expectedId) throw new Error(`Daytona tool call ids must be contiguous from ${expectedId}; received ${toolCall.id}`);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
async function executeToolCall(bindings, toolCall) {
|
|
121
|
+
const binding = hasOwn(bindings, toolCall.name) ? bindings[toolCall.name] : void 0;
|
|
122
|
+
if (!binding) return [toolCall.id, {
|
|
123
|
+
success: false,
|
|
124
|
+
error: `Unknown tool: ${toolCall.name}`
|
|
125
|
+
}];
|
|
126
|
+
try {
|
|
127
|
+
const value = await binding.execute(toolCall.args);
|
|
128
|
+
return [toolCall.id, {
|
|
129
|
+
success: true,
|
|
130
|
+
value
|
|
131
|
+
}];
|
|
132
|
+
} catch (toolError) {
|
|
133
|
+
const error = normalizeError(toolError);
|
|
134
|
+
return [toolCall.id, {
|
|
135
|
+
success: false,
|
|
136
|
+
error: error.message
|
|
137
|
+
}];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function parseExecutionEnvelope(output, resultMarker) {
|
|
141
|
+
const markerLine = output.split(/\r?\n/).reverse().find((line) => line.startsWith(resultMarker));
|
|
142
|
+
if (!markerLine) throw new Error("Daytona codeRun output did not include Code Mode marker");
|
|
143
|
+
const jsonText = markerLine.slice(resultMarker.length);
|
|
144
|
+
const parsed = JSON.parse(jsonText);
|
|
145
|
+
if (!isRecord(parsed) || typeof parsed.status !== "string") throw new Error("Daytona codeRun marker did not contain a valid envelope");
|
|
146
|
+
if (parsed.status === "done") {
|
|
147
|
+
if (typeof parsed.success !== "boolean") throw new Error("Daytona envelope field 'success' must be a boolean");
|
|
148
|
+
if (parsed.success) {
|
|
149
|
+
if (parsed.error !== void 0) throw new Error("Daytona success envelope must not include error");
|
|
150
|
+
return {
|
|
151
|
+
status: "done",
|
|
152
|
+
success: true,
|
|
153
|
+
value: parsed.value,
|
|
154
|
+
logs: readStringArray(parsed.logs, "logs")
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
if (parsed.value !== void 0) throw new Error("Daytona failure envelope must not include value");
|
|
158
|
+
return {
|
|
159
|
+
status: "done",
|
|
160
|
+
success: false,
|
|
161
|
+
error: readExecutionError(parsed.error, "error"),
|
|
162
|
+
logs: readStringArray(parsed.logs, "logs")
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
if (parsed.status === "need_tools") return {
|
|
166
|
+
status: "need_tools",
|
|
167
|
+
toolCalls: readToolCalls(parsed.toolCalls),
|
|
168
|
+
logs: readStringArray(parsed.logs, "logs")
|
|
169
|
+
};
|
|
170
|
+
if (parsed.status === "error") return {
|
|
171
|
+
status: "error",
|
|
172
|
+
error: readExecutionError(parsed.error, "error")
|
|
173
|
+
};
|
|
174
|
+
throw new Error(`Unknown Daytona execution status: ${parsed.status}`);
|
|
175
|
+
}
|
|
176
|
+
var DaytonaIsolateContext = class {
|
|
177
|
+
sandbox;
|
|
178
|
+
bindings;
|
|
179
|
+
timeoutMs;
|
|
180
|
+
maxToolRounds;
|
|
181
|
+
disposed = false;
|
|
182
|
+
constructor(sandbox, bindings, timeoutMs, maxToolRounds) {
|
|
183
|
+
this.sandbox = sandbox;
|
|
184
|
+
this.bindings = bindings;
|
|
185
|
+
this.timeoutMs = timeoutMs;
|
|
186
|
+
this.maxToolRounds = maxToolRounds;
|
|
187
|
+
}
|
|
188
|
+
disposedResult(logs) {
|
|
189
|
+
return {
|
|
190
|
+
success: false,
|
|
191
|
+
error: {
|
|
192
|
+
name: "DisposedError",
|
|
193
|
+
message: "Context has been disposed"
|
|
194
|
+
},
|
|
195
|
+
logs
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
timeoutResult(logs) {
|
|
199
|
+
return {
|
|
200
|
+
success: false,
|
|
201
|
+
error: {
|
|
202
|
+
name: "TimeoutError",
|
|
203
|
+
message: `Exceeded Daytona execution timeout (${this.timeoutMs}ms)`
|
|
204
|
+
},
|
|
205
|
+
logs
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
isDisposed() {
|
|
209
|
+
return this.disposed;
|
|
210
|
+
}
|
|
211
|
+
remainingTimeoutSeconds(deadlineMs) {
|
|
212
|
+
const remainingMs = deadlineMs - Date.now();
|
|
213
|
+
if (remainingMs <= 0) return;
|
|
214
|
+
return timeoutMsToSeconds(remainingMs);
|
|
215
|
+
}
|
|
216
|
+
remainingTimeoutMs(deadlineMs) {
|
|
217
|
+
const remainingMs = deadlineMs - Date.now();
|
|
218
|
+
return remainingMs > 0 ? remainingMs : void 0;
|
|
219
|
+
}
|
|
220
|
+
async execute(code) {
|
|
221
|
+
if (this.isDisposed()) return this.disposedResult([]);
|
|
222
|
+
const tools = bindingsToSchemas(this.bindings);
|
|
223
|
+
let toolResults;
|
|
224
|
+
let allLogs = [];
|
|
225
|
+
let toolRounds = 0;
|
|
226
|
+
let nextToolCallIndex = 0;
|
|
227
|
+
const deadlineMs = Date.now() + this.timeoutMs;
|
|
228
|
+
for (;;) try {
|
|
229
|
+
if (this.isDisposed()) return this.disposedResult(allLogs);
|
|
230
|
+
const remainingCodeRunMs = this.remainingTimeoutMs(deadlineMs);
|
|
231
|
+
if (remainingCodeRunMs === void 0) return this.timeoutResult(allLogs);
|
|
232
|
+
const resultMarker = createResultMarker();
|
|
233
|
+
const wrappedCode = wrapCode(code, tools, toolResults, resultMarker);
|
|
234
|
+
const response = await withTimeout(this.sandbox.process.codeRun(wrappedCode, void 0, timeoutMsToSeconds(remainingCodeRunMs)), remainingCodeRunMs);
|
|
235
|
+
if (response === void 0) return this.timeoutResult(allLogs);
|
|
236
|
+
const result = parseExecutionEnvelope(outputFromCodeRun(response), resultMarker);
|
|
237
|
+
if (result.status === "error") return {
|
|
238
|
+
success: false,
|
|
239
|
+
error: toNormalizedError(result.error),
|
|
240
|
+
logs: allLogs
|
|
241
|
+
};
|
|
242
|
+
if (result.status === "done") {
|
|
243
|
+
allLogs = result.logs;
|
|
244
|
+
if (this.isDisposed()) return this.disposedResult(allLogs);
|
|
245
|
+
if (!result.success) return {
|
|
246
|
+
success: false,
|
|
247
|
+
error: toNormalizedError(result.error),
|
|
248
|
+
logs: allLogs
|
|
249
|
+
};
|
|
250
|
+
return {
|
|
251
|
+
success: true,
|
|
252
|
+
value: result.value,
|
|
253
|
+
logs: allLogs
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
allLogs = result.logs;
|
|
257
|
+
if (this.isDisposed()) return this.disposedResult(allLogs);
|
|
258
|
+
if (toolRounds >= this.maxToolRounds) return {
|
|
259
|
+
success: false,
|
|
260
|
+
error: {
|
|
261
|
+
name: "MaxRoundsExceeded",
|
|
262
|
+
message: `Exceeded maximum tool callback rounds (${this.maxToolRounds})`
|
|
263
|
+
},
|
|
264
|
+
logs: allLogs
|
|
265
|
+
};
|
|
266
|
+
const cachedToolResults = { ...toolResults ?? {} };
|
|
267
|
+
assertExpectedToolCalls(result.toolCalls, nextToolCallIndex, cachedToolResults);
|
|
268
|
+
toolRounds++;
|
|
269
|
+
nextToolCallIndex += result.toolCalls.length;
|
|
270
|
+
if (this.isDisposed()) return this.disposedResult(allLogs);
|
|
271
|
+
const remainingToolMs = this.remainingTimeoutMs(deadlineMs);
|
|
272
|
+
if (remainingToolMs === void 0) return this.timeoutResult(allLogs);
|
|
273
|
+
const batchEntries = await withTimeout(Promise.all(result.toolCalls.map((toolCall) => executeToolCall(this.bindings, toolCall))), remainingToolMs);
|
|
274
|
+
if (batchEntries === void 0) return this.timeoutResult(allLogs);
|
|
275
|
+
if (this.isDisposed()) return this.disposedResult(allLogs);
|
|
276
|
+
if (this.remainingTimeoutSeconds(deadlineMs) === void 0) return this.timeoutResult(allLogs);
|
|
277
|
+
const batchResults = {};
|
|
278
|
+
for (const [id, payload] of batchEntries) batchResults[id] = payload;
|
|
279
|
+
toolResults = {
|
|
280
|
+
...cachedToolResults,
|
|
281
|
+
...batchResults
|
|
282
|
+
};
|
|
283
|
+
} catch (error) {
|
|
284
|
+
return {
|
|
285
|
+
success: false,
|
|
286
|
+
error: {
|
|
287
|
+
name: "DaytonaExecutionError",
|
|
288
|
+
message: `Failed to execute code in Daytona sandbox: ${normalizeError(error).message}`
|
|
289
|
+
},
|
|
290
|
+
logs: allLogs
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
dispose() {
|
|
295
|
+
this.disposed = true;
|
|
296
|
+
return Promise.resolve();
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
function createDaytonaIsolateDriver(config) {
|
|
300
|
+
const sandbox = config.sandbox;
|
|
301
|
+
const defaultTimeoutMs = validateTimeoutMs(config.timeout ?? 3e4, "timeout");
|
|
302
|
+
const maxToolRounds = validateMaxToolRounds(config.maxToolRounds ?? 10);
|
|
303
|
+
return { createContext(isolateConfig) {
|
|
304
|
+
const timeoutMs = validateTimeoutMs(isolateConfig.timeout ?? defaultTimeoutMs, "timeout");
|
|
305
|
+
return Promise.resolve(new DaytonaIsolateContext(sandbox, isolateConfig.bindings, timeoutMs, maxToolRounds));
|
|
306
|
+
} };
|
|
307
|
+
}
|
|
308
|
+
//#endregion
|
|
309
|
+
export { createDaytonaIsolateDriver };
|
|
310
|
+
|
|
311
|
+
//# sourceMappingURL=isolate-driver.js.map
|
|
@@ -0,0 +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":";;;AAoBA,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;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"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structural Daytona process/code-run types plus the host/sandbox protocol.
|
|
3
|
+
*/
|
|
4
|
+
export interface DaytonaCodeRunArtifacts {
|
|
5
|
+
stdout?: string | undefined;
|
|
6
|
+
}
|
|
7
|
+
export interface DaytonaCodeRunResponse {
|
|
8
|
+
exitCode?: number | undefined;
|
|
9
|
+
result?: string | undefined;
|
|
10
|
+
artifacts?: DaytonaCodeRunArtifacts | undefined;
|
|
11
|
+
}
|
|
12
|
+
export interface DaytonaCodeRunParams {
|
|
13
|
+
argv?: Array<string> | undefined;
|
|
14
|
+
env?: Record<string, string> | undefined;
|
|
15
|
+
}
|
|
16
|
+
export interface DaytonaProcessLike {
|
|
17
|
+
codeRun: (code: string, params?: DaytonaCodeRunParams, timeoutSeconds?: number) => Promise<DaytonaCodeRunResponse>;
|
|
18
|
+
}
|
|
19
|
+
export interface DaytonaSandboxLike {
|
|
20
|
+
process: DaytonaProcessLike;
|
|
21
|
+
}
|
|
22
|
+
export interface ToolSchema {
|
|
23
|
+
name: string;
|
|
24
|
+
description: string;
|
|
25
|
+
inputSchema: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
export interface ToolCallRequest {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
args: unknown;
|
|
31
|
+
}
|
|
32
|
+
export type ToolResultPayload = {
|
|
33
|
+
success: true;
|
|
34
|
+
value?: unknown;
|
|
35
|
+
error?: never;
|
|
36
|
+
} | {
|
|
37
|
+
success: false;
|
|
38
|
+
error: string;
|
|
39
|
+
value?: never;
|
|
40
|
+
};
|
|
41
|
+
export interface DaytonaExecutionError {
|
|
42
|
+
name: string;
|
|
43
|
+
message: string;
|
|
44
|
+
stack?: string | undefined;
|
|
45
|
+
}
|
|
46
|
+
export type DaytonaExecutionEnvelope = {
|
|
47
|
+
status: 'done';
|
|
48
|
+
success: true;
|
|
49
|
+
value?: unknown;
|
|
50
|
+
error?: never;
|
|
51
|
+
logs: Array<string>;
|
|
52
|
+
} | {
|
|
53
|
+
status: 'done';
|
|
54
|
+
success: false;
|
|
55
|
+
error: DaytonaExecutionError;
|
|
56
|
+
value?: never;
|
|
57
|
+
logs: Array<string>;
|
|
58
|
+
} | {
|
|
59
|
+
status: 'need_tools';
|
|
60
|
+
toolCalls: Array<ToolCallRequest>;
|
|
61
|
+
logs: Array<string>;
|
|
62
|
+
} | {
|
|
63
|
+
status: 'error';
|
|
64
|
+
error: DaytonaExecutionError;
|
|
65
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { ToolResultPayload, ToolSchema } from './types.js';
|
|
2
|
+
export declare const DAYTONA_RESULT_MARKER = "__TANSTACK_AI_CODE_MODE_RESULT__";
|
|
3
|
+
export declare function generateToolWrappers(tools: Array<ToolSchema>): string;
|
|
4
|
+
export declare function wrapCode(code: string, tools: Array<ToolSchema>, toolResults?: Record<string, ToolResultPayload>, resultMarker?: string): string;
|