@dudko.dev/agent-web 0.0.37 → 0.0.38
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 +156 -4
- package/dist/agent-web.js +270 -110
- package/dist/agent-web.js.map +1 -1
- package/dist/chunk-AY2BZYZY.js +573 -0
- package/dist/chunk-AY2BZYZY.js.map +1 -0
- package/dist/chunk-CTXDKSDD.js +39 -0
- package/dist/chunk-CTXDKSDD.js.map +1 -0
- package/dist/{chunk-CPSDKXO6.js → chunk-T6LZW7ML.js} +27 -35
- package/dist/chunk-T6LZW7ML.js.map +1 -0
- package/dist/chunk-V3JOK7EW.js +929 -0
- package/dist/chunk-V3JOK7EW.js.map +1 -0
- package/dist/index.cjs +5980 -3627
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +363 -3
- package/dist/index.d.ts +363 -3
- package/dist/index.js +1183 -583
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +879 -13
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +372 -13
- package/dist/mcp.d.ts +372 -13
- package/dist/mcp.js +857 -15
- package/dist/mcp.js.map +1 -1
- package/dist/sandbox-AMO2SA4X.js +269 -0
- package/dist/sandbox-AMO2SA4X.js.map +1 -0
- package/dist/sandbox-worker.cjs +745 -0
- package/dist/sandbox-worker.cjs.map +1 -0
- package/dist/sandbox-worker.d.cts +37 -0
- package/dist/sandbox-worker.d.ts +37 -0
- package/dist/sandbox-worker.js +27 -0
- package/dist/sandbox-worker.js.map +1 -0
- package/package.json +23 -4
- package/dist/chunk-CPSDKXO6.js.map +0 -1
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import {
|
|
2
|
+
fileToolBindingOf,
|
|
3
|
+
isTextMime,
|
|
4
|
+
normalizePath,
|
|
5
|
+
toolRunContextOf
|
|
6
|
+
} from "./chunk-AY2BZYZY.js";
|
|
7
|
+
import "./chunk-CTXDKSDD.js";
|
|
8
|
+
import {
|
|
9
|
+
RUN_JS_TOOL,
|
|
10
|
+
SANDBOX_MAX_FILE_CHARS,
|
|
11
|
+
SANDBOX_MAX_MODULES,
|
|
12
|
+
SANDBOX_MAX_MODULE_CHARS_TOTAL,
|
|
13
|
+
SANDBOX_MODULE_EXTENSIONS,
|
|
14
|
+
SANDBOX_PACKAGE,
|
|
15
|
+
SANDBOX_PLANNER_NOTE,
|
|
16
|
+
SANDBOX_SYNTHESIZER_NOTE,
|
|
17
|
+
createSandboxQueue,
|
|
18
|
+
moduleSpecifiersOf,
|
|
19
|
+
resolveModulePath,
|
|
20
|
+
resolveSandboxLimits,
|
|
21
|
+
runGuest,
|
|
22
|
+
runInWorker,
|
|
23
|
+
sandboxPeerMissing,
|
|
24
|
+
sandboxPromptNote,
|
|
25
|
+
sanitizeSandboxResult
|
|
26
|
+
} from "./chunk-V3JOK7EW.js";
|
|
27
|
+
|
|
28
|
+
// src/sandbox/index.ts
|
|
29
|
+
import { jsonSchema, tool } from "ai";
|
|
30
|
+
|
|
31
|
+
// src/sandbox/files.ts
|
|
32
|
+
var sandboxFilesOf = (tools) => {
|
|
33
|
+
let files;
|
|
34
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
35
|
+
const binding = fileToolBindingOf(t);
|
|
36
|
+
if (!binding || binding.op === "delete") continue;
|
|
37
|
+
if (!files) files = { vfs: binding.vfs };
|
|
38
|
+
if (files.vfs !== binding.vfs) continue;
|
|
39
|
+
files[binding.op] ??= name;
|
|
40
|
+
}
|
|
41
|
+
return files && (files.read || files.write || files.list) ? files : void 0;
|
|
42
|
+
};
|
|
43
|
+
var sandboxHostOps = (files) => [
|
|
44
|
+
...files.read ? ["readFile"] : [],
|
|
45
|
+
...files.write ? ["writeFile"] : [],
|
|
46
|
+
...files.list ? ["readdir"] : []
|
|
47
|
+
];
|
|
48
|
+
var pathOf = (value, what) => {
|
|
49
|
+
if (typeof value !== "string" || !value) throw new Error(`${what}: a path (string) is required`);
|
|
50
|
+
return normalizePath(value);
|
|
51
|
+
};
|
|
52
|
+
var readWorkspaceText = async (files, path, approve, maxChars) => {
|
|
53
|
+
if (!files.read) throw new Error("reading files is not available in this sandbox");
|
|
54
|
+
await approve?.(files.read, { path }, true);
|
|
55
|
+
const f = await files.vfs.read(path);
|
|
56
|
+
if (!f) throw new Error(`no file "${path}"`);
|
|
57
|
+
if (f.encoding === "base64" && !isTextMime(f.mimeType)) {
|
|
58
|
+
throw new Error(`"${path}" is a binary file (${f.mimeType}) and cannot be read as text`);
|
|
59
|
+
}
|
|
60
|
+
const text = f.encoding === "base64" ? atob(f.content) : f.content;
|
|
61
|
+
if (text.length > maxChars) {
|
|
62
|
+
throw new Error(`"${path}" is ${text.length} characters; the sandbox reads at most ${maxChars}`);
|
|
63
|
+
}
|
|
64
|
+
return text;
|
|
65
|
+
};
|
|
66
|
+
var createFileHost = (files, approve) => async (op, args) => {
|
|
67
|
+
switch (op) {
|
|
68
|
+
case "readFile":
|
|
69
|
+
return readWorkspaceText(
|
|
70
|
+
files,
|
|
71
|
+
pathOf(args[0], "fs.readFile"),
|
|
72
|
+
approve,
|
|
73
|
+
SANDBOX_MAX_FILE_CHARS
|
|
74
|
+
);
|
|
75
|
+
case "writeFile": {
|
|
76
|
+
if (!files.write) throw new Error("writing files is not available in this sandbox");
|
|
77
|
+
const path = pathOf(args[0], "fs.writeFile");
|
|
78
|
+
const content = args[1];
|
|
79
|
+
if (typeof content !== "string")
|
|
80
|
+
throw new Error("fs.writeFile: the content must be a string");
|
|
81
|
+
if (content.length > SANDBOX_MAX_FILE_CHARS) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`fs.writeFile: ${content.length} characters; the sandbox writes at most ${SANDBOX_MAX_FILE_CHARS}`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
await approve?.(files.write, { path, content }, false);
|
|
87
|
+
await files.vfs.write(path, content);
|
|
88
|
+
return void 0;
|
|
89
|
+
}
|
|
90
|
+
case "readdir": {
|
|
91
|
+
if (!files.list) throw new Error("listing files is not available in this sandbox");
|
|
92
|
+
const prefix = args[0] === void 0 || args[0] === "/" ? "/" : pathOf(args[0], "fs.readdir");
|
|
93
|
+
await approve?.(files.list, { prefix }, true);
|
|
94
|
+
return (await files.vfs.list(prefix)).map((f) => f.path);
|
|
95
|
+
}
|
|
96
|
+
default:
|
|
97
|
+
throw new Error(`fs.${String(op).slice(0, 40)} is not available in this sandbox`);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var collectModules = async (files, code, filename, approve, maxModuleChars) => {
|
|
101
|
+
const modules = {};
|
|
102
|
+
if (!files.read) return modules;
|
|
103
|
+
const seen = /* @__PURE__ */ new Set();
|
|
104
|
+
const queue = [{ source: code, base: filename }];
|
|
105
|
+
let total = 0;
|
|
106
|
+
while (queue.length > 0) {
|
|
107
|
+
const { source, base } = queue.shift();
|
|
108
|
+
for (const spec of moduleSpecifiersOf(source)) {
|
|
109
|
+
let path;
|
|
110
|
+
try {
|
|
111
|
+
path = normalizePath(resolveModulePath(base, spec));
|
|
112
|
+
} catch {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (seen.has(path)) continue;
|
|
116
|
+
seen.add(path);
|
|
117
|
+
if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) continue;
|
|
118
|
+
if (seen.size > SANDBOX_MAX_MODULES) return modules;
|
|
119
|
+
let text;
|
|
120
|
+
try {
|
|
121
|
+
text = await readWorkspaceText(files, path, approve, maxModuleChars);
|
|
122
|
+
} catch {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (total + text.length > SANDBOX_MAX_MODULE_CHARS_TOTAL) continue;
|
|
126
|
+
total += text.length;
|
|
127
|
+
modules[path] = text;
|
|
128
|
+
if (!path.toLowerCase().endsWith(".json")) queue.push({ source: text, base: path });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return modules;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// src/sandbox/index.ts
|
|
135
|
+
var MAX_CONCURRENT_RUNS = 4;
|
|
136
|
+
var portOf = (worker) => ({
|
|
137
|
+
post: (message) => worker.postMessage(message),
|
|
138
|
+
listen: (onMessage, onClose) => {
|
|
139
|
+
worker.addEventListener("message", (ev) => onMessage(ev.data));
|
|
140
|
+
worker.addEventListener(
|
|
141
|
+
"error",
|
|
142
|
+
(ev) => onClose?.(ev?.message || "the worker failed")
|
|
143
|
+
);
|
|
144
|
+
worker.start?.();
|
|
145
|
+
},
|
|
146
|
+
terminate: () => worker.terminate?.()
|
|
147
|
+
});
|
|
148
|
+
var loadEngine = async (custom) => {
|
|
149
|
+
let lib;
|
|
150
|
+
try {
|
|
151
|
+
const pkg = SANDBOX_PACKAGE;
|
|
152
|
+
lib = custom ? await custom() : await import(
|
|
153
|
+
/* webpackIgnore: true */
|
|
154
|
+
/* @vite-ignore */
|
|
155
|
+
pkg
|
|
156
|
+
);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
throw sandboxPeerMissing(
|
|
159
|
+
custom ? err?.message : "in a bundled app pass sandbox.worker, or sandbox.engine: () => import('quickjs-emscripten')"
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
const l = lib;
|
|
163
|
+
if (typeof l?.newQuickJSWASMModuleFromVariant !== "function" || typeof l.newVariant !== "function") {
|
|
164
|
+
throw sandboxPeerMissing("what sandbox.engine returned is not the quickjs-emscripten module");
|
|
165
|
+
}
|
|
166
|
+
return l;
|
|
167
|
+
};
|
|
168
|
+
var describeTool = (limits, files) => `Run JavaScript in an isolated sandbox and get back what it printed (console.log) and the value of its last expression. Use it to actually execute code you wrote - a function on test data, a calculation, a parser on a sample - instead of predicting its output. Plain JavaScript on QuickJS (ES2023, top-level await, setTimeout): no Node or browser APIs, no network, no packages${files ? "" : ", no files"}. ` + (files ? "Workspace files: import or require them by relative path (.js, .mjs, .json), or use the async fs.readFile(path), fs.writeFile(path, text), fs.readdir(path). " : "") + `Limits: ${limits.timeoutMs} ms, ${Math.round(limits.memoryLimitBytes / (1024 * 1024))} MiB. A failing program returns { ok: false, error } with its stack: read it and fix the code.`;
|
|
169
|
+
var createSandbox = (config, mounted = {}, warn = () => {
|
|
170
|
+
}) => {
|
|
171
|
+
const limits = resolveSandboxLimits(config);
|
|
172
|
+
const files = config.files === false ? void 0 : sandboxFilesOf(mounted);
|
|
173
|
+
const queue = createSandboxQueue(MAX_CONCURRENT_RUNS);
|
|
174
|
+
if (!config.worker) {
|
|
175
|
+
warn(
|
|
176
|
+
"[sandbox] no sandbox.worker: run_js runs on the page thread (isolated, but a long native call in the guest blocks the page). Pass a worker factory."
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
const execute = async (input, options) => {
|
|
180
|
+
const agentRun = toolRunContextOf(options);
|
|
181
|
+
const approve = agentRun?.approve;
|
|
182
|
+
const signal = options?.abortSignal;
|
|
183
|
+
const hasCode = typeof input?.code === "string" && input.code.trim() !== "";
|
|
184
|
+
const hasEntry = typeof input?.entry === "string" && input.entry.trim() !== "";
|
|
185
|
+
if (hasEntry && !files?.read) {
|
|
186
|
+
throw new Error(`${RUN_JS_TOOL}: "entry" needs workspace files; pass the program as "code"`);
|
|
187
|
+
}
|
|
188
|
+
if (hasCode === hasEntry) {
|
|
189
|
+
throw new Error(
|
|
190
|
+
`${RUN_JS_TOOL}: pass ${files?.read ? 'either "code" or "entry" (a workspace file)' : '"code"'}`
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
let code = input.code;
|
|
194
|
+
let filename = "/main.js";
|
|
195
|
+
if (hasEntry && files) {
|
|
196
|
+
filename = normalizePath(input.entry);
|
|
197
|
+
if (!/\.(js|mjs)$/i.test(filename)) {
|
|
198
|
+
throw new Error(`${RUN_JS_TOOL}: "entry" must be a .js or .mjs file, got "${filename}"`);
|
|
199
|
+
}
|
|
200
|
+
code = await readWorkspaceText(files, filename, approve, limits.maxCodeChars);
|
|
201
|
+
}
|
|
202
|
+
if (code.length > limits.maxCodeChars) {
|
|
203
|
+
throw new Error(
|
|
204
|
+
`${RUN_JS_TOOL}: the code is ${code.length} characters; the limit is ${limits.maxCodeChars}`
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
const request = { code, filename, limits };
|
|
208
|
+
if (files) {
|
|
209
|
+
request.modules = await collectModules(files, code, filename, approve, limits.maxCodeChars);
|
|
210
|
+
request.hostOps = sandboxHostOps(files);
|
|
211
|
+
}
|
|
212
|
+
const hostCall = files ? createFileHost(files, approve) : void 0;
|
|
213
|
+
return queue(async () => {
|
|
214
|
+
let worker;
|
|
215
|
+
if (config.worker) {
|
|
216
|
+
try {
|
|
217
|
+
worker = config.worker();
|
|
218
|
+
} catch (err) {
|
|
219
|
+
warn(
|
|
220
|
+
`[sandbox] sandbox.worker failed (${err?.message ?? err}); running on the page thread`
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (worker) {
|
|
225
|
+
return runInWorker(portOf(worker), request, { hostCall, signal });
|
|
226
|
+
}
|
|
227
|
+
const startedAt = Date.now();
|
|
228
|
+
const lib = await loadEngine(config.engine);
|
|
229
|
+
const raw = await runGuest(lib, request, { hostCall });
|
|
230
|
+
return { ...sanitizeSandboxResult(raw, limits), durationMs: Date.now() - startedAt };
|
|
231
|
+
});
|
|
232
|
+
};
|
|
233
|
+
const withFiles = Boolean(files?.read);
|
|
234
|
+
const runJs = tool({
|
|
235
|
+
description: describeTool(limits, Boolean(files)),
|
|
236
|
+
inputSchema: jsonSchema({
|
|
237
|
+
type: "object",
|
|
238
|
+
properties: {
|
|
239
|
+
code: {
|
|
240
|
+
type: "string",
|
|
241
|
+
description: 'The program. Print with console.log; the value of the last expression is returned as "result".'
|
|
242
|
+
},
|
|
243
|
+
...withFiles ? {
|
|
244
|
+
entry: {
|
|
245
|
+
type: "string",
|
|
246
|
+
description: 'Instead of "code": the path of a workspace .js / .mjs file to run, e.g. "/main.js".'
|
|
247
|
+
}
|
|
248
|
+
} : {}
|
|
249
|
+
},
|
|
250
|
+
...withFiles ? {} : { required: ["code"] },
|
|
251
|
+
additionalProperties: false
|
|
252
|
+
}),
|
|
253
|
+
execute
|
|
254
|
+
});
|
|
255
|
+
return {
|
|
256
|
+
tools: { [RUN_JS_TOOL]: runJs },
|
|
257
|
+
notes: {
|
|
258
|
+
planner: SANDBOX_PLANNER_NOTE,
|
|
259
|
+
executor: sandboxPromptNote(Boolean(files)),
|
|
260
|
+
synthesizer: SANDBOX_SYNTHESIZER_NOTE
|
|
261
|
+
},
|
|
262
|
+
files: Boolean(files),
|
|
263
|
+
thread: config.worker ? "worker" : "page"
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
export {
|
|
267
|
+
createSandbox
|
|
268
|
+
};
|
|
269
|
+
//# sourceMappingURL=sandbox-AMO2SA4X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/index.ts","../src/sandbox/files.ts"],"sourcesContent":["import { jsonSchema, tool, type Tool, type ToolSet } from 'ai'\nimport { normalizePath } from '../files/vfs.js'\nimport { toolRunContextOf } from '../tools/wrap.js'\nimport {\n createSandboxQueue,\n resolveSandboxLimits,\n RUN_JS_TOOL,\n runGuest,\n runInWorker,\n SANDBOX_PACKAGE,\n SANDBOX_PLANNER_NOTE,\n SANDBOX_SYNTHESIZER_NOTE,\n sandboxPeerMissing,\n sandboxPromptNote,\n sanitizeSandboxResult,\n type ISandboxConfig,\n type ISandboxLib,\n type ISandboxPort,\n type ISandboxRequest,\n type ISandboxResult,\n} from './engine.js'\nimport {\n collectModules,\n createFileHost,\n readWorkspaceText,\n sandboxFilesOf,\n sandboxHostOps,\n type SandboxFiles,\n} from './files.js'\n\n/**\n * `config.sandbox`: the `run_js` tool - the model's code runs in QuickJS compiled to\n * WebAssembly (the optional peer `quickjs-emscripten`), never in the page's own JavaScript\n * engine. This module is loaded only when the sandbox is switched on.\n *\n * Where the guest runs:\n * - `worker` given: in a Web Worker that is terminated when the run is over or over time (the\n * hard stop). One worker per run. The worker module is `@dudko.dev/agent-web/sandbox-worker`.\n * - no `worker`: on the page's thread, stopped by the engine's interrupt handler only. A single\n * long native call in the guest then blocks the page until it returns - prefer a worker.\n */\n\n/** A worker as the sandbox uses it: a real `Worker`, or a `MessagePort` in tests. */\nexport interface SandboxWorkerLike {\n postMessage(message: unknown): void\n addEventListener(type: string, listener: (ev: any) => void): void\n terminate?(): void\n}\n\nexport interface SandboxConfig extends ISandboxConfig {\n /**\n * Builds a fresh Worker for one run, e.g.\n * `() => new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' })`\n * (Vite: `import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'`). Without it\n * the guest runs on the page's thread - isolated all the same, but only softly interruptible.\n */\n worker?: () => SandboxWorkerLike\n /**\n * Loads the engine for the page-thread fallback, e.g. `() => import('quickjs-emscripten')`, so\n * that your bundler resolves it. Default: a runtime `import('quickjs-emscripten')` (Node, or a\n * page with an import map). Not used when `worker` is given.\n */\n engine?: () => Promise<unknown>\n}\n\nexport interface Sandbox {\n tools: ToolSet\n /** The run-stable sentences the stage prompts carry while `run_js` is mounted. */\n notes: { planner: string; executor: string; synthesizer: string }\n /** Whether the guest is bound to the workspace (import / require / fs). */\n files: boolean\n /** Where the guest runs. */\n thread: 'worker' | 'page'\n}\n\nconst MAX_CONCURRENT_RUNS = 4\n\nconst portOf = (worker: SandboxWorkerLike): ISandboxPort => ({\n post: (message) => worker.postMessage(message),\n listen: (onMessage, onClose) => {\n worker.addEventListener('message', (ev: { data: unknown }) => onMessage(ev.data))\n worker.addEventListener('error', (ev: { message?: string }) =>\n onClose?.(ev?.message || 'the worker failed'),\n )\n // A MessagePort (tests) delivers nothing until it is started; a Worker has no start().\n ;(worker as { start?: () => void }).start?.()\n },\n terminate: () => worker.terminate?.(),\n})\n\nconst loadEngine = async (custom: (() => Promise<unknown>) | undefined): Promise<ISandboxLib> => {\n let lib: unknown\n try {\n // A variable specifier plus the two bundler comments: the optional peer is left to the\n // runtime, so a host that never switches the sandbox on builds without it installed.\n const pkg = SANDBOX_PACKAGE\n lib = custom ? await custom() : await import(/* webpackIgnore: true */ /* @vite-ignore */ pkg)\n } catch (err) {\n throw sandboxPeerMissing(\n custom\n ? (err as Error)?.message\n : \"in a bundled app pass sandbox.worker, or sandbox.engine: () => import('quickjs-emscripten')\",\n )\n }\n const l = lib as Partial<ISandboxLib> | undefined\n if (\n typeof l?.newQuickJSWASMModuleFromVariant !== 'function' ||\n typeof l.newVariant !== 'function'\n ) {\n throw sandboxPeerMissing('what sandbox.engine returned is not the quickjs-emscripten module')\n }\n return l as ISandboxLib\n}\n\ninterface RunJsInput {\n code?: string\n entry?: string\n}\n\nconst describeTool = (limits: { timeoutMs: number; memoryLimitBytes: number }, files: boolean) =>\n 'Run JavaScript in an isolated sandbox and get back what it printed (console.log) and the value of its last expression. ' +\n 'Use it to actually execute code you wrote - a function on test data, a calculation, a parser on a sample - instead of predicting its output. ' +\n `Plain JavaScript on QuickJS (ES2023, top-level await, setTimeout): no Node or browser APIs, no network, no packages${files ? '' : ', no files'}. ` +\n (files\n ? 'Workspace files: import or require them by relative path (.js, .mjs, .json), or use the async fs.readFile(path), fs.writeFile(path, text), fs.readdir(path). '\n : '') +\n `Limits: ${limits.timeoutMs} ms, ${Math.round(limits.memoryLimitBytes / (1024 * 1024))} MiB. ` +\n 'A failing program returns { ok: false, error } with its stack: read it and fix the code.'\n\n/**\n * Build the sandbox for one agent. `mounted` are the agent's tools after its allow / exclude\n * filters: file tools among them (from `createFileTools`) are what binds the guest to the\n * workspace, unless `files: false`.\n */\nexport const createSandbox = (\n config: SandboxConfig,\n mounted: ToolSet = {},\n warn: (message: string) => void = () => {},\n): Sandbox => {\n const limits = resolveSandboxLimits(config)\n const files: SandboxFiles | undefined =\n config.files === false ? undefined : sandboxFilesOf(mounted)\n const queue = createSandboxQueue(MAX_CONCURRENT_RUNS)\n if (!config.worker) {\n warn(\n '[sandbox] no sandbox.worker: run_js runs on the page thread (isolated, but a long native call in the guest blocks the page). Pass a worker factory.',\n )\n }\n\n const execute = async (input: RunJsInput, options: unknown): Promise<ISandboxResult> => {\n const agentRun = toolRunContextOf(options)\n const approve = agentRun?.approve\n const signal = (options as { abortSignal?: AbortSignal } | undefined)?.abortSignal\n const hasCode = typeof input?.code === 'string' && input.code.trim() !== ''\n const hasEntry = typeof input?.entry === 'string' && input.entry.trim() !== ''\n if (hasEntry && !files?.read) {\n throw new Error(`${RUN_JS_TOOL}: \"entry\" needs workspace files; pass the program as \"code\"`)\n }\n if (hasCode === hasEntry) {\n throw new Error(\n `${RUN_JS_TOOL}: pass ${files?.read ? 'either \"code\" or \"entry\" (a workspace file)' : '\"code\"'}`,\n )\n }\n let code = input.code as string\n let filename = '/main.js'\n if (hasEntry && files) {\n filename = normalizePath(input.entry as string)\n if (!/\\.(js|mjs)$/i.test(filename)) {\n throw new Error(`${RUN_JS_TOOL}: \"entry\" must be a .js or .mjs file, got \"${filename}\"`)\n }\n code = await readWorkspaceText(files, filename, approve, limits.maxCodeChars)\n }\n if (code.length > limits.maxCodeChars) {\n throw new Error(\n `${RUN_JS_TOOL}: the code is ${code.length} characters; the limit is ${limits.maxCodeChars}`,\n )\n }\n const request: ISandboxRequest = { code, filename, limits }\n if (files) {\n request.modules = await collectModules(files, code, filename, approve, limits.maxCodeChars)\n request.hostOps = sandboxHostOps(files)\n }\n const hostCall = files ? createFileHost(files, approve) : undefined\n return queue(async () => {\n let worker: SandboxWorkerLike | undefined\n if (config.worker) {\n try {\n worker = config.worker()\n } catch (err) {\n // No Worker here (an old or locked-down environment): the page thread still isolates.\n warn(\n `[sandbox] sandbox.worker failed (${(err as Error)?.message ?? err}); running on the page thread`,\n )\n }\n }\n if (worker) {\n return runInWorker(portOf(worker), request, { hostCall, signal })\n }\n const startedAt = Date.now()\n const lib = await loadEngine(config.engine)\n const raw = await runGuest(lib, request, { hostCall })\n return { ...sanitizeSandboxResult(raw, limits), durationMs: Date.now() - startedAt }\n })\n }\n\n const withFiles = Boolean(files?.read)\n const runJs: Tool = tool({\n description: describeTool(limits, Boolean(files)),\n inputSchema: jsonSchema<RunJsInput>({\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description:\n 'The program. Print with console.log; the value of the last expression is returned as \"result\".',\n },\n ...(withFiles\n ? {\n entry: {\n type: 'string',\n description:\n 'Instead of \"code\": the path of a workspace .js / .mjs file to run, e.g. \"/main.js\".',\n },\n }\n : {}),\n },\n ...(withFiles ? {} : { required: ['code'] }),\n additionalProperties: false,\n }),\n execute,\n })\n return {\n tools: { [RUN_JS_TOOL]: runJs },\n notes: {\n planner: SANDBOX_PLANNER_NOTE,\n executor: sandboxPromptNote(Boolean(files)),\n synthesizer: SANDBOX_SYNTHESIZER_NOTE,\n },\n files: Boolean(files),\n thread: config.worker ? 'worker' : 'page',\n }\n}\n","import type { ToolSet } from 'ai'\nimport { fileToolBindingOf } from '../files/tools.js'\nimport { isTextMime, normalizePath, type VirtualFileSystem } from '../files/vfs.js'\nimport {\n moduleSpecifiersOf,\n resolveModulePath,\n SANDBOX_MAX_FILE_CHARS,\n SANDBOX_MAX_MODULE_CHARS_TOTAL,\n SANDBOX_MAX_MODULES,\n SANDBOX_MODULE_EXTENSIONS,\n type SandboxHostCall,\n type SandboxHostOp,\n} from './engine.js'\n\n/**\n * The workspace a sandbox is bound to: the virtual file system the agent's own file tools work\n * on, and - per operation - the NAME of the tool that grants it. The guest gets an operation\n * only when the agent has the tool for it (a read-only mount gives no `writeFile`), and every\n * call passes the consent gate under that tool's name, so a rule that denies `fs_write` denies\n * the guest's writes too.\n */\nexport interface SandboxFiles {\n vfs: VirtualFileSystem\n read?: string\n write?: string\n list?: string\n}\n\n/** The agent's consent gate, as a tool reaches it (`ToolRunContext.approve`). */\nexport type SandboxApprove = (toolName: string, input: unknown, readOnly: boolean) => Promise<void>\n\n/** Find the file tools among the mounted tools (the first file system that can be read wins). */\nexport const sandboxFilesOf = (tools: ToolSet): SandboxFiles | undefined => {\n let files: SandboxFiles | undefined\n for (const [name, t] of Object.entries(tools)) {\n const binding = fileToolBindingOf(t)\n if (!binding || binding.op === 'delete') continue\n if (!files) files = { vfs: binding.vfs }\n if (files.vfs !== binding.vfs) continue\n files[binding.op] ??= name\n }\n return files && (files.read || files.write || files.list) ? files : undefined\n}\n\nexport const sandboxHostOps = (files: SandboxFiles): SandboxHostOp[] => [\n ...(files.read ? (['readFile'] as const) : []),\n ...(files.write ? (['writeFile'] as const) : []),\n ...(files.list ? (['readdir'] as const) : []),\n]\n\nconst pathOf = (value: unknown, what: string): string => {\n if (typeof value !== 'string' || !value) throw new Error(`${what}: a path (string) is required`)\n // Throws on a path that climbs out of the root; there is nothing above it to reach.\n return normalizePath(value)\n}\n\n/** Read one workspace file as text, under the same rules as `fs_read` plus a size cap. */\nexport const readWorkspaceText = async (\n files: SandboxFiles,\n path: string,\n approve: SandboxApprove | undefined,\n maxChars: number,\n): Promise<string> => {\n if (!files.read) throw new Error('reading files is not available in this sandbox')\n await approve?.(files.read, { path }, true)\n const f = await files.vfs.read(path)\n if (!f) throw new Error(`no file \"${path}\"`)\n if (f.encoding === 'base64' && !isTextMime(f.mimeType)) {\n throw new Error(`\"${path}\" is a binary file (${f.mimeType}) and cannot be read as text`)\n }\n const text = f.encoding === 'base64' ? atob(f.content) : f.content\n if (text.length > maxChars) {\n throw new Error(`\"${path}\" is ${text.length} characters; the sandbox reads at most ${maxChars}`)\n }\n return text\n}\n\n/** Serves the guest's `fs` calls on the agent's side of the boundary. */\nexport const createFileHost =\n (files: SandboxFiles, approve: SandboxApprove | undefined): SandboxHostCall =>\n async (op, args) => {\n switch (op) {\n case 'readFile':\n return readWorkspaceText(\n files,\n pathOf(args[0], 'fs.readFile'),\n approve,\n SANDBOX_MAX_FILE_CHARS,\n )\n case 'writeFile': {\n if (!files.write) throw new Error('writing files is not available in this sandbox')\n const path = pathOf(args[0], 'fs.writeFile')\n const content = args[1]\n if (typeof content !== 'string')\n throw new Error('fs.writeFile: the content must be a string')\n if (content.length > SANDBOX_MAX_FILE_CHARS) {\n throw new Error(\n `fs.writeFile: ${content.length} characters; the sandbox writes at most ${SANDBOX_MAX_FILE_CHARS}`,\n )\n }\n await approve?.(files.write, { path, content }, false)\n await files.vfs.write(path, content)\n return undefined\n }\n case 'readdir': {\n if (!files.list) throw new Error('listing files is not available in this sandbox')\n const prefix =\n args[0] === undefined || args[0] === '/' ? '/' : pathOf(args[0], 'fs.readdir')\n await approve?.(files.list, { prefix }, true)\n return (await files.vfs.list(prefix)).map((f) => f.path)\n }\n default:\n throw new Error(`fs.${String(op).slice(0, 40)} is not available in this sandbox`)\n }\n }\n\n/**\n * The workspace modules a program refers to, by literal path, followed through their own\n * imports: what the guest's loader will be able to load. A file that is missing, too large, of\n * another kind, or outside the root is simply not handed over - the guest's `import` of it then\n * fails with the reason. Bounded in count and total size.\n */\nexport const collectModules = async (\n files: SandboxFiles,\n code: string,\n filename: string,\n approve: SandboxApprove | undefined,\n maxModuleChars: number,\n): Promise<Record<string, string>> => {\n const modules: Record<string, string> = {}\n if (!files.read) return modules\n const seen = new Set<string>()\n const queue: { source: string; base: string }[] = [{ source: code, base: filename }]\n let total = 0\n while (queue.length > 0) {\n const { source, base } = queue.shift() as { source: string; base: string }\n for (const spec of moduleSpecifiersOf(source)) {\n let path: string\n try {\n path = normalizePath(resolveModulePath(base, spec))\n } catch {\n continue\n }\n if (seen.has(path)) continue\n seen.add(path)\n if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) continue\n if (seen.size > SANDBOX_MAX_MODULES) return modules\n let text: string\n try {\n text = await readWorkspaceText(files, path, approve, maxModuleChars)\n } catch {\n continue\n }\n if (total + text.length > SANDBOX_MAX_MODULE_CHARS_TOTAL) continue\n total += text.length\n modules[path] = text\n if (!path.toLowerCase().endsWith('.json')) queue.push({ source: text, base: path })\n }\n }\n return modules\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,YAAq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