@dudko.dev/agent-web 0.0.40 → 0.0.41
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 +301 -22
- package/dist/agent-web.js +169 -161
- package/dist/agent-web.js.map +1 -1
- package/dist/chunk-4FBTBE74.js +510 -0
- package/dist/chunk-4FBTBE74.js.map +1 -0
- package/dist/{chunk-TZITKUFW.js → chunk-L7Y3QRAM.js} +152 -20
- package/dist/chunk-L7Y3QRAM.js.map +1 -0
- package/dist/{chunk-V3JOK7EW.js → chunk-YPCHD6DV.js} +4 -2
- package/dist/chunk-YPCHD6DV.js.map +1 -0
- package/dist/chunk-YUA2BHRM.js +584 -0
- package/dist/chunk-YUA2BHRM.js.map +1 -0
- package/dist/elicitation-BA1knkdA.d.cts +566 -0
- package/dist/elicitation-BA1knkdA.d.ts +566 -0
- package/dist/index.cjs +1813 -221
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +690 -117
- package/dist/index.d.ts +690 -117
- package/dist/index.js +1275 -185
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +2135 -49
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +285 -9
- package/dist/mcp.d.ts +285 -9
- package/dist/mcp.js +1573 -48
- package/dist/mcp.js.map +1 -1
- package/dist/{sandbox-KG6OUG24.js → sandbox-ZDQIIZS7.js} +21 -8
- package/dist/sandbox-ZDQIIZS7.js.map +1 -0
- package/dist/sandbox-worker.cjs +3 -1
- package/dist/sandbox-worker.cjs.map +1 -1
- package/dist/sandbox-worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-A6ZJALLU.js +0 -254
- package/dist/chunk-A6ZJALLU.js.map +0 -1
- package/dist/chunk-CTXDKSDD.js +0 -39
- package/dist/chunk-CTXDKSDD.js.map +0 -1
- package/dist/chunk-TZITKUFW.js.map +0 -1
- package/dist/chunk-V3JOK7EW.js.map +0 -1
- package/dist/sandbox-KG6OUG24.js.map +0 -1
- package/dist/vault-BatBaRQP.d.cts +0 -36
- package/dist/vault-BatBaRQP.d.ts +0 -36
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
fileToolBindingOf,
|
|
3
3
|
isTextMime,
|
|
4
|
+
markCodeExecution,
|
|
4
5
|
normalizePath,
|
|
5
6
|
toolRunContextOf
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
7
|
+
} from "./chunk-L7Y3QRAM.js";
|
|
8
|
+
import "./chunk-YUA2BHRM.js";
|
|
8
9
|
import {
|
|
9
10
|
RUN_JS_TOOL,
|
|
10
11
|
SANDBOX_MAX_FILE_CHARS,
|
|
@@ -23,7 +24,7 @@ import {
|
|
|
23
24
|
sandboxPeerMissing,
|
|
24
25
|
sandboxPromptNote,
|
|
25
26
|
sanitizeSandboxResult
|
|
26
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-YPCHD6DV.js";
|
|
27
28
|
|
|
28
29
|
// src/sandbox/index.ts
|
|
29
30
|
import { jsonSchema, tool } from "ai";
|
|
@@ -63,7 +64,7 @@ var readWorkspaceText = async (files, path, approve, maxChars) => {
|
|
|
63
64
|
}
|
|
64
65
|
return text;
|
|
65
66
|
};
|
|
66
|
-
var createFileHost = (files, approve) => async (op, args) => {
|
|
67
|
+
var createFileHost = (files, approve, onWrite) => async (op, args) => {
|
|
67
68
|
switch (op) {
|
|
68
69
|
case "readFile":
|
|
69
70
|
return readWorkspaceText(
|
|
@@ -84,7 +85,8 @@ var createFileHost = (files, approve) => async (op, args) => {
|
|
|
84
85
|
);
|
|
85
86
|
}
|
|
86
87
|
await approve?.(files.write, { path, content }, false);
|
|
87
|
-
await files.vfs.write(path, content);
|
|
88
|
+
const info = await files.vfs.write(path, content);
|
|
89
|
+
onWrite?.(info);
|
|
88
90
|
return void 0;
|
|
89
91
|
}
|
|
90
92
|
case "readdir": {
|
|
@@ -209,7 +211,17 @@ var createSandbox = (config, mounted = {}, warn = () => {
|
|
|
209
211
|
request.modules = await collectModules(files, code, filename, approve, limits.maxCodeChars);
|
|
210
212
|
request.hostOps = sandboxHostOps(files);
|
|
211
213
|
}
|
|
212
|
-
const hostCall = files ? createFileHost(
|
|
214
|
+
const hostCall = files ? createFileHost(
|
|
215
|
+
files,
|
|
216
|
+
approve,
|
|
217
|
+
(file) => agentRun?.emit({
|
|
218
|
+
type: "file.written",
|
|
219
|
+
path: file.path,
|
|
220
|
+
mediaType: file.mimeType,
|
|
221
|
+
bytes: file.size,
|
|
222
|
+
...agentRun.step ? { step: agentRun.step } : {}
|
|
223
|
+
})
|
|
224
|
+
) : void 0;
|
|
213
225
|
return queue(async () => {
|
|
214
226
|
let worker;
|
|
215
227
|
if (config.worker) {
|
|
@@ -253,7 +265,8 @@ var createSandbox = (config, mounted = {}, warn = () => {
|
|
|
253
265
|
execute
|
|
254
266
|
});
|
|
255
267
|
return {
|
|
256
|
-
|
|
268
|
+
// It runs code: asked whenever the run acts on an MCP server's skill (tools/approval.ts).
|
|
269
|
+
tools: { [RUN_JS_TOOL]: markCodeExecution(runJs) },
|
|
257
270
|
notes: {
|
|
258
271
|
planner: SANDBOX_PLANNER_NOTE,
|
|
259
272
|
executor: sandboxPromptNote(Boolean(files)),
|
|
@@ -266,4 +279,4 @@ var createSandbox = (config, mounted = {}, warn = () => {
|
|
|
266
279
|
export {
|
|
267
280
|
createSandbox
|
|
268
281
|
};
|
|
269
|
-
//# sourceMappingURL=sandbox-
|
|
282
|
+
//# sourceMappingURL=sandbox-ZDQIIZS7.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 { markCodeExecution } from '../tools/approval.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\n ? createFileHost(files, approve, (file) =>\n agentRun?.emit({\n type: 'file.written',\n path: file.path,\n mediaType: file.mimeType,\n bytes: file.size,\n ...(agentRun.step ? { step: agentRun.step } : {}),\n }),\n )\n : 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 // It runs code: asked whenever the run acts on an MCP server's skill (tools/approval.ts).\n tools: { [RUN_JS_TOOL]: markCodeExecution(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 {\n isTextMime,\n normalizePath,\n type VirtualFileInfo,\n type VirtualFileSystem,\n} 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 (\n files: SandboxFiles,\n approve: SandboxApprove | undefined,\n /** Told about every file the guest wrote, after the write succeeded (the run's `file.written`). */\n onWrite?: (file: VirtualFileInfo) => void,\n ): 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 const info = await files.vfs.write(path, content)\n onWrite?.(info)\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,YAAqC;;;ACqCnD,IAAM,iBAAiB,CAAC,UAA6C;AAC1E,MAAI;AACJ,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC7C,UAAM,UAAU,kBAAkB,CAAC;AACnC,QAAI,CAAC,WAAW,QAAQ,OAAO,SAAU;AACzC,QAAI,CAAC,MAAO,SAAQ,EAAE,KAAK,QAAQ,IAAI;AACvC,QAAI,MAAM,QAAQ,QAAQ,IAAK;AAC/B,UAAM,QAAQ,EAAE,MAAM;AAAA,EACxB;AACA,SAAO,UAAU,MAAM,QAAQ,MAAM,SAAS,MAAM,QAAQ,QAAQ;AACtE;AAEO,IAAM,iBAAiB,CAAC,UAAyC;AAAA,EACtE,GAA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,QAAQ,KAAK,CAAC;AAAA,IAChD,aAAa,WAAuB;AAAA,MAClC,MAAM;AAAA,MACN,YAAY;AAAA,QACV,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,aACE;AAAA,QACJ;AAAA,QACA,GAAI,YACA;AAAA,UACE,OAAO;AAAA,YACL,MAAM;AAAA,YACN,aACE;AAAA,UACJ;AAAA,QACF,IACA,CAAC;AAAA,MACP;AAAA,MACA,GAAI,YAAY,CAAC,IAAI,EAAE,UAAU,CAAC,MAAM,EAAE;AAAA,MAC1C,sBAAsB;AAAA,IACxB,CAAC;AAAA,IACD;AAAA,EACF,CAAC;AACD,SAAO;AAAA;AAAA,IAEL,OAAO,EAAE,CAAC,WAAW,GAAG,kBAAkB,KAAK,EAAE;AAAA,IACjD,OAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,kBAAkB,QAAQ,KAAK,CAAC;AAAA,MAC1C,aAAa;AAAA,IACf;AAAA,IACA,OAAO,QAAQ,KAAK;AAAA,IACpB,QAAQ,OAAO,SAAS,WAAW;AAAA,EACrC;AACF;","names":[]}
|
package/dist/sandbox-worker.cjs
CHANGED
|
@@ -266,6 +266,7 @@ var runGuest = async (lib, request, options = {}) => {
|
|
|
266
266
|
const ctx = rt.newContext();
|
|
267
267
|
return new Promise((resolve) => {
|
|
268
268
|
const startedAt = Date.now();
|
|
269
|
+
let programAt = 0;
|
|
269
270
|
let finished = false;
|
|
270
271
|
let interrupted = false;
|
|
271
272
|
let cpuMs = 0;
|
|
@@ -283,7 +284,7 @@ var runGuest = async (lib, request, options = {}) => {
|
|
|
283
284
|
let main;
|
|
284
285
|
let mainKind = "value";
|
|
285
286
|
const cpuUsed = () => cpuMs + (entryAt ? Date.now() - entryAt : 0);
|
|
286
|
-
const wallUsed = () => Date.now() -
|
|
287
|
+
const wallUsed = () => programAt === 0 ? 0 : Date.now() - programAt - waitMs - (waitingSince ? Date.now() - waitingSince : 0);
|
|
287
288
|
const overTime = () => cpuUsed() > limits.timeoutMs || pendingCalls === 0 && wallUsed() > limits.timeoutMs;
|
|
288
289
|
rt.setInterruptHandler(() => {
|
|
289
290
|
if (finished || overTime()) {
|
|
@@ -657,6 +658,7 @@ var runGuest = async (lib, request, options = {}) => {
|
|
|
657
658
|
engineFailure(err);
|
|
658
659
|
return;
|
|
659
660
|
}
|
|
661
|
+
programAt = Date.now();
|
|
660
662
|
options.onStart?.();
|
|
661
663
|
armWatchdog();
|
|
662
664
|
enter(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sandbox/worker.ts","../src/sandbox/engine.ts"],"sourcesContent":["import { serveSandbox, type ISandboxLib } from './engine.js'\n\n/**\n * The Web Worker side of the sandbox (`config.sandbox.worker`): the entry\n * `@dudko.dev/agent-web/sandbox-worker`. Loaded as a worker it serves by itself:\n *\n * ```ts\n * // Vite\n * import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'\n * createAgent({ model, sandbox: { worker: () => new SandboxWorker() } })\n * // webpack 5 and other bundlers that follow `new URL(..., import.meta.url)`\n * createAgent({\n * model,\n * sandbox: {\n * worker: () =>\n * new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' }),\n * },\n * })\n * ```\n *\n * One worker serves one run and is terminated by the agent. The engine (the optional peer\n * `quickjs-emscripten`) is imported here with a literal specifier, so the host's bundler puts\n * it - and its .wasm file - into the worker's chunk and nowhere else.\n */\n\n/** The slice of a worker scope / MessagePort this needs. */\nexport interface SandboxWorkerScope {\n postMessage(message: unknown): void\n addEventListener(type: string, listener: (ev: any) => void): void\n}\n\nexport interface ServeSandboxOptions {\n /** The message endpoint (default: the worker global scope). */\n scope?: SandboxWorkerScope\n /** Load the engine yourself (default: `import('quickjs-emscripten')`). */\n engine?: () => Promise<unknown>\n}\n\nexport const serveSandboxWorker = (opts: ServeSandboxOptions = {}): void => {\n const scope = opts.scope ?? (globalThis as unknown as SandboxWorkerScope)\n serveSandbox(\n {\n post: (message) => scope.postMessage(message),\n listen: (onMessage) => {\n scope.addEventListener('message', (ev: { data: unknown }) => onMessage(ev.data))\n ;(scope as { start?: () => void }).start?.()\n },\n },\n async () =>\n (await (opts.engine\n ? opts.engine()\n : import('quickjs-emscripten'))) as unknown as ISandboxLib,\n )\n}\n\nconst inWorker = (): boolean => {\n const g = globalThis as {\n WorkerGlobalScope?: unknown\n importScripts?: unknown\n document?: unknown\n }\n return typeof g.WorkerGlobalScope !== 'undefined' && typeof g.document === 'undefined'\n}\n\nif (inWorker()) serveSandboxWorker()\n","// The JavaScript sandbox behind `config.sandbox` / the `run_js` tool: the guest runs in QuickJS\n// compiled to WebAssembly (the optional peer `quickjs-emscripten`), never in the host's own\n// JavaScript engine. This file is the part both packages share - limits, the guest's runtime,\n// the module resolver, the worker protocol and what is allowed back across the boundary.\n//\n// It is pure (no imports, no node:* and no DOM) and is a COPY, byte for byte, of the sibling\n// package's file: `packages/agent/src/sandbox-engine.ts` = `packages/agent-web/src/sandbox/engine.ts`.\n// Change both; the Node package's `tests/sandbox-engine.test.ts` compares them.\n//\n// Security boundary. What the guest can reach is exactly what `bootstrap` hands it: console,\n// timers, and - only when the host passes them - a module map and named file operations. Every\n// value that crosses is a string produced inside the guest and re-parsed here, never a host\n// reference. Every guard has a test and a mutation check (see the two packages' sandbox tests).\n\nexport const RUN_JS_TOOL = 'run_js'\nexport const SANDBOX_PACKAGE = 'quickjs-emscripten'\n\nexport interface ISandboxConfig {\n // Time one run may take, in ms (default 5000, at most 60000). Waiting for a file operation -\n // a consent prompt included - does not count.\n timeoutMs?: number\n // The guest's memory, in bytes: the whole WebAssembly memory of its engine instance, the\n // engine's own 16 MiB included (default 32 MiB, at least 16 MiB, at most 256 MiB).\n memoryLimitBytes?: number\n // What a run returns to the model, stdout and result together, in characters (default 8000).\n maxOutputChars?: number\n // The longest program accepted, in characters (default 100000).\n maxCodeChars?: number\n // Let the guest import / require workspace files and use `fs` (default true where the agent\n // has a workspace; without one there is nothing to bind and this is ignored).\n files?: boolean\n}\n\nexport interface ISandboxLimits {\n timeoutMs: number\n memoryLimitBytes: number\n maxOutputChars: number\n maxCodeChars: number\n}\n\nconst MIB = 1024 * 1024\n\nexport const SANDBOX_DEFAULTS: ISandboxLimits = {\n timeoutMs: 5000,\n memoryLimitBytes: 32 * MIB,\n maxOutputChars: 8000,\n maxCodeChars: 100_000,\n}\n\n// A host cannot configure past these: the tool is for checking a piece of code, not for hosting one.\nexport const SANDBOX_CAPS: ISandboxLimits = {\n timeoutMs: 60_000,\n memoryLimitBytes: 256 * MIB,\n maxOutputChars: 100_000,\n maxCodeChars: 1_000_000,\n}\n\nconst SANDBOX_FLOORS: ISandboxLimits = {\n timeoutMs: 50,\n // What the engine's WebAssembly module asks for before it runs anything.\n memoryLimitBytes: 16 * MIB,\n maxOutputChars: 200,\n maxCodeChars: 100,\n}\n\n// One module the guest may load, and all of them together (characters).\nexport const SANDBOX_MAX_MODULES = 64\nexport const SANDBOX_MAX_MODULE_CHARS_TOTAL = 2_000_000\n// A file the guest reads or writes through `fs` (characters), and the calls of one run.\nexport const SANDBOX_MAX_FILE_CHARS = 1_000_000\nexport const SANDBOX_MAX_HOST_CALLS = 500\nexport const SANDBOX_MODULE_EXTENSIONS: readonly string[] = ['.js', '.mjs', '.json']\n\nconst MAX_TIMERS = 1000\n// QuickJS's own stack check. Small on purpose: wasm frames live on the host thread's native\n// stack, and a deeper guest recursion would overflow THAT before QuickJS noticed.\nconst GUEST_STACK_BYTES = 256 * 1024\nconst ERROR_NAME_CHARS = 200\nconst ERROR_TEXT_CHARS = 4000\n\nconst bounded = (value: unknown, key: keyof ISandboxLimits): number => {\n const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : NaN\n if (Number.isNaN(n) || n <= 0) {\n return SANDBOX_DEFAULTS[key]\n }\n return Math.min(SANDBOX_CAPS[key], Math.max(SANDBOX_FLOORS[key], n))\n}\n\nexport const resolveSandboxLimits = (config: ISandboxConfig | undefined): ISandboxLimits => ({\n timeoutMs: bounded(config?.timeoutMs, 'timeoutMs'),\n memoryLimitBytes: bounded(config?.memoryLimitBytes, 'memoryLimitBytes'),\n maxOutputChars: bounded(config?.maxOutputChars, 'maxOutputChars'),\n maxCodeChars: bounded(config?.maxCodeChars, 'maxCodeChars'),\n})\n\nexport interface ISandboxError {\n name: string\n message: string\n // Guest frames only: the host's own frames never cross.\n stack?: string\n}\n\n// What `run_js` returns to the model.\nexport interface ISandboxResult {\n ok: boolean\n // console.log / info / warn / error, in the order they were called.\n stdout: string\n // The value of the last expression (a module's default export), as JSON-like data.\n result?: unknown\n error?: ISandboxError\n // stdout or result was cut to fit `maxOutputChars`.\n truncated: boolean\n durationMs: number\n}\n\nexport type SandboxHostOp = 'readFile' | 'writeFile' | 'readdir'\n\n// One run, as it is posted to the engine. Structured-cloneable.\nexport interface ISandboxRequest {\n code: string\n // The path the code is evaluated as (stack traces, the base of relative imports).\n filename?: string\n limits: ISandboxLimits\n // Workspace files the guest may `import` / `require`, by absolute path. Absent = no loader.\n modules?: Record<string, string>\n // The `fs` functions the host serves. Absent or empty = no `fs`.\n hostOps?: SandboxHostOp[]\n}\n\n// Serves one `fs` call of the guest. Arguments and the answer are JSON-like data.\nexport type SandboxHostCall = (op: string, args: unknown[]) => Promise<unknown>\n\nexport class SandboxUnavailableError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SandboxUnavailableError'\n }\n}\n\nexport const sandboxPeerMissing = (detail?: string): SandboxUnavailableError =>\n new SandboxUnavailableError(\n `The sandbox (${RUN_JS_TOOL}) needs the optional package \"${SANDBOX_PACKAGE}\", which is not installed. ` +\n `Add it to your app: npm install ${SANDBOX_PACKAGE}${detail ? ` (${detail})` : ''}`,\n )\n\n// The run-stable sentences the stage prompts carry when the sandbox is on (both packages say the same).\nexport const sandboxPromptNote = (files: boolean): string =>\n `${RUN_JS_TOOL} runs JavaScript you wrote in an isolated sandbox and returns what it printed (console.log) and the value of its last expression. ` +\n `It is plain JavaScript on QuickJS (ES2023, top-level await), not Node and not a browser: no network, no npm packages, no process${\n files\n ? '; workspace files are reachable by relative path (import / require of .js, .mjs, .json) and through the async fs.readFile / fs.writeFile / fs.readdir'\n : ', no files'\n }. ` +\n `Never say that code was run, tested or printed something unless ${RUN_JS_TOOL} was called and returned it: quote its real output, and if it was not run, say so.`\n\nexport const SANDBOX_PLANNER_NOTE = `When the request needs code to be run, tested or checked on data, or a calculation that is easier to compute than to reason about, plan a step that calls ${RUN_JS_TOOL} for it.`\n\nexport const SANDBOX_SYNTHESIZER_NOTE = `Report the output of running code only when a ${RUN_JS_TOOL} call returned it; if the code was written but not run, say it was not run.`\n\nconst clip = (text: string, max: number): string => (text.length > max ? text.slice(0, max) : text)\n\nconst errorText = (err: unknown): string => {\n if (err instanceof Error) {\n return `${err.name}: ${err.message}`\n }\n return typeof err === 'string' ? err : 'unknown error'\n}\n\nconst dirname = (path: string): string => {\n const i = path.lastIndexOf('/')\n return i <= 0 ? '/' : path.slice(0, i)\n}\n\n// Resolve what the guest asked to load against the file that asked. Throws (with a message for\n// the model) on anything that is not a workspace file by path: a package, a Node built-in, a\n// path that climbs out of the root, an extension outside the allowed three.\nexport const resolveModulePath = (base: string, specifier: string): string => {\n const spec = String(specifier)\n if (!/^(\\.{1,2}\\/|\\/)/.test(spec) || /[\\\\\\0]/.test(spec)) {\n throw new Error(\n `Cannot load \"${clip(spec, 200)}\": the sandbox has no packages and no Node or browser modules - only workspace files by path (\"./lib.js\")`,\n )\n }\n const parts: string[] = spec.startsWith('/') ? [] : dirname(base).split('/').filter(Boolean)\n for (const seg of spec.split('/')) {\n if (!seg || seg === '.') {\n continue\n }\n if (seg === '..') {\n if (parts.length === 0) {\n throw new Error(`Cannot load \"${clip(spec, 200)}\": the path leaves the workspace`)\n }\n parts.pop()\n continue\n }\n parts.push(seg)\n }\n const path = `/${parts.join('/')}`\n if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) {\n throw new Error(\n `Cannot load \"${clip(path, 200)}\": only ${SANDBOX_MODULE_EXTENSIONS.join(', ')} files can be imported`,\n )\n }\n return path\n}\n\n// The literal specifiers a source names (import / export-from / import() / require). Used by the\n// host to hand the guest exactly the files a program refers to. A regex, not a parser: a match\n// inside a string or a comment only costs one more read of a real workspace file.\nexport const moduleSpecifiersOf = (source: string): string[] => {\n const found = new Set<string>()\n const patterns = [\n /\\bimport\\s*(?:[\\w$*{}\\s,]*?\\bfrom\\s*)?(['\"])([^'\"\\n]+)\\1/g,\n /\\bexport\\s*[\\w$*{}\\s,]*?\\bfrom\\s*(['\"])([^'\"\\n]+)\\1/g,\n /\\b(?:import|require)\\s*\\(\\s*(['\"])([^'\"\\n]+)\\1\\s*\\)/g,\n ]\n for (const re of patterns) {\n for (const m of source.matchAll(re)) {\n found.add(m[2])\n }\n }\n return [...found]\n}\n\n// Static import / export declarations make the program an ES module (its result is then the\n// default export); everything else is a script whose result is its last expression.\nconst looksLikeModule = (code: string): boolean =>\n /(^|[\\n;])\\s*(import\\s*[\\w$*{'\"]|export\\s+[\\w$*{])/.test(code)\n\n// JS_EVAL_FLAG_ASYNC: a script may use top-level await; its completion value arrives wrapped.\nconst EVAL_SCRIPT_ASYNC = 128\n\n// The guest's own runtime, evaluated inside it before the program. It may be tampered with by\n// the program (it shares its realm) - which only ever damages the program's own output: the\n// host takes nothing from it but strings.\nconst BOOTSTRAP = `(function (host, cfg) {\n 'use strict';\n var g = globalThis, J = JSON, S = String, E = Error, P = Promise, M = Map, R = Reflect;\n var hostLog = host.log, hostTimer = host.timer, hostClear = host.clear;\n var hostCall = host.call, hostResolve = host.resolve, hostCompile = host.compile;\n function inspect(v, depth, seen) {\n var t = typeof v;\n if (t === 'string') return depth ? J.stringify(v) : v;\n if (t === 'bigint') return S(v) + 'n';\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';\n if (t !== 'object' || v === null) return S(v);\n if (v instanceof E) return S(v.name) + ': ' + S(v.message) + (v.stack ? '\\\\n' + S(v.stack).replace(/\\\\n$/, '') : '');\n if (seen.indexOf(v) >= 0) return '[Circular]';\n if (depth > 4) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (v instanceof Date) return isNaN(v) ? 'Invalid Date' : v.toISOString();\n if (v instanceof RegExp) return S(v);\n seen.push(v);\n var parts = [], out, i, keys;\n if (Array.isArray(v)) {\n for (i = 0; i < v.length && i < 100; i++) parts.push(inspect(v[i], depth + 1, seen));\n if (v.length > 100) parts.push('... ' + (v.length - 100) + ' more');\n out = parts.length ? '[ ' + parts.join(', ') + ' ]' : '[]';\n } else if (v instanceof M) {\n v.forEach(function (val, key) { if (parts.length < 50) parts.push(inspect(key, depth + 1, seen) + ' => ' + inspect(val, depth + 1, seen)); });\n out = 'Map(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';\n } else if (v instanceof Set) {\n v.forEach(function (val) { if (parts.length < 50) parts.push(inspect(val, depth + 1, seen)); });\n out = 'Set(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';\n } else {\n keys = Object.keys(v);\n for (i = 0; i < keys.length && i < 50; i++) parts.push(keys[i] + ': ' + inspect(v[keys[i]], depth + 1, seen));\n if (keys.length > 50) parts.push('... ' + (keys.length - 50) + ' more');\n out = parts.length ? '{ ' + parts.join(', ') + ' }' : '{}';\n }\n seen.pop();\n return out;\n }\n function print(level) {\n return function () {\n var s = '', i;\n try {\n for (i = 0; i < arguments.length && s.length <= cfg.max; i++) s += (i ? ' ' : '') + inspect(arguments[i], 0, []);\n } catch (e) { s += '[unprintable]'; }\n hostLog(level, s.length > cfg.max ? s.slice(0, cfg.max + 1) : s);\n };\n }\n g.console = { log: print(''), info: print(''), debug: print(''), trace: print(''), warn: print('warn'), error: print('error') };\n function plain(v, depth, seen, budget) {\n var t = typeof v, out, i, keys;\n if ((budget.n -= 1) < 0) { budget.cut = true; return '[Truncated]'; }\n if (v === null || t === 'boolean' || t === 'undefined') return v;\n if (t === 'string') { if (v.length > cfg.max) { budget.cut = true; return v.slice(0, cfg.max); } return v; }\n if (t === 'number') return isFinite(v) ? v : S(v);\n if (t === 'bigint') return S(v) + 'n';\n if (t === 'symbol') return S(v);\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';\n if (v instanceof E) return { name: S(v.name), message: S(v.message) };\n if (seen.indexOf(v) >= 0) return '[Circular]';\n if (depth >= 8) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (v instanceof Date) return isNaN(v) ? null : v.toISOString();\n seen.push(v);\n if (v instanceof M) { out = []; v.forEach(function (val, key) { out.push([plain(key, depth + 1, seen, budget), plain(val, depth + 1, seen, budget)]); }); }\n else if (v instanceof Set) { out = []; v.forEach(function (val) { out.push(plain(val, depth + 1, seen, budget)); }); }\n else if (Array.isArray(v)) { out = []; for (i = 0; i < v.length && budget.n >= 0; i++) out.push(plain(v[i], depth + 1, seen, budget)); }\n else { out = {}; keys = Object.keys(v); for (i = 0; i < keys.length && budget.n >= 0; i++) out[keys[i]] = plain(v[keys[i]], depth + 1, seen, budget); }\n seen.pop();\n return out;\n }\n function serialize(v, max) {\n if (v === undefined) return '';\n var budget = { n: 20000, cut: false }, text;\n try { text = J.stringify(plain(v, 0, [], budget)); } catch (e) { text = J.stringify('[unserializable]'); }\n if (text === undefined) return '';\n if (text.length > max) return 'T' + text.slice(0, max);\n return (budget.cut ? 'C' : 'J') + text;\n }\n function describe(e) {\n var name = 'Error', message = '', stack = '';\n try {\n if (e instanceof E || (e && typeof e === 'object' && typeof e.message === 'string')) {\n name = S(e.name || 'Error'); message = S(e.message); stack = typeof e.stack === 'string' ? e.stack : '';\n } else { message = 'thrown: ' + inspect(e, 1, []); }\n } catch (x) { message = '[unprintable error]'; }\n return J.stringify([name.slice(0, cfg.nameMax), message.slice(0, cfg.textMax), stack.slice(0, cfg.textMax)]);\n }\n var timers = new M(), nextTimer = 1;\n function timer(repeat) {\n return function (fn, ms) {\n if (typeof fn !== 'function') throw new TypeError('the first argument must be a function');\n if (timers.size >= cfg.maxTimers) throw new RangeError('too many timers');\n var id = nextTimer++;\n ms = +ms; if (!(ms >= 0)) ms = 0; if (ms > 2147483647) ms = 2147483647;\n if (repeat && ms < 1) ms = 1;\n timers.set(id, { fn: fn, args: Array.prototype.slice.call(arguments, 2), ms: ms, repeat: repeat });\n hostTimer(id, ms);\n return id;\n };\n }\n function clear(id) { if (timers.delete(id)) hostClear(id); }\n function fire(id) {\n var t = timers.get(id);\n if (!t) return;\n if (t.repeat) hostTimer(id, t.ms); else timers.delete(id);\n R.apply(t.fn, undefined, t.args);\n }\n g.setTimeout = timer(false); g.setInterval = timer(true);\n g.clearTimeout = clear; g.clearInterval = clear;\n g.queueMicrotask = function (fn) { P.resolve().then(fn); };\n if (cfg.ops.length) {\n var fs = {};\n cfg.ops.forEach(function (op) {\n fs[op] = function () {\n var text;\n try { text = J.stringify(Array.prototype.slice.call(arguments)); } catch (e) { return P.reject(new TypeError('fs.' + op + ': the arguments must be plain data')); }\n if (text.length > cfg.maxCall) return P.reject(new RangeError('fs.' + op + ': the arguments are too large'));\n return hostCall(op, text).then(function (r) { return r === '' ? undefined : J.parse(r); });\n };\n });\n g.fs = fs;\n }\n var loaded = new M();\n function requireFrom(base) {\n return function require(spec) {\n var path = hostResolve(base, S(spec)), mod = loaded.get(path), made;\n if (mod) return mod.exports;\n mod = { exports: {} };\n loaded.set(path, mod);\n made = hostCompile(path);\n if (typeof made === 'string') mod.exports = J.parse(made);\n else made.call(mod.exports, mod, mod.exports, requireFrom(path), path, path.slice(0, Math.max(1, path.lastIndexOf('/'))));\n return mod.exports;\n };\n }\n g.require = requireFrom(cfg.filename);\n return { fire: fire, serialize: serialize, describe: describe };\n})`\n\nconst BOOTSTRAP_FILE = '<sandbox>'\nconst REFUSED = '\\u0001refused:'\n\n// The slice of quickjs-emscripten this file uses. Typed loosely on purpose: the package is an\n// optional peer, so its types must not appear in what this package publishes.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Any = any\nexport interface ISandboxLib {\n RELEASE_SYNC: Any\n newVariant: (base: Any, options: { wasmMemory: Any }) => Any\n newQuickJSWASMModuleFromVariant: (variant: Any) => Promise<Any>\n}\n\nconst WASM_PAGE = 65536\n\n// The memory limit. QuickJS's own accounting (`setMemoryLimit`) cannot be relied on in this\n// build: without malloc_usable_size it counts 8 bytes per allocation, so a 2 MiB \"limit\" let a\n// guest take 490 MB (measured). The bound that holds is the WebAssembly memory itself: the\n// engine is instantiated on a Memory with a maximum, and the wasm runtime refuses to grow past\n// it - whatever the guest, or a bug in the engine, asks for.\nconst newBoundedModule = (lib: ISandboxLib, limitBytes: number): Promise<Any> => {\n const wasm = (globalThis as Any).WebAssembly\n const wasmMemory = new wasm.Memory({\n initial: SANDBOX_FLOORS.memoryLimitBytes / WASM_PAGE,\n maximum: Math.floor(limitBytes / WASM_PAGE),\n })\n return lib.newQuickJSWASMModuleFromVariant(lib.newVariant(lib.RELEASE_SYNC, { wasmMemory }))\n}\n\nexport interface IRunGuestOptions {\n hostCall?: SandboxHostCall\n // Called once the engine is loaded, right before the program is evaluated (the clock starts here).\n onStart?: () => void\n}\n\n/**\n * Run one program in a fresh QuickJS instance (its own WebAssembly module, so its own memory)\n * and resolve with what it printed and returned. Never rejects for anything the GUEST did - a\n * throw, a timeout, running out of memory are results. It rejects only when the engine itself\n * cannot be created.\n *\n * It runs on the calling thread: the interrupt handler stops JavaScript that loops, but not a\n * single long native call (a 16 MiB `indexOf`). The hard stop is the caller's - see `runInWorker`.\n */\nexport const runGuest = async (\n lib: ISandboxLib,\n request: ISandboxRequest,\n options: IRunGuestOptions = {},\n): Promise<ISandboxResult> => {\n const { limits } = request\n const filename = request.filename ?? '/main.js'\n const modules = request.modules\n const hostOps = options.hostCall ? (request.hostOps ?? []) : []\n const mod = await newBoundedModule(lib, limits.memoryLimitBytes)\n const rt = mod.newRuntime()\n // Makes one oversized allocation fail at once; the bound itself is the module's memory.\n rt.setMemoryLimit(limits.memoryLimitBytes)\n rt.setMaxStackSize(GUEST_STACK_BYTES)\n const ctx = rt.newContext()\n\n return new Promise<ISandboxResult>((resolve) => {\n const startedAt = Date.now()\n let finished = false\n let interrupted = false\n // Time spent inside the guest, and time spent waiting for the host to serve a file call.\n let cpuMs = 0\n let entryAt = 0\n let waitMs = 0\n let waitingSince = 0\n let pendingCalls = 0\n let hostCalls = 0\n let watchdog: ReturnType<typeof setTimeout> | undefined\n const hostTimers = new Map<number, ReturnType<typeof setTimeout>>()\n const out: string[] = []\n let outChars = 0\n let truncated = false\n let internals: Any\n let main: Any\n // 'script' = the async-script wrapper ({ value }), 'module' = a namespace, 'value' = the result itself.\n let mainKind: 'script' | 'module' | 'value' = 'value'\n\n const cpuUsed = (): number => cpuMs + (entryAt ? Date.now() - entryAt : 0)\n const wallUsed = (): number =>\n Date.now() - startedAt - waitMs - (waitingSince ? Date.now() - waitingSince : 0)\n const overTime = (): boolean =>\n cpuUsed() > limits.timeoutMs || (pendingCalls === 0 && wallUsed() > limits.timeoutMs)\n\n rt.setInterruptHandler(() => {\n if (finished || overTime()) {\n interrupted = true\n return true\n }\n return false\n })\n\n const finish = (error?: ISandboxError, result?: { value: unknown }): void => {\n if (finished) {\n return\n }\n finished = true\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n }\n for (const t of hostTimers.values()) {\n clearTimeout(t)\n }\n hostTimers.clear()\n // The instance is not disposed handle by handle: nothing of it is reused, and dropping the\n // module frees its memory with it.\n resolve({\n ok: !error,\n stdout: out.join(''),\n ...(result ? { result: result.value } : {}),\n ...(error ? { error } : {}),\n truncated,\n durationMs: Date.now() - startedAt,\n })\n }\n\n const timedOut = (): ISandboxError => ({\n name: 'TimeoutError',\n message: `the run was stopped after ${limits.timeoutMs} ms (timeoutMs)`,\n })\n\n // Read a guest error. Runs guest code (getters), so it is skipped after an interrupt.\n const describe = (handle: Any): ISandboxError => {\n if (interrupted) {\n return timedOut()\n }\n try {\n let raw: unknown\n if (internals) {\n const r = ctx.callFunction(internals.describe, ctx.undefined, handle)\n raw = r.error ? undefined : JSON.parse(ctx.getString(r.value))\n }\n if (!Array.isArray(raw)) {\n const d = ctx.dump(handle) as { name?: unknown; message?: unknown; stack?: unknown }\n raw = [d?.name ?? 'Error', d?.message ?? String(d), d?.stack ?? '']\n }\n const [name, message, stack] = raw as unknown[]\n const frames = String(stack ?? '')\n .split('\\n')\n .filter((line) => line.trim() && !line.includes(BOOTSTRAP_FILE))\n .join('\\n')\n return {\n name: clip(String(name || 'Error'), ERROR_NAME_CHARS),\n message: clip(String(message ?? ''), ERROR_TEXT_CHARS),\n ...(frames ? { stack: clip(frames, ERROR_TEXT_CHARS) } : {}),\n }\n } catch {\n return interrupted\n ? timedOut()\n : { name: 'Error', message: 'the program threw an error that could not be read' }\n }\n }\n\n // Something escaped the engine as a HOST exception (the native stack ran out under a deep\n // guest recursion, or the engine trapped). The instance is not trusted after that.\n const engineFailure = (err: unknown): void => {\n if (interrupted) {\n finish(timedOut())\n } else if (err instanceof RangeError) {\n finish({ name: 'RangeError', message: 'Maximum call stack size exceeded' })\n } else {\n finish({ name: 'SandboxError', message: clip(errorText(err), ERROR_TEXT_CHARS) })\n }\n }\n\n const armWatchdog = (): void => {\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n watchdog = undefined\n }\n if (finished || pendingCalls > 0) {\n return\n }\n watchdog = setTimeout(\n () => {\n watchdog = undefined\n if (overTime()) {\n interrupted = true\n finish(timedOut())\n } else {\n armWatchdog()\n }\n },\n Math.max(1, limits.timeoutMs - wallUsed() + 1),\n )\n }\n\n // Look at the program's promise: done, failed, or still waiting on a timer / a file call.\n const settle = (): void => {\n while (!finished) {\n if (interrupted) {\n finish(timedOut())\n return\n }\n const state = ctx.getPromiseState(main)\n if (state.type === 'rejected') {\n finish(describe(state.error))\n return\n }\n if (state.type === 'pending') {\n if (hostTimers.size === 0 && pendingCalls === 0) {\n finish({\n name: 'Error',\n message:\n 'the program awaits a promise that can never settle (nothing is left to run)',\n })\n }\n return\n }\n if (mainKind !== 'value') {\n main = ctx.getProp(state.value, mainKind === 'script' ? 'value' : 'default')\n mainKind = 'value'\n continue\n }\n if (!state.notAPromise) {\n main = state.value\n continue\n }\n // Like Node, the run ends when nothing is left to run - not when the last line is reached.\n if (hostTimers.size > 0 || pendingCalls > 0) {\n return\n }\n const max = Math.max(200, limits.maxOutputChars - outChars)\n const r = ctx.callFunction(\n internals.serialize,\n ctx.undefined,\n state.value,\n ctx.newNumber(max),\n )\n if (r.error) {\n finish(describe(r.error))\n return\n }\n const text = ctx.getString(r.value) as string\n if (text === '') {\n finish()\n } else if (text[0] === 'T') {\n truncated = true\n finish(undefined, { value: clip(text.slice(1), max) })\n } else {\n truncated ||= text[0] === 'C'\n finish(undefined, { value: JSON.parse(text.slice(1)) })\n }\n return\n }\n }\n\n // Every entry into the guest goes through here: timed, drained, then judged.\n const enter = (fn: () => void): void => {\n if (finished) {\n return\n }\n entryAt = Date.now()\n try {\n fn()\n while (!finished && !interrupted) {\n const jobs = rt.executePendingJobs()\n if (jobs.error) {\n const error = describe(jobs.error)\n cpuMs += Date.now() - entryAt\n entryAt = 0\n finish(error)\n return\n }\n if (!rt.hasPendingJob()) {\n break\n }\n }\n cpuMs += Date.now() - entryAt\n entryAt = 0\n settle()\n } catch (err) {\n cpuMs += Date.now() - entryAt\n entryAt = 0\n engineFailure(err)\n }\n }\n\n const guestError = (name: string, message: string): Error =>\n Object.assign(new Error(message), { name })\n\n const host = ctx.newObject()\n const expose = (name: string, fn: (...args: Any[]) => Any): void => {\n ctx.setProp(host, name, ctx.newFunction(name, fn))\n }\n expose('log', (levelHandle, textHandle) => {\n if (outChars >= limits.maxOutputChars) {\n truncated = true\n return\n }\n const level = ctx.getString(levelHandle) as string\n let line = `${level ? `[${level}] ` : ''}${ctx.getString(textHandle) as string}\\n`\n if (outChars + line.length > limits.maxOutputChars) {\n line = line.slice(0, limits.maxOutputChars - outChars)\n truncated = true\n }\n out.push(line)\n outChars += line.length\n })\n expose('timer', (idHandle, msHandle) => {\n const id = ctx.getNumber(idHandle) as number\n const ms = ctx.getNumber(msHandle) as number\n const previous = hostTimers.get(id)\n if (previous !== undefined) {\n clearTimeout(previous)\n } else if (hostTimers.size >= MAX_TIMERS) {\n throw guestError('RangeError', 'too many timers')\n }\n hostTimers.set(\n id,\n setTimeout(\n () => {\n hostTimers.delete(id)\n enter(() => {\n const r = ctx.callFunction(internals.fire, ctx.undefined, ctx.newNumber(id))\n if (r.error) {\n // An exception nobody caught in a timer callback ends the run, as it would a process.\n finish(describe(r.error))\n }\n })\n },\n // A timer past the deadline never fires: the watchdog ends the run first.\n Math.min(Math.max(0, ms), limits.timeoutMs + 1),\n ),\n )\n })\n expose('clear', (idHandle) => {\n const id = ctx.getNumber(idHandle) as number\n const t = hostTimers.get(id)\n if (t !== undefined) {\n clearTimeout(t)\n hostTimers.delete(id)\n }\n })\n expose('call', (opHandle, argsHandle) => {\n const op = ctx.getString(opHandle) as string\n if (!hostOps.includes(op as SandboxHostOp) || !options.hostCall) {\n throw guestError('Error', `fs.${clip(op, 40)} is not available in this sandbox`)\n }\n if ((hostCalls += 1) > SANDBOX_MAX_HOST_CALLS) {\n throw guestError(\n 'RangeError',\n `too many file operations in one run (limit ${SANDBOX_MAX_HOST_CALLS})`,\n )\n }\n const args = JSON.parse(ctx.getString(argsHandle) as string) as unknown[]\n const deferred = ctx.newPromise()\n if (pendingCalls === 0) {\n waitingSince = Date.now()\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n watchdog = undefined\n }\n }\n pendingCalls += 1\n const done = (settleGuest: () => void): void => {\n pendingCalls -= 1\n if (pendingCalls === 0) {\n waitMs += Date.now() - waitingSince\n waitingSince = 0\n }\n if (finished) {\n return\n }\n armWatchdog()\n enter(settleGuest)\n }\n options.hostCall(op, args).then(\n (value) =>\n done(() => {\n const text = value === undefined ? '' : JSON.stringify(value)\n deferred.resolve(ctx.newString(text ?? ''))\n }),\n (err: unknown) =>\n done(() => {\n deferred.reject(\n ctx.newError({\n name: 'Error',\n message: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS),\n }),\n )\n }),\n )\n return deferred.handle\n })\n const load = (path: string): string => {\n if (!modules) {\n throw guestError('Error', `Cannot load \"${clip(path, 200)}\": this sandbox has no files`)\n }\n if (!Object.hasOwn(modules, path)) {\n throw guestError(\n 'Error',\n `Cannot load \"${clip(path, 200)}\": no such file in the workspace (a module must exist before the run and be named by a literal path)`,\n )\n }\n return modules[path]\n }\n const resolvePath = (base: string, spec: string): string => {\n try {\n return resolveModulePath(base, spec)\n } catch (err) {\n throw guestError('Error', err instanceof Error ? err.message : String(err))\n }\n }\n expose('resolve', (baseHandle, specHandle) =>\n ctx.newString(\n resolvePath(ctx.getString(baseHandle) as string, ctx.getString(specHandle) as string),\n ),\n )\n expose('compile', (pathHandle) => {\n const path = ctx.getString(pathHandle) as string\n const source = load(path)\n if (path.toLowerCase().endsWith('.json')) {\n return ctx.newString(source)\n }\n const r = ctx.evalCode(\n `(function (module, exports, require, __filename, __dirname) {${source}\\n})`,\n path,\n )\n if (r.error) {\n return { error: r.error }\n }\n return r.value\n })\n // `import` (static and dynamic). Always installed, so that `import('node:fs')` fails with a\n // sentence the model can act on instead of an engine default.\n rt.setModuleLoader(\n (path: string) => {\n try {\n if (path.startsWith(REFUSED)) {\n throw new Error(path.slice(REFUSED.length))\n }\n const source = load(path)\n return path.toLowerCase().endsWith('.json')\n ? `export default JSON.parse(${JSON.stringify(source)})`\n : source\n } catch (err) {\n return { error: err as Error }\n }\n },\n (base: string, spec: string) => {\n // A refusal travels as a name the loader then refuses with the same sentence (the\n // engine drops an error returned from here).\n try {\n return resolveModulePath(base, spec)\n } catch (err) {\n return `${REFUSED}${err instanceof Error ? err.message : String(err)}`\n }\n },\n )\n\n try {\n const boot = ctx.evalCode(BOOTSTRAP, BOOTSTRAP_FILE)\n if (boot.error) {\n finish({ name: 'SandboxError', message: 'the sandbox runtime failed to start' })\n return\n }\n const made = ctx.callFunction(\n boot.value,\n ctx.undefined,\n host,\n ctx\n .evalCode(\n `(${JSON.stringify({\n max: limits.maxOutputChars,\n nameMax: ERROR_NAME_CHARS,\n textMax: ERROR_TEXT_CHARS,\n maxTimers: MAX_TIMERS,\n maxCall: SANDBOX_MAX_FILE_CHARS + 2000,\n ops: hostOps,\n filename,\n })})`,\n BOOTSTRAP_FILE,\n )\n .unwrap(),\n )\n if (made.error) {\n finish({ name: 'SandboxError', message: 'the sandbox runtime failed to start' })\n return\n }\n internals = {\n fire: ctx.getProp(made.value, 'fire'),\n serialize: ctx.getProp(made.value, 'serialize'),\n describe: ctx.getProp(made.value, 'describe'),\n }\n } catch (err) {\n engineFailure(err)\n return\n }\n\n options.onStart?.()\n armWatchdog()\n enter(() => {\n let evaluated = ctx.evalCode(request.code, filename, EVAL_SCRIPT_ASYNC)\n mainKind = 'script'\n // A script that does not compile has run nothing: when it is written as a module, run it as one.\n if (evaluated.error && !interrupted && looksLikeModule(request.code)) {\n evaluated = ctx.evalCode(request.code, filename, { type: 'module' })\n mainKind = 'module'\n }\n if (evaluated.error) {\n finish(describe(evaluated.error))\n return\n }\n main = evaluated.value\n })\n })\n}\n\n// ── What comes back ──────────────────────────────────────────────────────\n\nconst jsonSafe = (value: unknown, max: number): { value: unknown; cut: boolean } => {\n let text: string | undefined\n try {\n text = JSON.stringify(value)\n } catch {\n return { value: '[unserializable]', cut: true }\n }\n if (text === undefined) {\n return { value: undefined, cut: false }\n }\n if (text.length > max) {\n return { value: text.slice(0, max), cut: true }\n }\n // Re-parsed: what leaves is plain data, whatever was handed in.\n return { value: JSON.parse(text) as unknown, cut: false }\n}\n\n/**\n * The authoritative shape and size of a run's result. The engine already bounds what it\n * produces; this runs on the agent's side of the boundary and trusts none of it (a worker is\n * the guest's side).\n */\nexport const sanitizeSandboxResult = (raw: unknown, limits: ISandboxLimits): ISandboxResult => {\n const r = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n let truncated = r.truncated === true\n let stdout = typeof r.stdout === 'string' ? r.stdout : ''\n if (stdout.length > limits.maxOutputChars) {\n stdout = stdout.slice(0, limits.maxOutputChars)\n truncated = true\n }\n const result: ISandboxResult = { ok: r.ok === true, stdout, truncated, durationMs: 0 }\n if (Object.hasOwn(r, 'result') && r.result !== undefined) {\n const safe = jsonSafe(r.result, Math.max(200, limits.maxOutputChars - stdout.length))\n if (safe.value !== undefined) {\n result.result = safe.value\n }\n truncated ||= safe.cut\n }\n if (r.error && typeof r.error === 'object') {\n const e = r.error as Record<string, unknown>\n result.error = {\n name: clip(typeof e.name === 'string' ? e.name : 'Error', ERROR_NAME_CHARS),\n message: clip(typeof e.message === 'string' ? e.message : '', ERROR_TEXT_CHARS),\n ...(typeof e.stack === 'string' && e.stack ? { stack: clip(e.stack, ERROR_TEXT_CHARS) } : {}),\n }\n result.ok = false\n } else if (!result.ok) {\n result.error = { name: 'Error', message: 'the run failed' }\n }\n result.truncated = truncated\n result.durationMs =\n typeof r.durationMs === 'number' && Number.isFinite(r.durationMs) && r.durationMs >= 0\n ? Math.round(r.durationMs)\n : 0\n return result\n}\n\n// ── The worker protocol ──────────────────────────────────────────────────\n// The guest does not run on the agent's thread. One worker serves one run and is thrown away.\n\nexport type SandboxToWorker =\n | { type: 'run'; request: ISandboxRequest }\n | { type: 'host-result'; id: number; ok: boolean; value?: unknown; error?: string }\n\nexport type SandboxFromWorker =\n | { type: 'started' }\n | { type: 'host-call'; id: number; op: string; args: unknown[] }\n | { type: 'done'; result: unknown }\n | { type: 'failed'; code: 'peer-missing' | 'engine'; message: string }\n\n// A message channel as this file needs it; each package adapts its own worker type to it.\nexport interface ISandboxPort {\n post: (message: unknown) => void\n // `onClose` fires when the other side is gone (a worker that exited or crashed).\n listen: (onMessage: (message: unknown) => void, onClose?: (reason: string) => void) => void\n // The parent's side only: kill the worker.\n terminate?: () => void\n}\n\n/** The worker's side: load the engine, run what is posted, answer. */\nexport const serveSandbox = (port: ISandboxPort, loadLib: () => Promise<ISandboxLib>): void => {\n const waiting = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>()\n let seq = 0\n let busy = false\n const run = async (request: ISandboxRequest): Promise<void> => {\n let lib: ISandboxLib\n try {\n lib = await loadLib()\n } catch (err) {\n port.post({ type: 'failed', code: 'peer-missing', message: errorText(err) })\n return\n }\n try {\n const result = await runGuest(lib, request, {\n onStart: () => port.post({ type: 'started' }),\n hostCall: (op, args) =>\n new Promise((resolve, reject) => {\n const id = (seq += 1)\n waiting.set(id, { resolve, reject })\n port.post({ type: 'host-call', id, op, args })\n }),\n })\n port.post({ type: 'done', result })\n } catch (err) {\n port.post({ type: 'failed', code: 'engine', message: errorText(err) })\n }\n }\n port.listen((message) => {\n const m = message as SandboxToWorker\n if (m?.type === 'run' && !busy) {\n busy = true\n void run(m.request)\n } else if (m?.type === 'host-result') {\n const w = waiting.get(m.id)\n if (w) {\n waiting.delete(m.id)\n if (m.ok) {\n w.resolve(m.value)\n } else {\n w.reject(new Error(typeof m.error === 'string' ? m.error : 'the file operation failed'))\n }\n }\n }\n })\n}\n\nexport interface IRunInWorkerOptions {\n hostCall?: SandboxHostCall\n signal?: AbortSignal\n // How long the worker may take to load the engine before the run is given up (default 20 s).\n startupMs?: number\n // How far past `timeoutMs` the worker lives before it is terminated (default 1000 ms).\n graceMs?: number\n}\n\n/**\n * The agent's side: post one run to a fresh worker and wait for it - or kill it. The engine's\n * own interrupt handler is the soft stop; `terminate()` here is the hard one, and it does not\n * depend on anything the guest does. Rejects only when the sandbox itself is unavailable (the\n * optional peer is missing, the worker never started) or the run was aborted.\n */\nexport const runInWorker = (\n port: ISandboxPort,\n request: ISandboxRequest,\n options: IRunInWorkerOptions = {},\n): Promise<ISandboxResult> =>\n new Promise<ISandboxResult>((resolve, reject) => {\n const { limits } = request\n const startedAt = Date.now()\n const graceMs = options.graceMs ?? 1000\n let over = false\n let serving = 0\n let timer: ReturnType<typeof setTimeout> | undefined\n const stop = (): void => {\n over = true\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n options.signal?.removeEventListener('abort', onAbort)\n try {\n port.terminate?.()\n } catch {\n /* already gone */\n }\n }\n const end = (result: ISandboxResult): void => {\n if (over) {\n return\n }\n stop()\n resolve({ ...result, durationMs: Date.now() - startedAt })\n }\n const fail = (err: Error): void => {\n if (over) {\n return\n }\n stop()\n reject(err)\n }\n const failed = (name: string, message: string): ISandboxResult => ({\n ok: false,\n stdout: '',\n error: { name, message },\n truncated: false,\n durationMs: 0,\n })\n function onAbort(): void {\n fail(Object.assign(new Error('The run was aborted'), { name: 'AbortError' }))\n }\n const arm = (ms: number, onFire: () => void): void => {\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n timer = setTimeout(onFire, ms)\n }\n const armKill = (): void =>\n arm(limits.timeoutMs + graceMs, () =>\n end(\n failed(\n 'TimeoutError',\n `the run was killed after ${limits.timeoutMs} ms (timeoutMs): it did not stop by itself`,\n ),\n ),\n )\n if (options.signal?.aborted) {\n onAbort()\n return\n }\n options.signal?.addEventListener('abort', onAbort, { once: true })\n arm(options.startupMs ?? 20_000, () =>\n fail(new SandboxUnavailableError('the sandbox worker did not start in time')),\n )\n port.listen(\n (message) => {\n if (over) {\n return\n }\n const m = message as SandboxFromWorker\n switch (m?.type) {\n case 'started':\n armKill()\n break\n case 'host-call': {\n const id = m.id\n serving += 1\n // The clock does not run while the agent's side serves a call (it may be asking the user).\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n const answer = (reply: SandboxToWorker): void => {\n serving -= 1\n if (over) {\n return\n }\n if (serving === 0) {\n armKill()\n }\n port.post(reply)\n }\n const call = options.hostCall\n ? options.hostCall(String(m.op), Array.isArray(m.args) ? m.args : [])\n : Promise.reject(new Error('this sandbox has no files'))\n call.then(\n (value) => answer({ type: 'host-result', id, ok: true, value }),\n (err: unknown) =>\n answer({\n type: 'host-result',\n id,\n ok: false,\n error: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS),\n }),\n )\n break\n }\n case 'done':\n end(sanitizeSandboxResult(m.result, limits))\n break\n case 'failed':\n fail(\n m.code === 'peer-missing'\n ? sandboxPeerMissing(clip(String(m.message), 300))\n : new SandboxUnavailableError(\n `the sandbox engine failed: ${clip(String(m.message), 300)}`,\n ),\n )\n break\n }\n },\n (reason) =>\n end(failed('SandboxError', `the sandbox stopped unexpectedly: ${clip(reason, 300)}`)),\n )\n port.post({ type: 'run', request } satisfies SandboxToWorker)\n })\n\n// At most `size` runs at once; the rest wait their turn (each run is a worker and a heap).\nexport const createSandboxQueue = (size: number): (<T>(task: () => Promise<T>) => Promise<T>) => {\n let active = 0\n const waiting: (() => void)[] = []\n return async <T>(task: () => Promise<T>): Promise<T> => {\n if (active >= size) {\n await new Promise<void>((go) => waiting.push(go))\n }\n active += 1\n try {\n return await task()\n } finally {\n active -= 1\n waiting.shift()?.()\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcO,IAAM,cAAc;AA0B3B,IAAM,MAAM,OAAO;AAEZ,IAAM,mBAAmC;AAAA,EAC9C,WAAW;AAAA,EACX,kBAAkB,KAAK;AAAA,EACvB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAGO,IAAM,eAA+B;AAAA,EAC1C,WAAW;AAAA,EACX,kBAAkB,MAAM;AAAA,EACxB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAEA,IAAM,iBAAiC;AAAA,EACrC,WAAW;AAAA;AAAA,EAEX,kBAAkB,KAAK;AAAA,EACvB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAMO,IAAM,yBAAyB;AAC/B,IAAM,yBAAyB;AAC/B,IAAM,4BAA+C,CAAC,OAAO,QAAQ,OAAO;AAEnF,IAAM,aAAa;AAGnB,IAAM,oBAAoB,MAAM;AAChC,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AA6ElB,IAAM,uBAAuB,6JAA6J,WAAW;AAErM,IAAM,2BAA2B,iDAAiD,WAAW;AAEpG,IAAM,OAAO,CAAC,MAAc,QAAyB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O,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,oBAAmB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/worker.ts","../src/sandbox/engine.ts"],"sourcesContent":["import { serveSandbox, type ISandboxLib } from './engine.js'\n\n/**\n * The Web Worker side of the sandbox (`config.sandbox.worker`): the entry\n * `@dudko.dev/agent-web/sandbox-worker`. Loaded as a worker it serves by itself:\n *\n * ```ts\n * // Vite\n * import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'\n * createAgent({ model, sandbox: { worker: () => new SandboxWorker() } })\n * // webpack 5 and other bundlers that follow `new URL(..., import.meta.url)`\n * createAgent({\n * model,\n * sandbox: {\n * worker: () =>\n * new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' }),\n * },\n * })\n * ```\n *\n * One worker serves one run and is terminated by the agent. The engine (the optional peer\n * `quickjs-emscripten`) is imported here with a literal specifier, so the host's bundler puts\n * it - and its .wasm file - into the worker's chunk and nowhere else.\n */\n\n/** The slice of a worker scope / MessagePort this needs. */\nexport interface SandboxWorkerScope {\n postMessage(message: unknown): void\n addEventListener(type: string, listener: (ev: any) => void): void\n}\n\nexport interface ServeSandboxOptions {\n /** The message endpoint (default: the worker global scope). */\n scope?: SandboxWorkerScope\n /** Load the engine yourself (default: `import('quickjs-emscripten')`). */\n engine?: () => Promise<unknown>\n}\n\nexport const serveSandboxWorker = (opts: ServeSandboxOptions = {}): void => {\n const scope = opts.scope ?? (globalThis as unknown as SandboxWorkerScope)\n serveSandbox(\n {\n post: (message) => scope.postMessage(message),\n listen: (onMessage) => {\n scope.addEventListener('message', (ev: { data: unknown }) => onMessage(ev.data))\n ;(scope as { start?: () => void }).start?.()\n },\n },\n async () =>\n (await (opts.engine\n ? opts.engine()\n : import('quickjs-emscripten'))) as unknown as ISandboxLib,\n )\n}\n\nconst inWorker = (): boolean => {\n const g = globalThis as {\n WorkerGlobalScope?: unknown\n importScripts?: unknown\n document?: unknown\n }\n return typeof g.WorkerGlobalScope !== 'undefined' && typeof g.document === 'undefined'\n}\n\nif (inWorker()) serveSandboxWorker()\n","// The JavaScript sandbox behind `config.sandbox` / the `run_js` tool: the guest runs in QuickJS\n// compiled to WebAssembly (the optional peer `quickjs-emscripten`), never in the host's own\n// JavaScript engine. This file is the part both packages share - limits, the guest's runtime,\n// the module resolver, the worker protocol and what is allowed back across the boundary.\n//\n// It is pure (no imports, no node:* and no DOM) and is a COPY, byte for byte, of the sibling\n// package's file: `packages/agent/src/sandbox-engine.ts` = `packages/agent-web/src/sandbox/engine.ts`.\n// Change both; the Node package's `tests/sandbox-engine.test.ts` compares them.\n//\n// Security boundary. What the guest can reach is exactly what `bootstrap` hands it: console,\n// timers, and - only when the host passes them - a module map and named file operations. Every\n// value that crosses is a string produced inside the guest and re-parsed here, never a host\n// reference. Every guard has a test and a mutation check (see the two packages' sandbox tests).\n\nexport const RUN_JS_TOOL = 'run_js'\nexport const SANDBOX_PACKAGE = 'quickjs-emscripten'\n\nexport interface ISandboxConfig {\n // Time one run may take, in ms (default 5000, at most 60000), counted from the program's first\n // instruction: starting the worker and the engine does not count, and neither does waiting for\n // a file operation - a consent prompt included.\n timeoutMs?: number\n // The guest's memory, in bytes: the whole WebAssembly memory of its engine instance, the\n // engine's own 16 MiB included (default 32 MiB, at least 16 MiB, at most 256 MiB).\n memoryLimitBytes?: number\n // What a run returns to the model, stdout and result together, in characters (default 8000).\n maxOutputChars?: number\n // The longest program accepted, in characters (default 100000).\n maxCodeChars?: number\n // Let the guest import / require workspace files and use `fs` (default true where the agent\n // has a workspace; without one there is nothing to bind and this is ignored).\n files?: boolean\n}\n\nexport interface ISandboxLimits {\n timeoutMs: number\n memoryLimitBytes: number\n maxOutputChars: number\n maxCodeChars: number\n}\n\nconst MIB = 1024 * 1024\n\nexport const SANDBOX_DEFAULTS: ISandboxLimits = {\n timeoutMs: 5000,\n memoryLimitBytes: 32 * MIB,\n maxOutputChars: 8000,\n maxCodeChars: 100_000,\n}\n\n// A host cannot configure past these: the tool is for checking a piece of code, not for hosting one.\nexport const SANDBOX_CAPS: ISandboxLimits = {\n timeoutMs: 60_000,\n memoryLimitBytes: 256 * MIB,\n maxOutputChars: 100_000,\n maxCodeChars: 1_000_000,\n}\n\nconst SANDBOX_FLOORS: ISandboxLimits = {\n timeoutMs: 50,\n // What the engine's WebAssembly module asks for before it runs anything.\n memoryLimitBytes: 16 * MIB,\n maxOutputChars: 200,\n maxCodeChars: 100,\n}\n\n// One module the guest may load, and all of them together (characters).\nexport const SANDBOX_MAX_MODULES = 64\nexport const SANDBOX_MAX_MODULE_CHARS_TOTAL = 2_000_000\n// A file the guest reads or writes through `fs` (characters), and the calls of one run.\nexport const SANDBOX_MAX_FILE_CHARS = 1_000_000\nexport const SANDBOX_MAX_HOST_CALLS = 500\nexport const SANDBOX_MODULE_EXTENSIONS: readonly string[] = ['.js', '.mjs', '.json']\n\nconst MAX_TIMERS = 1000\n// QuickJS's own stack check. Small on purpose: wasm frames live on the host thread's native\n// stack, and a deeper guest recursion would overflow THAT before QuickJS noticed.\nconst GUEST_STACK_BYTES = 256 * 1024\nconst ERROR_NAME_CHARS = 200\nconst ERROR_TEXT_CHARS = 4000\n\nconst bounded = (value: unknown, key: keyof ISandboxLimits): number => {\n const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : NaN\n if (Number.isNaN(n) || n <= 0) {\n return SANDBOX_DEFAULTS[key]\n }\n return Math.min(SANDBOX_CAPS[key], Math.max(SANDBOX_FLOORS[key], n))\n}\n\nexport const resolveSandboxLimits = (config: ISandboxConfig | undefined): ISandboxLimits => ({\n timeoutMs: bounded(config?.timeoutMs, 'timeoutMs'),\n memoryLimitBytes: bounded(config?.memoryLimitBytes, 'memoryLimitBytes'),\n maxOutputChars: bounded(config?.maxOutputChars, 'maxOutputChars'),\n maxCodeChars: bounded(config?.maxCodeChars, 'maxCodeChars'),\n})\n\nexport interface ISandboxError {\n name: string\n message: string\n // Guest frames only: the host's own frames never cross.\n stack?: string\n}\n\n// What `run_js` returns to the model.\nexport interface ISandboxResult {\n ok: boolean\n // console.log / info / warn / error, in the order they were called.\n stdout: string\n // The value of the last expression (a module's default export), as JSON-like data.\n result?: unknown\n error?: ISandboxError\n // stdout or result was cut to fit `maxOutputChars`.\n truncated: boolean\n durationMs: number\n}\n\nexport type SandboxHostOp = 'readFile' | 'writeFile' | 'readdir'\n\n// One run, as it is posted to the engine. Structured-cloneable.\nexport interface ISandboxRequest {\n code: string\n // The path the code is evaluated as (stack traces, the base of relative imports).\n filename?: string\n limits: ISandboxLimits\n // Workspace files the guest may `import` / `require`, by absolute path. Absent = no loader.\n modules?: Record<string, string>\n // The `fs` functions the host serves. Absent or empty = no `fs`.\n hostOps?: SandboxHostOp[]\n}\n\n// Serves one `fs` call of the guest. Arguments and the answer are JSON-like data.\nexport type SandboxHostCall = (op: string, args: unknown[]) => Promise<unknown>\n\nexport class SandboxUnavailableError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SandboxUnavailableError'\n }\n}\n\nexport const sandboxPeerMissing = (detail?: string): SandboxUnavailableError =>\n new SandboxUnavailableError(\n `The sandbox (${RUN_JS_TOOL}) needs the optional package \"${SANDBOX_PACKAGE}\", which is not installed. ` +\n `Add it to your app: npm install ${SANDBOX_PACKAGE}${detail ? ` (${detail})` : ''}`,\n )\n\n// The run-stable sentences the stage prompts carry when the sandbox is on (both packages say the same).\nexport const sandboxPromptNote = (files: boolean): string =>\n `${RUN_JS_TOOL} runs JavaScript you wrote in an isolated sandbox and returns what it printed (console.log) and the value of its last expression. ` +\n `It is plain JavaScript on QuickJS (ES2023, top-level await), not Node and not a browser: no network, no npm packages, no process${\n files\n ? '; workspace files are reachable by relative path (import / require of .js, .mjs, .json) and through the async fs.readFile / fs.writeFile / fs.readdir'\n : ', no files'\n }. ` +\n `Never say that code was run, tested or printed something unless ${RUN_JS_TOOL} was called and returned it: quote its real output, and if it was not run, say so.`\n\nexport const SANDBOX_PLANNER_NOTE = `When the request needs code to be run, tested or checked on data, or a calculation that is easier to compute than to reason about, plan a step that calls ${RUN_JS_TOOL} for it.`\n\nexport const SANDBOX_SYNTHESIZER_NOTE = `Report the output of running code only when a ${RUN_JS_TOOL} call returned it; if the code was written but not run, say it was not run.`\n\nconst clip = (text: string, max: number): string => (text.length > max ? text.slice(0, max) : text)\n\nconst errorText = (err: unknown): string => {\n if (err instanceof Error) {\n return `${err.name}: ${err.message}`\n }\n return typeof err === 'string' ? err : 'unknown error'\n}\n\nconst dirname = (path: string): string => {\n const i = path.lastIndexOf('/')\n return i <= 0 ? '/' : path.slice(0, i)\n}\n\n// Resolve what the guest asked to load against the file that asked. Throws (with a message for\n// the model) on anything that is not a workspace file by path: a package, a Node built-in, a\n// path that climbs out of the root, an extension outside the allowed three.\nexport const resolveModulePath = (base: string, specifier: string): string => {\n const spec = String(specifier)\n if (!/^(\\.{1,2}\\/|\\/)/.test(spec) || /[\\\\\\0]/.test(spec)) {\n throw new Error(\n `Cannot load \"${clip(spec, 200)}\": the sandbox has no packages and no Node or browser modules - only workspace files by path (\"./lib.js\")`,\n )\n }\n const parts: string[] = spec.startsWith('/') ? [] : dirname(base).split('/').filter(Boolean)\n for (const seg of spec.split('/')) {\n if (!seg || seg === '.') {\n continue\n }\n if (seg === '..') {\n if (parts.length === 0) {\n throw new Error(`Cannot load \"${clip(spec, 200)}\": the path leaves the workspace`)\n }\n parts.pop()\n continue\n }\n parts.push(seg)\n }\n const path = `/${parts.join('/')}`\n if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) {\n throw new Error(\n `Cannot load \"${clip(path, 200)}\": only ${SANDBOX_MODULE_EXTENSIONS.join(', ')} files can be imported`,\n )\n }\n return path\n}\n\n// The literal specifiers a source names (import / export-from / import() / require). Used by the\n// host to hand the guest exactly the files a program refers to. A regex, not a parser: a match\n// inside a string or a comment only costs one more read of a real workspace file.\nexport const moduleSpecifiersOf = (source: string): string[] => {\n const found = new Set<string>()\n const patterns = [\n /\\bimport\\s*(?:[\\w$*{}\\s,]*?\\bfrom\\s*)?(['\"])([^'\"\\n]+)\\1/g,\n /\\bexport\\s*[\\w$*{}\\s,]*?\\bfrom\\s*(['\"])([^'\"\\n]+)\\1/g,\n /\\b(?:import|require)\\s*\\(\\s*(['\"])([^'\"\\n]+)\\1\\s*\\)/g,\n ]\n for (const re of patterns) {\n for (const m of source.matchAll(re)) {\n found.add(m[2])\n }\n }\n return [...found]\n}\n\n// Static import / export declarations make the program an ES module (its result is then the\n// default export); everything else is a script whose result is its last expression.\nconst looksLikeModule = (code: string): boolean =>\n /(^|[\\n;])\\s*(import\\s*[\\w$*{'\"]|export\\s+[\\w$*{])/.test(code)\n\n// JS_EVAL_FLAG_ASYNC: a script may use top-level await; its completion value arrives wrapped.\nconst EVAL_SCRIPT_ASYNC = 128\n\n// The guest's own runtime, evaluated inside it before the program. It may be tampered with by\n// the program (it shares its realm) - which only ever damages the program's own output: the\n// host takes nothing from it but strings.\nconst BOOTSTRAP = `(function (host, cfg) {\n 'use strict';\n var g = globalThis, J = JSON, S = String, E = Error, P = Promise, M = Map, R = Reflect;\n var hostLog = host.log, hostTimer = host.timer, hostClear = host.clear;\n var hostCall = host.call, hostResolve = host.resolve, hostCompile = host.compile;\n function inspect(v, depth, seen) {\n var t = typeof v;\n if (t === 'string') return depth ? J.stringify(v) : v;\n if (t === 'bigint') return S(v) + 'n';\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';\n if (t !== 'object' || v === null) return S(v);\n if (v instanceof E) return S(v.name) + ': ' + S(v.message) + (v.stack ? '\\\\n' + S(v.stack).replace(/\\\\n$/, '') : '');\n if (seen.indexOf(v) >= 0) return '[Circular]';\n if (depth > 4) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (v instanceof Date) return isNaN(v) ? 'Invalid Date' : v.toISOString();\n if (v instanceof RegExp) return S(v);\n seen.push(v);\n var parts = [], out, i, keys;\n if (Array.isArray(v)) {\n for (i = 0; i < v.length && i < 100; i++) parts.push(inspect(v[i], depth + 1, seen));\n if (v.length > 100) parts.push('... ' + (v.length - 100) + ' more');\n out = parts.length ? '[ ' + parts.join(', ') + ' ]' : '[]';\n } else if (v instanceof M) {\n v.forEach(function (val, key) { if (parts.length < 50) parts.push(inspect(key, depth + 1, seen) + ' => ' + inspect(val, depth + 1, seen)); });\n out = 'Map(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';\n } else if (v instanceof Set) {\n v.forEach(function (val) { if (parts.length < 50) parts.push(inspect(val, depth + 1, seen)); });\n out = 'Set(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';\n } else {\n keys = Object.keys(v);\n for (i = 0; i < keys.length && i < 50; i++) parts.push(keys[i] + ': ' + inspect(v[keys[i]], depth + 1, seen));\n if (keys.length > 50) parts.push('... ' + (keys.length - 50) + ' more');\n out = parts.length ? '{ ' + parts.join(', ') + ' }' : '{}';\n }\n seen.pop();\n return out;\n }\n function print(level) {\n return function () {\n var s = '', i;\n try {\n for (i = 0; i < arguments.length && s.length <= cfg.max; i++) s += (i ? ' ' : '') + inspect(arguments[i], 0, []);\n } catch (e) { s += '[unprintable]'; }\n hostLog(level, s.length > cfg.max ? s.slice(0, cfg.max + 1) : s);\n };\n }\n g.console = { log: print(''), info: print(''), debug: print(''), trace: print(''), warn: print('warn'), error: print('error') };\n function plain(v, depth, seen, budget) {\n var t = typeof v, out, i, keys;\n if ((budget.n -= 1) < 0) { budget.cut = true; return '[Truncated]'; }\n if (v === null || t === 'boolean' || t === 'undefined') return v;\n if (t === 'string') { if (v.length > cfg.max) { budget.cut = true; return v.slice(0, cfg.max); } return v; }\n if (t === 'number') return isFinite(v) ? v : S(v);\n if (t === 'bigint') return S(v) + 'n';\n if (t === 'symbol') return S(v);\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';\n if (v instanceof E) return { name: S(v.name), message: S(v.message) };\n if (seen.indexOf(v) >= 0) return '[Circular]';\n if (depth >= 8) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (v instanceof Date) return isNaN(v) ? null : v.toISOString();\n seen.push(v);\n if (v instanceof M) { out = []; v.forEach(function (val, key) { out.push([plain(key, depth + 1, seen, budget), plain(val, depth + 1, seen, budget)]); }); }\n else if (v instanceof Set) { out = []; v.forEach(function (val) { out.push(plain(val, depth + 1, seen, budget)); }); }\n else if (Array.isArray(v)) { out = []; for (i = 0; i < v.length && budget.n >= 0; i++) out.push(plain(v[i], depth + 1, seen, budget)); }\n else { out = {}; keys = Object.keys(v); for (i = 0; i < keys.length && budget.n >= 0; i++) out[keys[i]] = plain(v[keys[i]], depth + 1, seen, budget); }\n seen.pop();\n return out;\n }\n function serialize(v, max) {\n if (v === undefined) return '';\n var budget = { n: 20000, cut: false }, text;\n try { text = J.stringify(plain(v, 0, [], budget)); } catch (e) { text = J.stringify('[unserializable]'); }\n if (text === undefined) return '';\n if (text.length > max) return 'T' + text.slice(0, max);\n return (budget.cut ? 'C' : 'J') + text;\n }\n function describe(e) {\n var name = 'Error', message = '', stack = '';\n try {\n if (e instanceof E || (e && typeof e === 'object' && typeof e.message === 'string')) {\n name = S(e.name || 'Error'); message = S(e.message); stack = typeof e.stack === 'string' ? e.stack : '';\n } else { message = 'thrown: ' + inspect(e, 1, []); }\n } catch (x) { message = '[unprintable error]'; }\n return J.stringify([name.slice(0, cfg.nameMax), message.slice(0, cfg.textMax), stack.slice(0, cfg.textMax)]);\n }\n var timers = new M(), nextTimer = 1;\n function timer(repeat) {\n return function (fn, ms) {\n if (typeof fn !== 'function') throw new TypeError('the first argument must be a function');\n if (timers.size >= cfg.maxTimers) throw new RangeError('too many timers');\n var id = nextTimer++;\n ms = +ms; if (!(ms >= 0)) ms = 0; if (ms > 2147483647) ms = 2147483647;\n if (repeat && ms < 1) ms = 1;\n timers.set(id, { fn: fn, args: Array.prototype.slice.call(arguments, 2), ms: ms, repeat: repeat });\n hostTimer(id, ms);\n return id;\n };\n }\n function clear(id) { if (timers.delete(id)) hostClear(id); }\n function fire(id) {\n var t = timers.get(id);\n if (!t) return;\n if (t.repeat) hostTimer(id, t.ms); else timers.delete(id);\n R.apply(t.fn, undefined, t.args);\n }\n g.setTimeout = timer(false); g.setInterval = timer(true);\n g.clearTimeout = clear; g.clearInterval = clear;\n g.queueMicrotask = function (fn) { P.resolve().then(fn); };\n if (cfg.ops.length) {\n var fs = {};\n cfg.ops.forEach(function (op) {\n fs[op] = function () {\n var text;\n try { text = J.stringify(Array.prototype.slice.call(arguments)); } catch (e) { return P.reject(new TypeError('fs.' + op + ': the arguments must be plain data')); }\n if (text.length > cfg.maxCall) return P.reject(new RangeError('fs.' + op + ': the arguments are too large'));\n return hostCall(op, text).then(function (r) { return r === '' ? undefined : J.parse(r); });\n };\n });\n g.fs = fs;\n }\n var loaded = new M();\n function requireFrom(base) {\n return function require(spec) {\n var path = hostResolve(base, S(spec)), mod = loaded.get(path), made;\n if (mod) return mod.exports;\n mod = { exports: {} };\n loaded.set(path, mod);\n made = hostCompile(path);\n if (typeof made === 'string') mod.exports = J.parse(made);\n else made.call(mod.exports, mod, mod.exports, requireFrom(path), path, path.slice(0, Math.max(1, path.lastIndexOf('/'))));\n return mod.exports;\n };\n }\n g.require = requireFrom(cfg.filename);\n return { fire: fire, serialize: serialize, describe: describe };\n})`\n\nconst BOOTSTRAP_FILE = '<sandbox>'\nconst REFUSED = '\\u0001refused:'\n\n// The slice of quickjs-emscripten this file uses. Typed loosely on purpose: the package is an\n// optional peer, so its types must not appear in what this package publishes.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Any = any\nexport interface ISandboxLib {\n RELEASE_SYNC: Any\n newVariant: (base: Any, options: { wasmMemory: Any }) => Any\n newQuickJSWASMModuleFromVariant: (variant: Any) => Promise<Any>\n}\n\nconst WASM_PAGE = 65536\n\n// The memory limit. QuickJS's own accounting (`setMemoryLimit`) cannot be relied on in this\n// build: without malloc_usable_size it counts 8 bytes per allocation, so a 2 MiB \"limit\" let a\n// guest take 490 MB (measured). The bound that holds is the WebAssembly memory itself: the\n// engine is instantiated on a Memory with a maximum, and the wasm runtime refuses to grow past\n// it - whatever the guest, or a bug in the engine, asks for.\nconst newBoundedModule = (lib: ISandboxLib, limitBytes: number): Promise<Any> => {\n const wasm = (globalThis as Any).WebAssembly\n const wasmMemory = new wasm.Memory({\n initial: SANDBOX_FLOORS.memoryLimitBytes / WASM_PAGE,\n maximum: Math.floor(limitBytes / WASM_PAGE),\n })\n return lib.newQuickJSWASMModuleFromVariant(lib.newVariant(lib.RELEASE_SYNC, { wasmMemory }))\n}\n\nexport interface IRunGuestOptions {\n hostCall?: SandboxHostCall\n // Called once the engine is loaded, right before the program is evaluated (the clock starts here).\n onStart?: () => void\n}\n\n/**\n * Run one program in a fresh QuickJS instance (its own WebAssembly module, so its own memory)\n * and resolve with what it printed and returned. Never rejects for anything the GUEST did - a\n * throw, a timeout, running out of memory are results. It rejects only when the engine itself\n * cannot be created.\n *\n * It runs on the calling thread: the interrupt handler stops JavaScript that loops, but not a\n * single long native call (a 16 MiB `indexOf`). The hard stop is the caller's - see `runInWorker`.\n */\nexport const runGuest = async (\n lib: ISandboxLib,\n request: ISandboxRequest,\n options: IRunGuestOptions = {},\n): Promise<ISandboxResult> => {\n const { limits } = request\n const filename = request.filename ?? '/main.js'\n const modules = request.modules\n const hostOps = options.hostCall ? (request.hostOps ?? []) : []\n const mod = await newBoundedModule(lib, limits.memoryLimitBytes)\n const rt = mod.newRuntime()\n // Makes one oversized allocation fail at once; the bound itself is the module's memory.\n rt.setMemoryLimit(limits.memoryLimitBytes)\n rt.setMaxStackSize(GUEST_STACK_BYTES)\n const ctx = rt.newContext()\n\n return new Promise<ISandboxResult>((resolve) => {\n const startedAt = Date.now()\n // The limit's clock starts with the program (`onStart`), not here: what runs before it is the\n // engine's own start (the host functions, the bootstrap) - our code, the same for every run,\n // and nothing of the guest's. On a busy machine that start alone can outlast a short limit;\n // a worker's start is bounded by `startupMs` instead.\n let programAt = 0\n let finished = false\n let interrupted = false\n // Time spent inside the guest, and time spent waiting for the host to serve a file call.\n let cpuMs = 0\n let entryAt = 0\n let waitMs = 0\n let waitingSince = 0\n let pendingCalls = 0\n let hostCalls = 0\n let watchdog: ReturnType<typeof setTimeout> | undefined\n const hostTimers = new Map<number, ReturnType<typeof setTimeout>>()\n const out: string[] = []\n let outChars = 0\n let truncated = false\n let internals: Any\n let main: Any\n // 'script' = the async-script wrapper ({ value }), 'module' = a namespace, 'value' = the result itself.\n let mainKind: 'script' | 'module' | 'value' = 'value'\n\n const cpuUsed = (): number => cpuMs + (entryAt ? Date.now() - entryAt : 0)\n const wallUsed = (): number =>\n programAt === 0\n ? 0\n : Date.now() - programAt - waitMs - (waitingSince ? Date.now() - waitingSince : 0)\n const overTime = (): boolean =>\n cpuUsed() > limits.timeoutMs || (pendingCalls === 0 && wallUsed() > limits.timeoutMs)\n\n rt.setInterruptHandler(() => {\n if (finished || overTime()) {\n interrupted = true\n return true\n }\n return false\n })\n\n const finish = (error?: ISandboxError, result?: { value: unknown }): void => {\n if (finished) {\n return\n }\n finished = true\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n }\n for (const t of hostTimers.values()) {\n clearTimeout(t)\n }\n hostTimers.clear()\n // The instance is not disposed handle by handle: nothing of it is reused, and dropping the\n // module frees its memory with it.\n resolve({\n ok: !error,\n stdout: out.join(''),\n ...(result ? { result: result.value } : {}),\n ...(error ? { error } : {}),\n truncated,\n durationMs: Date.now() - startedAt,\n })\n }\n\n const timedOut = (): ISandboxError => ({\n name: 'TimeoutError',\n message: `the run was stopped after ${limits.timeoutMs} ms (timeoutMs)`,\n })\n\n // Read a guest error. Runs guest code (getters), so it is skipped after an interrupt.\n const describe = (handle: Any): ISandboxError => {\n if (interrupted) {\n return timedOut()\n }\n try {\n let raw: unknown\n if (internals) {\n const r = ctx.callFunction(internals.describe, ctx.undefined, handle)\n raw = r.error ? undefined : JSON.parse(ctx.getString(r.value))\n }\n if (!Array.isArray(raw)) {\n const d = ctx.dump(handle) as { name?: unknown; message?: unknown; stack?: unknown }\n raw = [d?.name ?? 'Error', d?.message ?? String(d), d?.stack ?? '']\n }\n const [name, message, stack] = raw as unknown[]\n const frames = String(stack ?? '')\n .split('\\n')\n .filter((line) => line.trim() && !line.includes(BOOTSTRAP_FILE))\n .join('\\n')\n return {\n name: clip(String(name || 'Error'), ERROR_NAME_CHARS),\n message: clip(String(message ?? ''), ERROR_TEXT_CHARS),\n ...(frames ? { stack: clip(frames, ERROR_TEXT_CHARS) } : {}),\n }\n } catch {\n return interrupted\n ? timedOut()\n : { name: 'Error', message: 'the program threw an error that could not be read' }\n }\n }\n\n // Something escaped the engine as a HOST exception (the native stack ran out under a deep\n // guest recursion, or the engine trapped). The instance is not trusted after that.\n const engineFailure = (err: unknown): void => {\n if (interrupted) {\n finish(timedOut())\n } else if (err instanceof RangeError) {\n finish({ name: 'RangeError', message: 'Maximum call stack size exceeded' })\n } else {\n finish({ name: 'SandboxError', message: clip(errorText(err), ERROR_TEXT_CHARS) })\n }\n }\n\n const armWatchdog = (): void => {\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n watchdog = undefined\n }\n if (finished || pendingCalls > 0) {\n return\n }\n watchdog = setTimeout(\n () => {\n watchdog = undefined\n if (overTime()) {\n interrupted = true\n finish(timedOut())\n } else {\n armWatchdog()\n }\n },\n Math.max(1, limits.timeoutMs - wallUsed() + 1),\n )\n }\n\n // Look at the program's promise: done, failed, or still waiting on a timer / a file call.\n const settle = (): void => {\n while (!finished) {\n if (interrupted) {\n finish(timedOut())\n return\n }\n const state = ctx.getPromiseState(main)\n if (state.type === 'rejected') {\n finish(describe(state.error))\n return\n }\n if (state.type === 'pending') {\n if (hostTimers.size === 0 && pendingCalls === 0) {\n finish({\n name: 'Error',\n message:\n 'the program awaits a promise that can never settle (nothing is left to run)',\n })\n }\n return\n }\n if (mainKind !== 'value') {\n main = ctx.getProp(state.value, mainKind === 'script' ? 'value' : 'default')\n mainKind = 'value'\n continue\n }\n if (!state.notAPromise) {\n main = state.value\n continue\n }\n // Like Node, the run ends when nothing is left to run - not when the last line is reached.\n if (hostTimers.size > 0 || pendingCalls > 0) {\n return\n }\n const max = Math.max(200, limits.maxOutputChars - outChars)\n const r = ctx.callFunction(\n internals.serialize,\n ctx.undefined,\n state.value,\n ctx.newNumber(max),\n )\n if (r.error) {\n finish(describe(r.error))\n return\n }\n const text = ctx.getString(r.value) as string\n if (text === '') {\n finish()\n } else if (text[0] === 'T') {\n truncated = true\n finish(undefined, { value: clip(text.slice(1), max) })\n } else {\n truncated ||= text[0] === 'C'\n finish(undefined, { value: JSON.parse(text.slice(1)) })\n }\n return\n }\n }\n\n // Every entry into the guest goes through here: timed, drained, then judged.\n const enter = (fn: () => void): void => {\n if (finished) {\n return\n }\n entryAt = Date.now()\n try {\n fn()\n while (!finished && !interrupted) {\n const jobs = rt.executePendingJobs()\n if (jobs.error) {\n const error = describe(jobs.error)\n cpuMs += Date.now() - entryAt\n entryAt = 0\n finish(error)\n return\n }\n if (!rt.hasPendingJob()) {\n break\n }\n }\n cpuMs += Date.now() - entryAt\n entryAt = 0\n settle()\n } catch (err) {\n cpuMs += Date.now() - entryAt\n entryAt = 0\n engineFailure(err)\n }\n }\n\n const guestError = (name: string, message: string): Error =>\n Object.assign(new Error(message), { name })\n\n const host = ctx.newObject()\n const expose = (name: string, fn: (...args: Any[]) => Any): void => {\n ctx.setProp(host, name, ctx.newFunction(name, fn))\n }\n expose('log', (levelHandle, textHandle) => {\n if (outChars >= limits.maxOutputChars) {\n truncated = true\n return\n }\n const level = ctx.getString(levelHandle) as string\n let line = `${level ? `[${level}] ` : ''}${ctx.getString(textHandle) as string}\\n`\n if (outChars + line.length > limits.maxOutputChars) {\n line = line.slice(0, limits.maxOutputChars - outChars)\n truncated = true\n }\n out.push(line)\n outChars += line.length\n })\n expose('timer', (idHandle, msHandle) => {\n const id = ctx.getNumber(idHandle) as number\n const ms = ctx.getNumber(msHandle) as number\n const previous = hostTimers.get(id)\n if (previous !== undefined) {\n clearTimeout(previous)\n } else if (hostTimers.size >= MAX_TIMERS) {\n throw guestError('RangeError', 'too many timers')\n }\n hostTimers.set(\n id,\n setTimeout(\n () => {\n hostTimers.delete(id)\n enter(() => {\n const r = ctx.callFunction(internals.fire, ctx.undefined, ctx.newNumber(id))\n if (r.error) {\n // An exception nobody caught in a timer callback ends the run, as it would a process.\n finish(describe(r.error))\n }\n })\n },\n // A timer past the deadline never fires: the watchdog ends the run first.\n Math.min(Math.max(0, ms), limits.timeoutMs + 1),\n ),\n )\n })\n expose('clear', (idHandle) => {\n const id = ctx.getNumber(idHandle) as number\n const t = hostTimers.get(id)\n if (t !== undefined) {\n clearTimeout(t)\n hostTimers.delete(id)\n }\n })\n expose('call', (opHandle, argsHandle) => {\n const op = ctx.getString(opHandle) as string\n if (!hostOps.includes(op as SandboxHostOp) || !options.hostCall) {\n throw guestError('Error', `fs.${clip(op, 40)} is not available in this sandbox`)\n }\n if ((hostCalls += 1) > SANDBOX_MAX_HOST_CALLS) {\n throw guestError(\n 'RangeError',\n `too many file operations in one run (limit ${SANDBOX_MAX_HOST_CALLS})`,\n )\n }\n const args = JSON.parse(ctx.getString(argsHandle) as string) as unknown[]\n const deferred = ctx.newPromise()\n if (pendingCalls === 0) {\n waitingSince = Date.now()\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n watchdog = undefined\n }\n }\n pendingCalls += 1\n const done = (settleGuest: () => void): void => {\n pendingCalls -= 1\n if (pendingCalls === 0) {\n waitMs += Date.now() - waitingSince\n waitingSince = 0\n }\n if (finished) {\n return\n }\n armWatchdog()\n enter(settleGuest)\n }\n options.hostCall(op, args).then(\n (value) =>\n done(() => {\n const text = value === undefined ? '' : JSON.stringify(value)\n deferred.resolve(ctx.newString(text ?? ''))\n }),\n (err: unknown) =>\n done(() => {\n deferred.reject(\n ctx.newError({\n name: 'Error',\n message: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS),\n }),\n )\n }),\n )\n return deferred.handle\n })\n const load = (path: string): string => {\n if (!modules) {\n throw guestError('Error', `Cannot load \"${clip(path, 200)}\": this sandbox has no files`)\n }\n if (!Object.hasOwn(modules, path)) {\n throw guestError(\n 'Error',\n `Cannot load \"${clip(path, 200)}\": no such file in the workspace (a module must exist before the run and be named by a literal path)`,\n )\n }\n return modules[path]\n }\n const resolvePath = (base: string, spec: string): string => {\n try {\n return resolveModulePath(base, spec)\n } catch (err) {\n throw guestError('Error', err instanceof Error ? err.message : String(err))\n }\n }\n expose('resolve', (baseHandle, specHandle) =>\n ctx.newString(\n resolvePath(ctx.getString(baseHandle) as string, ctx.getString(specHandle) as string),\n ),\n )\n expose('compile', (pathHandle) => {\n const path = ctx.getString(pathHandle) as string\n const source = load(path)\n if (path.toLowerCase().endsWith('.json')) {\n return ctx.newString(source)\n }\n const r = ctx.evalCode(\n `(function (module, exports, require, __filename, __dirname) {${source}\\n})`,\n path,\n )\n if (r.error) {\n return { error: r.error }\n }\n return r.value\n })\n // `import` (static and dynamic). Always installed, so that `import('node:fs')` fails with a\n // sentence the model can act on instead of an engine default.\n rt.setModuleLoader(\n (path: string) => {\n try {\n if (path.startsWith(REFUSED)) {\n throw new Error(path.slice(REFUSED.length))\n }\n const source = load(path)\n return path.toLowerCase().endsWith('.json')\n ? `export default JSON.parse(${JSON.stringify(source)})`\n : source\n } catch (err) {\n return { error: err as Error }\n }\n },\n (base: string, spec: string) => {\n // A refusal travels as a name the loader then refuses with the same sentence (the\n // engine drops an error returned from here).\n try {\n return resolveModulePath(base, spec)\n } catch (err) {\n return `${REFUSED}${err instanceof Error ? err.message : String(err)}`\n }\n },\n )\n\n try {\n const boot = ctx.evalCode(BOOTSTRAP, BOOTSTRAP_FILE)\n if (boot.error) {\n finish({ name: 'SandboxError', message: 'the sandbox runtime failed to start' })\n return\n }\n const made = ctx.callFunction(\n boot.value,\n ctx.undefined,\n host,\n ctx\n .evalCode(\n `(${JSON.stringify({\n max: limits.maxOutputChars,\n nameMax: ERROR_NAME_CHARS,\n textMax: ERROR_TEXT_CHARS,\n maxTimers: MAX_TIMERS,\n maxCall: SANDBOX_MAX_FILE_CHARS + 2000,\n ops: hostOps,\n filename,\n })})`,\n BOOTSTRAP_FILE,\n )\n .unwrap(),\n )\n if (made.error) {\n finish({ name: 'SandboxError', message: 'the sandbox runtime failed to start' })\n return\n }\n internals = {\n fire: ctx.getProp(made.value, 'fire'),\n serialize: ctx.getProp(made.value, 'serialize'),\n describe: ctx.getProp(made.value, 'describe'),\n }\n } catch (err) {\n engineFailure(err)\n return\n }\n\n programAt = Date.now()\n options.onStart?.()\n armWatchdog()\n enter(() => {\n let evaluated = ctx.evalCode(request.code, filename, EVAL_SCRIPT_ASYNC)\n mainKind = 'script'\n // A script that does not compile has run nothing: when it is written as a module, run it as one.\n if (evaluated.error && !interrupted && looksLikeModule(request.code)) {\n evaluated = ctx.evalCode(request.code, filename, { type: 'module' })\n mainKind = 'module'\n }\n if (evaluated.error) {\n finish(describe(evaluated.error))\n return\n }\n main = evaluated.value\n })\n })\n}\n\n// ── What comes back ──────────────────────────────────────────────────────\n\nconst jsonSafe = (value: unknown, max: number): { value: unknown; cut: boolean } => {\n let text: string | undefined\n try {\n text = JSON.stringify(value)\n } catch {\n return { value: '[unserializable]', cut: true }\n }\n if (text === undefined) {\n return { value: undefined, cut: false }\n }\n if (text.length > max) {\n return { value: text.slice(0, max), cut: true }\n }\n // Re-parsed: what leaves is plain data, whatever was handed in.\n return { value: JSON.parse(text) as unknown, cut: false }\n}\n\n/**\n * The authoritative shape and size of a run's result. The engine already bounds what it\n * produces; this runs on the agent's side of the boundary and trusts none of it (a worker is\n * the guest's side).\n */\nexport const sanitizeSandboxResult = (raw: unknown, limits: ISandboxLimits): ISandboxResult => {\n const r = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n let truncated = r.truncated === true\n let stdout = typeof r.stdout === 'string' ? r.stdout : ''\n if (stdout.length > limits.maxOutputChars) {\n stdout = stdout.slice(0, limits.maxOutputChars)\n truncated = true\n }\n const result: ISandboxResult = { ok: r.ok === true, stdout, truncated, durationMs: 0 }\n if (Object.hasOwn(r, 'result') && r.result !== undefined) {\n const safe = jsonSafe(r.result, Math.max(200, limits.maxOutputChars - stdout.length))\n if (safe.value !== undefined) {\n result.result = safe.value\n }\n truncated ||= safe.cut\n }\n if (r.error && typeof r.error === 'object') {\n const e = r.error as Record<string, unknown>\n result.error = {\n name: clip(typeof e.name === 'string' ? e.name : 'Error', ERROR_NAME_CHARS),\n message: clip(typeof e.message === 'string' ? e.message : '', ERROR_TEXT_CHARS),\n ...(typeof e.stack === 'string' && e.stack ? { stack: clip(e.stack, ERROR_TEXT_CHARS) } : {}),\n }\n result.ok = false\n } else if (!result.ok) {\n result.error = { name: 'Error', message: 'the run failed' }\n }\n result.truncated = truncated\n result.durationMs =\n typeof r.durationMs === 'number' && Number.isFinite(r.durationMs) && r.durationMs >= 0\n ? Math.round(r.durationMs)\n : 0\n return result\n}\n\n// ── The worker protocol ──────────────────────────────────────────────────\n// The guest does not run on the agent's thread. One worker serves one run and is thrown away.\n\nexport type SandboxToWorker =\n | { type: 'run'; request: ISandboxRequest }\n | { type: 'host-result'; id: number; ok: boolean; value?: unknown; error?: string }\n\nexport type SandboxFromWorker =\n | { type: 'started' }\n | { type: 'host-call'; id: number; op: string; args: unknown[] }\n | { type: 'done'; result: unknown }\n | { type: 'failed'; code: 'peer-missing' | 'engine'; message: string }\n\n// A message channel as this file needs it; each package adapts its own worker type to it.\nexport interface ISandboxPort {\n post: (message: unknown) => void\n // `onClose` fires when the other side is gone (a worker that exited or crashed).\n listen: (onMessage: (message: unknown) => void, onClose?: (reason: string) => void) => void\n // The parent's side only: kill the worker.\n terminate?: () => void\n}\n\n/** The worker's side: load the engine, run what is posted, answer. */\nexport const serveSandbox = (port: ISandboxPort, loadLib: () => Promise<ISandboxLib>): void => {\n const waiting = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>()\n let seq = 0\n let busy = false\n const run = async (request: ISandboxRequest): Promise<void> => {\n let lib: ISandboxLib\n try {\n lib = await loadLib()\n } catch (err) {\n port.post({ type: 'failed', code: 'peer-missing', message: errorText(err) })\n return\n }\n try {\n const result = await runGuest(lib, request, {\n onStart: () => port.post({ type: 'started' }),\n hostCall: (op, args) =>\n new Promise((resolve, reject) => {\n const id = (seq += 1)\n waiting.set(id, { resolve, reject })\n port.post({ type: 'host-call', id, op, args })\n }),\n })\n port.post({ type: 'done', result })\n } catch (err) {\n port.post({ type: 'failed', code: 'engine', message: errorText(err) })\n }\n }\n port.listen((message) => {\n const m = message as SandboxToWorker\n if (m?.type === 'run' && !busy) {\n busy = true\n void run(m.request)\n } else if (m?.type === 'host-result') {\n const w = waiting.get(m.id)\n if (w) {\n waiting.delete(m.id)\n if (m.ok) {\n w.resolve(m.value)\n } else {\n w.reject(new Error(typeof m.error === 'string' ? m.error : 'the file operation failed'))\n }\n }\n }\n })\n}\n\nexport interface IRunInWorkerOptions {\n hostCall?: SandboxHostCall\n signal?: AbortSignal\n // How long the worker may take to load the engine before the run is given up (default 20 s).\n startupMs?: number\n // How far past `timeoutMs` the worker lives before it is terminated (default 1000 ms).\n graceMs?: number\n}\n\n/**\n * The agent's side: post one run to a fresh worker and wait for it - or kill it. The engine's\n * own interrupt handler is the soft stop; `terminate()` here is the hard one, and it does not\n * depend on anything the guest does. Rejects only when the sandbox itself is unavailable (the\n * optional peer is missing, the worker never started) or the run was aborted.\n */\nexport const runInWorker = (\n port: ISandboxPort,\n request: ISandboxRequest,\n options: IRunInWorkerOptions = {},\n): Promise<ISandboxResult> =>\n new Promise<ISandboxResult>((resolve, reject) => {\n const { limits } = request\n const startedAt = Date.now()\n const graceMs = options.graceMs ?? 1000\n let over = false\n let serving = 0\n let timer: ReturnType<typeof setTimeout> | undefined\n const stop = (): void => {\n over = true\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n options.signal?.removeEventListener('abort', onAbort)\n try {\n port.terminate?.()\n } catch {\n /* already gone */\n }\n }\n const end = (result: ISandboxResult): void => {\n if (over) {\n return\n }\n stop()\n resolve({ ...result, durationMs: Date.now() - startedAt })\n }\n const fail = (err: Error): void => {\n if (over) {\n return\n }\n stop()\n reject(err)\n }\n const failed = (name: string, message: string): ISandboxResult => ({\n ok: false,\n stdout: '',\n error: { name, message },\n truncated: false,\n durationMs: 0,\n })\n function onAbort(): void {\n fail(Object.assign(new Error('The run was aborted'), { name: 'AbortError' }))\n }\n const arm = (ms: number, onFire: () => void): void => {\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n timer = setTimeout(onFire, ms)\n }\n const armKill = (): void =>\n arm(limits.timeoutMs + graceMs, () =>\n end(\n failed(\n 'TimeoutError',\n `the run was killed after ${limits.timeoutMs} ms (timeoutMs): it did not stop by itself`,\n ),\n ),\n )\n if (options.signal?.aborted) {\n onAbort()\n return\n }\n options.signal?.addEventListener('abort', onAbort, { once: true })\n arm(options.startupMs ?? 20_000, () =>\n fail(new SandboxUnavailableError('the sandbox worker did not start in time')),\n )\n port.listen(\n (message) => {\n if (over) {\n return\n }\n const m = message as SandboxFromWorker\n switch (m?.type) {\n case 'started':\n armKill()\n break\n case 'host-call': {\n const id = m.id\n serving += 1\n // The clock does not run while the agent's side serves a call (it may be asking the user).\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n const answer = (reply: SandboxToWorker): void => {\n serving -= 1\n if (over) {\n return\n }\n if (serving === 0) {\n armKill()\n }\n port.post(reply)\n }\n const call = options.hostCall\n ? options.hostCall(String(m.op), Array.isArray(m.args) ? m.args : [])\n : Promise.reject(new Error('this sandbox has no files'))\n call.then(\n (value) => answer({ type: 'host-result', id, ok: true, value }),\n (err: unknown) =>\n answer({\n type: 'host-result',\n id,\n ok: false,\n error: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS),\n }),\n )\n break\n }\n case 'done':\n end(sanitizeSandboxResult(m.result, limits))\n break\n case 'failed':\n fail(\n m.code === 'peer-missing'\n ? sandboxPeerMissing(clip(String(m.message), 300))\n : new SandboxUnavailableError(\n `the sandbox engine failed: ${clip(String(m.message), 300)}`,\n ),\n )\n break\n }\n },\n (reason) =>\n end(failed('SandboxError', `the sandbox stopped unexpectedly: ${clip(reason, 300)}`)),\n )\n port.post({ type: 'run', request } satisfies SandboxToWorker)\n })\n\n// At most `size` runs at once; the rest wait their turn (each run is a worker and a heap).\nexport const createSandboxQueue = (size: number): (<T>(task: () => Promise<T>) => Promise<T>) => {\n let active = 0\n const waiting: (() => void)[] = []\n return async <T>(task: () => Promise<T>): Promise<T> => {\n if (active >= size) {\n await new Promise<void>((go) => waiting.push(go))\n }\n active += 1\n try {\n return await task()\n } finally {\n active -= 1\n waiting.shift()?.()\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcO,IAAM,cAAc;AA2B3B,IAAM,MAAM,OAAO;AAEZ,IAAM,mBAAmC;AAAA,EAC9C,WAAW;AAAA,EACX,kBAAkB,KAAK;AAAA,EACvB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAGO,IAAM,eAA+B;AAAA,EAC1C,WAAW;AAAA,EACX,kBAAkB,MAAM;AAAA,EACxB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAEA,IAAM,iBAAiC;AAAA,EACrC,WAAW;AAAA;AAAA,EAEX,kBAAkB,KAAK;AAAA,EACvB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAMO,IAAM,yBAAyB;AAC/B,IAAM,yBAAyB;AAC/B,IAAM,4BAA+C,CAAC,OAAO,QAAQ,OAAO;AAEnF,IAAM,aAAa;AAGnB,IAAM,oBAAoB,MAAM;AAChC,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AA6ElB,IAAM,uBAAuB,6JAA6J,WAAW;AAErM,IAAM,2BAA2B,iDAAiD,WAAW;AAEpG,IAAM,OAAO,CAAC,MAAc,QAAyB,KA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ACF;AAEA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AAKV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,oBAAmB;","names":[]}
|
package/dist/sandbox-worker.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudko.dev/agent-web",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.41",
|
|
4
4
|
"description": "Headless, configurable in-browser LLM agent on the Vercel AI SDK: multi-provider bring-your-own-key (OpenAI, Anthropic, Google, xAI, DeepSeek, gateway, openai-compatible) AND local WebGPU/WebLLM, native + prompted tool-calling, structured output, an encrypted IndexedDB token vault, and a plan → execute → replan → synthesize loop. UI-agnostic.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|