@dudko.dev/agent-web 0.0.40 → 0.0.42

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.
Files changed (40) hide show
  1. package/README.md +305 -22
  2. package/dist/agent-web.js +169 -161
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/chunk-2MLHZ6LQ.js +510 -0
  5. package/dist/chunk-2MLHZ6LQ.js.map +1 -0
  6. package/dist/{chunk-TZITKUFW.js → chunk-DAREMCXF.js} +152 -20
  7. package/dist/chunk-DAREMCXF.js.map +1 -0
  8. package/dist/{chunk-V3JOK7EW.js → chunk-YPCHD6DV.js} +4 -2
  9. package/dist/chunk-YPCHD6DV.js.map +1 -0
  10. package/dist/chunk-ZSZSSJS4.js +973 -0
  11. package/dist/chunk-ZSZSSJS4.js.map +1 -0
  12. package/dist/elicitation-DS-84_bF.d.cts +680 -0
  13. package/dist/elicitation-DS-84_bF.d.ts +680 -0
  14. package/dist/index.cjs +1939 -225
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +692 -117
  17. package/dist/index.d.ts +692 -117
  18. package/dist/index.js +1325 -189
  19. package/dist/index.js.map +1 -1
  20. package/dist/mcp.cjs +2478 -49
  21. package/dist/mcp.cjs.map +1 -1
  22. package/dist/mcp.d.cts +291 -9
  23. package/dist/mcp.d.ts +291 -9
  24. package/dist/mcp.js +1578 -48
  25. package/dist/mcp.js.map +1 -1
  26. package/dist/{sandbox-KG6OUG24.js → sandbox-3VRX47UY.js} +21 -8
  27. package/dist/sandbox-3VRX47UY.js.map +1 -0
  28. package/dist/sandbox-worker.cjs +3 -1
  29. package/dist/sandbox-worker.cjs.map +1 -1
  30. package/dist/sandbox-worker.js +1 -1
  31. package/package.json +1 -1
  32. package/dist/chunk-A6ZJALLU.js +0 -254
  33. package/dist/chunk-A6ZJALLU.js.map +0 -1
  34. package/dist/chunk-CTXDKSDD.js +0 -39
  35. package/dist/chunk-CTXDKSDD.js.map +0 -1
  36. package/dist/chunk-TZITKUFW.js.map +0 -1
  37. package/dist/chunk-V3JOK7EW.js.map +0 -1
  38. package/dist/sandbox-KG6OUG24.js.map +0 -1
  39. package/dist/vault-BatBaRQP.d.cts +0 -36
  40. package/dist/vault-BatBaRQP.d.ts +0 -36
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sandbox/engine.ts"],"sourcesContent":["// 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":";AAcO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AA0B/B,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;AAGO,IAAM,sBAAsB;AAC5B,IAAM,iCAAiC;AAEvC,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,mBAAm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