@dudko.dev/agent-web 0.0.37 → 0.0.39
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 +179 -7
- package/dist/agent-web.js +315 -125
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-Y7OGKYE5.js → chunk-3V27UZT6.js} +35 -9
- package/dist/chunk-3V27UZT6.js.map +1 -0
- package/dist/chunk-A6ZJALLU.js +254 -0
- package/dist/chunk-A6ZJALLU.js.map +1 -0
- package/dist/chunk-CTXDKSDD.js +39 -0
- package/dist/chunk-CTXDKSDD.js.map +1 -0
- package/dist/chunk-TZITKUFW.js +800 -0
- package/dist/chunk-TZITKUFW.js.map +1 -0
- package/dist/chunk-V3JOK7EW.js +929 -0
- package/dist/chunk-V3JOK7EW.js.map +1 -0
- package/dist/index.cjs +7253 -2159
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1714 -324
- package/dist/index.d.ts +1714 -324
- package/dist/index.js +3832 -862
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +1031 -24
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +409 -13
- package/dist/mcp.d.ts +409 -13
- package/dist/mcp.js +918 -26
- package/dist/mcp.js.map +1 -1
- package/dist/sandbox-KG6OUG24.js +269 -0
- package/dist/sandbox-KG6OUG24.js.map +1 -0
- package/dist/sandbox-worker.cjs +745 -0
- package/dist/sandbox-worker.cjs.map +1 -0
- package/dist/sandbox-worker.d.cts +37 -0
- package/dist/sandbox-worker.d.ts +37 -0
- package/dist/sandbox-worker.js +27 -0
- package/dist/sandbox-worker.js.map +1 -0
- package/dist/{webllm-PCPDLDQA.js → webllm-BEL5A4OF.js} +2 -2
- package/package.json +23 -4
- package/dist/chunk-CPSDKXO6.js +0 -132
- package/dist/chunk-CPSDKXO6.js.map +0 -1
- package/dist/chunk-Y7OGKYE5.js.map +0 -1
- /package/dist/{webllm-PCPDLDQA.js.map → webllm-BEL5A4OF.js.map} +0 -0
|
@@ -0,0 +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,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,GAAG,IAAI;AAE9F,IAAM,YAAY,CAAC,QAAyB;AAC1C,MAAI,eAAe,OAAO;AACxB,WAAO,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO;AAAA,EACpC;AACA,SAAO,OAAO,QAAQ,WAAW,MAAM;AACzC;AAEA,IAAM,UAAU,CAAC,SAAyB;AACxC,QAAM,IAAI,KAAK,YAAY,GAA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,UAAU,SAAS,UAAU,GAAG,EAAE,CAAC;AAAA,IACvE;AAAA,EACF;AACA,OAAK,OAAO,CAAC,YAAY;AACvB,UAAM,IAAI;AACV,QAAI,GAAG,SAAS,SAAS,CAAC,MAAM;AAC9B,aAAO;AACP,WAAK,IAAI,EAAE,OAAO;AAAA,IACpB,WAAW,GAAG,SAAS,eAAe;AACpC,YAAM,IAAI,QAAQ,IAAI,EAAE,EAAE;AAC1B,UAAI,GAAG;AACL,gBAAQ,OAAO,EAAE,EAAE;AACnB,YAAI,EAAE,IAAI;AACR,YAAE,QAAQ,EAAE,KAAK;AAAA,QACnB,OAAO;AACL,YAAE,OAAO,IAAI,MAAM,OAAO,EAAE,UAAU,WAAW,EAAE,QAAQ,2BAA2B,CAAC;AAAA,QACzF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;AD58BO,IAAM,qBAAqB,CAAC,OAA4B,CAAC,MAAY;AAC1E,QAAM,QAAQ,KAAK,SAAU;AAC7B;AAAA,IACE;AAAA,MACE,MAAM,CAAC,YAAY,MAAM,YAAY,OAAO;AAAA,MAC5C,QAAQ,CAAC,cAAc;AACrB,cAAM,iBAAiB,WAAW,CAAC,OAA0B,UAAU,GAAG,IAAI,CAAC;AAC9E,QAAC,MAAiC,QAAQ;AAAA,MAC7C;AAAA,IACF;AAAA,IACA,YACG,OAAO,KAAK,SACT,KAAK,OAAO,IACZ,OAAO,oBAAoB;AAAA,EACnC;AACF;AAEA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AAKV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,oBAAmB;","names":[]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Web Worker side of the sandbox (`config.sandbox.worker`): the entry
|
|
3
|
+
* `@dudko.dev/agent-web/sandbox-worker`. Loaded as a worker it serves by itself:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* // Vite
|
|
7
|
+
* import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'
|
|
8
|
+
* createAgent({ model, sandbox: { worker: () => new SandboxWorker() } })
|
|
9
|
+
* // webpack 5 and other bundlers that follow `new URL(..., import.meta.url)`
|
|
10
|
+
* createAgent({
|
|
11
|
+
* model,
|
|
12
|
+
* sandbox: {
|
|
13
|
+
* worker: () =>
|
|
14
|
+
* new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' }),
|
|
15
|
+
* },
|
|
16
|
+
* })
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* One worker serves one run and is terminated by the agent. The engine (the optional peer
|
|
20
|
+
* `quickjs-emscripten`) is imported here with a literal specifier, so the host's bundler puts
|
|
21
|
+
* it - and its .wasm file - into the worker's chunk and nowhere else.
|
|
22
|
+
*/
|
|
23
|
+
/** The slice of a worker scope / MessagePort this needs. */
|
|
24
|
+
interface SandboxWorkerScope {
|
|
25
|
+
postMessage(message: unknown): void;
|
|
26
|
+
addEventListener(type: string, listener: (ev: any) => void): void;
|
|
27
|
+
}
|
|
28
|
+
interface ServeSandboxOptions {
|
|
29
|
+
/** The message endpoint (default: the worker global scope). */
|
|
30
|
+
scope?: SandboxWorkerScope;
|
|
31
|
+
/** Load the engine yourself (default: `import('quickjs-emscripten')`). */
|
|
32
|
+
engine?: () => Promise<unknown>;
|
|
33
|
+
}
|
|
34
|
+
declare const serveSandboxWorker: (opts?: ServeSandboxOptions) => void;
|
|
35
|
+
|
|
36
|
+
export { serveSandboxWorker };
|
|
37
|
+
export type { SandboxWorkerScope, ServeSandboxOptions };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Web Worker side of the sandbox (`config.sandbox.worker`): the entry
|
|
3
|
+
* `@dudko.dev/agent-web/sandbox-worker`. Loaded as a worker it serves by itself:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* // Vite
|
|
7
|
+
* import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'
|
|
8
|
+
* createAgent({ model, sandbox: { worker: () => new SandboxWorker() } })
|
|
9
|
+
* // webpack 5 and other bundlers that follow `new URL(..., import.meta.url)`
|
|
10
|
+
* createAgent({
|
|
11
|
+
* model,
|
|
12
|
+
* sandbox: {
|
|
13
|
+
* worker: () =>
|
|
14
|
+
* new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' }),
|
|
15
|
+
* },
|
|
16
|
+
* })
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* One worker serves one run and is terminated by the agent. The engine (the optional peer
|
|
20
|
+
* `quickjs-emscripten`) is imported here with a literal specifier, so the host's bundler puts
|
|
21
|
+
* it - and its .wasm file - into the worker's chunk and nowhere else.
|
|
22
|
+
*/
|
|
23
|
+
/** The slice of a worker scope / MessagePort this needs. */
|
|
24
|
+
interface SandboxWorkerScope {
|
|
25
|
+
postMessage(message: unknown): void;
|
|
26
|
+
addEventListener(type: string, listener: (ev: any) => void): void;
|
|
27
|
+
}
|
|
28
|
+
interface ServeSandboxOptions {
|
|
29
|
+
/** The message endpoint (default: the worker global scope). */
|
|
30
|
+
scope?: SandboxWorkerScope;
|
|
31
|
+
/** Load the engine yourself (default: `import('quickjs-emscripten')`). */
|
|
32
|
+
engine?: () => Promise<unknown>;
|
|
33
|
+
}
|
|
34
|
+
declare const serveSandboxWorker: (opts?: ServeSandboxOptions) => void;
|
|
35
|
+
|
|
36
|
+
export { serveSandboxWorker };
|
|
37
|
+
export type { SandboxWorkerScope, ServeSandboxOptions };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {
|
|
2
|
+
serveSandbox
|
|
3
|
+
} from "./chunk-V3JOK7EW.js";
|
|
4
|
+
|
|
5
|
+
// src/sandbox/worker.ts
|
|
6
|
+
var serveSandboxWorker = (opts = {}) => {
|
|
7
|
+
const scope = opts.scope ?? globalThis;
|
|
8
|
+
serveSandbox(
|
|
9
|
+
{
|
|
10
|
+
post: (message) => scope.postMessage(message),
|
|
11
|
+
listen: (onMessage) => {
|
|
12
|
+
scope.addEventListener("message", (ev) => onMessage(ev.data));
|
|
13
|
+
scope.start?.();
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
async () => await (opts.engine ? opts.engine() : import("quickjs-emscripten"))
|
|
17
|
+
);
|
|
18
|
+
};
|
|
19
|
+
var inWorker = () => {
|
|
20
|
+
const g = globalThis;
|
|
21
|
+
return typeof g.WorkerGlobalScope !== "undefined" && typeof g.document === "undefined";
|
|
22
|
+
};
|
|
23
|
+
if (inWorker()) serveSandboxWorker();
|
|
24
|
+
export {
|
|
25
|
+
serveSandboxWorker
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=sandbox-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/worker.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"],"mappings":";;;;;AAsCO,IAAM,qBAAqB,CAAC,OAA4B,CAAC,MAAY;AAC1E,QAAM,QAAQ,KAAK,SAAU;AAC7B;AAAA,IACE;AAAA,MACE,MAAM,CAAC,YAAY,MAAM,YAAY,OAAO;AAAA,MAC5C,QAAQ,CAAC,cAAc;AACrB,cAAM,iBAAiB,WAAW,CAAC,OAA0B,UAAU,GAAG,IAAI,CAAC;AAC9E,QAAC,MAAiC,QAAQ;AAAA,MAC7C;AAAA,IACF;AAAA,IACA,YACG,OAAO,KAAK,SACT,KAAK,OAAO,IACZ,OAAO,oBAAoB;AAAA,EACnC;AACF;AAEA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AAKV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,oBAAmB;","names":[]}
|
|
@@ -3,11 +3,11 @@ import {
|
|
|
3
3
|
isWebGPUAvailable,
|
|
4
4
|
preloadWebLLMModel,
|
|
5
5
|
unloadWebLLMModel
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-3V27UZT6.js";
|
|
7
7
|
export {
|
|
8
8
|
createWebLLMModel,
|
|
9
9
|
isWebGPUAvailable,
|
|
10
10
|
preloadWebLLMModel,
|
|
11
11
|
unloadWebLLMModel
|
|
12
12
|
};
|
|
13
|
-
//# sourceMappingURL=webllm-
|
|
13
|
+
//# sourceMappingURL=webllm-BEL5A4OF.js.map
|
package/package.json
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudko.dev/agent-web",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.39",
|
|
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
|
-
"sideEffects":
|
|
6
|
+
"sideEffects": [
|
|
7
|
+
"./dist/sandbox-worker.js",
|
|
8
|
+
"./dist/sandbox-worker.cjs"
|
|
9
|
+
],
|
|
7
10
|
"main": "./dist/index.cjs",
|
|
8
11
|
"module": "./dist/index.js",
|
|
9
12
|
"types": "./dist/index.d.ts",
|
|
@@ -40,6 +43,16 @@
|
|
|
40
43
|
"default": "./dist/webmcp.cjs"
|
|
41
44
|
}
|
|
42
45
|
},
|
|
46
|
+
"./sandbox-worker": {
|
|
47
|
+
"import": {
|
|
48
|
+
"types": "./dist/sandbox-worker.d.ts",
|
|
49
|
+
"default": "./dist/sandbox-worker.js"
|
|
50
|
+
},
|
|
51
|
+
"require": {
|
|
52
|
+
"types": "./dist/sandbox-worker.d.cts",
|
|
53
|
+
"default": "./dist/sandbox-worker.cjs"
|
|
54
|
+
}
|
|
55
|
+
},
|
|
43
56
|
"./bundle": {
|
|
44
57
|
"types": "./dist/index.d.ts",
|
|
45
58
|
"import": "./dist/agent-web.js"
|
|
@@ -141,7 +154,8 @@
|
|
|
141
154
|
"@browser-ai/core": "^3.0.0",
|
|
142
155
|
"@browser-ai/web-llm": "^3.0.0",
|
|
143
156
|
"@mlc-ai/web-llm": ">=0.2.70",
|
|
144
|
-
"@modelcontextprotocol/sdk": "^1.30.0"
|
|
157
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
158
|
+
"quickjs-emscripten": "^0.32.0"
|
|
145
159
|
},
|
|
146
160
|
"peerDependenciesMeta": {
|
|
147
161
|
"@ai-sdk/openai": {
|
|
@@ -173,6 +187,9 @@
|
|
|
173
187
|
},
|
|
174
188
|
"@modelcontextprotocol/sdk": {
|
|
175
189
|
"optional": true
|
|
190
|
+
},
|
|
191
|
+
"quickjs-emscripten": {
|
|
192
|
+
"optional": true
|
|
176
193
|
}
|
|
177
194
|
},
|
|
178
195
|
"devDependencies": {
|
|
@@ -189,8 +206,10 @@
|
|
|
189
206
|
"@types/node": "^22.9.0",
|
|
190
207
|
"fake-indexeddb": "^6.2.8",
|
|
191
208
|
"prettier": "^3.10.1",
|
|
209
|
+
"quickjs-emscripten": "^0.32.0",
|
|
192
210
|
"tsup": "^9.0.0",
|
|
193
|
-
"typescript": "^6.0.3"
|
|
211
|
+
"typescript": "^6.0.3",
|
|
212
|
+
"@dudko.dev/test-servers": "0.0.0"
|
|
194
213
|
},
|
|
195
214
|
"scripts": {
|
|
196
215
|
"build": "tsup",
|
package/dist/chunk-CPSDKXO6.js
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
// src/storage/db.ts
|
|
2
|
-
import { openDB } from "idb";
|
|
3
|
-
var KEYS_STORE = "keys";
|
|
4
|
-
var SECRETS_STORE = "secrets";
|
|
5
|
-
var SESSIONS_STORE = "sessions";
|
|
6
|
-
var FILES_STORE = "files";
|
|
7
|
-
var RUNS_STORE = "runs";
|
|
8
|
-
var DB_VERSION = 3;
|
|
9
|
-
var cache = /* @__PURE__ */ new Map();
|
|
10
|
-
var openAgentWebDB = (opts = {}) => {
|
|
11
|
-
const name = opts.dbName ?? "agent-web";
|
|
12
|
-
let p = cache.get(name);
|
|
13
|
-
if (!p) {
|
|
14
|
-
p = openDB(name, DB_VERSION, {
|
|
15
|
-
upgrade(db) {
|
|
16
|
-
if (!db.objectStoreNames.contains(KEYS_STORE)) db.createObjectStore(KEYS_STORE);
|
|
17
|
-
if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE);
|
|
18
|
-
if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE);
|
|
19
|
-
if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE);
|
|
20
|
-
if (!db.objectStoreNames.contains(RUNS_STORE)) db.createObjectStore(RUNS_STORE);
|
|
21
|
-
}
|
|
22
|
-
});
|
|
23
|
-
cache.set(name, p);
|
|
24
|
-
p.catch(() => {
|
|
25
|
-
if (cache.get(name) === p) cache.delete(name);
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
return p;
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
// src/secrets/crypto.ts
|
|
32
|
-
var KEY_ID = "vault-key-v1";
|
|
33
|
-
var webcrypto = () => {
|
|
34
|
-
const c = globalThis.crypto;
|
|
35
|
-
if (!c?.subtle || !c.getRandomValues) {
|
|
36
|
-
throw new Error("WebCrypto (crypto.subtle) is unavailable in this environment");
|
|
37
|
-
}
|
|
38
|
-
return c;
|
|
39
|
-
};
|
|
40
|
-
var loadOrCreateKey = async (dbName) => {
|
|
41
|
-
const db = await openAgentWebDB({ dbName });
|
|
42
|
-
const existing = await db.get(KEYS_STORE, KEY_ID);
|
|
43
|
-
if (existing) return existing;
|
|
44
|
-
const key = await webcrypto().subtle.generateKey(
|
|
45
|
-
{ name: "AES-GCM", length: 256 },
|
|
46
|
-
/* extractable */
|
|
47
|
-
false,
|
|
48
|
-
["encrypt", "decrypt"]
|
|
49
|
-
);
|
|
50
|
-
const tx = db.transaction(KEYS_STORE, "readwrite");
|
|
51
|
-
const winner = await tx.store.get(KEY_ID);
|
|
52
|
-
if (winner) {
|
|
53
|
-
await tx.done;
|
|
54
|
-
return winner;
|
|
55
|
-
}
|
|
56
|
-
await tx.store.put(key, KEY_ID);
|
|
57
|
-
await tx.done;
|
|
58
|
-
return key;
|
|
59
|
-
};
|
|
60
|
-
var keyCache = /* @__PURE__ */ new Map();
|
|
61
|
-
var getOrCreateVaultKey = (dbName) => {
|
|
62
|
-
const cacheKey = dbName ?? "agent-web";
|
|
63
|
-
let p = keyCache.get(cacheKey);
|
|
64
|
-
if (!p) {
|
|
65
|
-
p = loadOrCreateKey(dbName);
|
|
66
|
-
keyCache.set(cacheKey, p);
|
|
67
|
-
p.catch(() => {
|
|
68
|
-
if (keyCache.get(cacheKey) === p) keyCache.delete(cacheKey);
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
return p;
|
|
72
|
-
};
|
|
73
|
-
var textEncoder = new TextEncoder();
|
|
74
|
-
var textDecoder = new TextDecoder();
|
|
75
|
-
var encryptJSON = async (key, value) => {
|
|
76
|
-
const c = webcrypto();
|
|
77
|
-
const iv = c.getRandomValues(new Uint8Array(12));
|
|
78
|
-
const data = textEncoder.encode(JSON.stringify(value));
|
|
79
|
-
const ciphertext = await c.subtle.encrypt({ name: "AES-GCM", iv }, key, data);
|
|
80
|
-
return { iv, ciphertext };
|
|
81
|
-
};
|
|
82
|
-
var decryptJSON = async (key, blob) => {
|
|
83
|
-
const iv = new Uint8Array(blob.iv);
|
|
84
|
-
const plain = await webcrypto().subtle.decrypt({ name: "AES-GCM", iv }, key, blob.ciphertext);
|
|
85
|
-
return JSON.parse(textDecoder.decode(plain));
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
// src/secrets/vault.ts
|
|
89
|
-
var IndexedDBVault = class {
|
|
90
|
-
dbName;
|
|
91
|
-
constructor(opts = {}) {
|
|
92
|
-
this.dbName = opts.dbName;
|
|
93
|
-
}
|
|
94
|
-
key() {
|
|
95
|
-
return getOrCreateVaultKey(this.dbName);
|
|
96
|
-
}
|
|
97
|
-
/** Encrypt and store a secret string under `id`. */
|
|
98
|
-
async setSecret(id, value) {
|
|
99
|
-
const blob = await encryptJSON(await this.key(), value);
|
|
100
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
101
|
-
await db.put(SECRETS_STORE, blob, id);
|
|
102
|
-
}
|
|
103
|
-
/** Fetch and decrypt a secret, or undefined if absent. */
|
|
104
|
-
async getSecret(id) {
|
|
105
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
106
|
-
const blob = await db.get(SECRETS_STORE, id);
|
|
107
|
-
if (!blob) return void 0;
|
|
108
|
-
return decryptJSON(await this.key(), blob);
|
|
109
|
-
}
|
|
110
|
-
async deleteSecret(id) {
|
|
111
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
112
|
-
await db.delete(SECRETS_STORE, id);
|
|
113
|
-
}
|
|
114
|
-
async listSecretIds() {
|
|
115
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
116
|
-
return (await db.getAllKeys(SECRETS_STORE)).map(String);
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
export {
|
|
121
|
-
KEYS_STORE,
|
|
122
|
-
SECRETS_STORE,
|
|
123
|
-
SESSIONS_STORE,
|
|
124
|
-
FILES_STORE,
|
|
125
|
-
RUNS_STORE,
|
|
126
|
-
openAgentWebDB,
|
|
127
|
-
getOrCreateVaultKey,
|
|
128
|
-
encryptJSON,
|
|
129
|
-
decryptJSON,
|
|
130
|
-
IndexedDBVault
|
|
131
|
-
};
|
|
132
|
-
//# sourceMappingURL=chunk-CPSDKXO6.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/db.ts","../src/secrets/crypto.ts","../src/secrets/vault.ts"],"sourcesContent":["import { openDB, type IDBPDatabase } from 'idb'\n\nexport interface AgentWebDBOptions {\n /** Database name (default 'agent-web'). Use a distinct name to isolate apps. */\n dbName?: string\n}\n\nexport const KEYS_STORE = 'keys'\nexport const SECRETS_STORE = 'secrets'\nexport const SESSIONS_STORE = 'sessions'\nexport const FILES_STORE = 'files'\nexport const RUNS_STORE = 'runs'\n\n// v1: keys, secrets, sessions. v2: + files (the virtual file system). v3: + runs (checkpoints).\nconst DB_VERSION = 3\n\nlet cache = new Map<string, Promise<IDBPDatabase>>()\n\n/**\n * The single owner of the IndexedDB database. Every persistent store — the\n * non-extractable crypto key, encrypted secrets, and session transcripts —\n * lives under ONE database name + version. Centralising `openDB` here prevents\n * the classic bug where two modules open the same DB name with different store\n * sets and the second call throws a VersionError.\n */\nexport const openAgentWebDB = (opts: AgentWebDBOptions = {}): Promise<IDBPDatabase> => {\n const name = opts.dbName ?? 'agent-web'\n let p = cache.get(name)\n if (!p) {\n p = openDB(name, DB_VERSION, {\n upgrade(db) {\n // Idempotent by store: an existing v1 database gains only what it lacks.\n if (!db.objectStoreNames.contains(KEYS_STORE)) db.createObjectStore(KEYS_STORE)\n if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE)\n if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE)\n if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE)\n if (!db.objectStoreNames.contains(RUNS_STORE)) db.createObjectStore(RUNS_STORE)\n },\n })\n cache.set(name, p)\n // A failed open (private mode, storage denied) must not stay cached, or\n // every later call would replay the same rejection forever.\n p.catch(() => {\n if (cache.get(name) === p) cache.delete(name)\n })\n }\n return p\n}\n\n/** Test hook: drop cached connections so a fresh (e.g. fake-indexeddb) DB is opened. */\nexport const _resetDBCache = (): void => {\n cache = new Map()\n}\n","import { KEYS_STORE, openAgentWebDB } from '../storage/db.js'\n\nconst KEY_ID = 'vault-key-v1'\n\nconst webcrypto = (): Crypto => {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (!c?.subtle || !c.getRandomValues) {\n throw new Error('WebCrypto (crypto.subtle) is unavailable in this environment')\n }\n return c\n}\n\nconst loadOrCreateKey = async (dbName?: string): Promise<CryptoKey> => {\n const db = await openAgentWebDB({ dbName })\n const existing = (await db.get(KEYS_STORE, KEY_ID)) as CryptoKey | undefined\n if (existing) return existing\n const key = await webcrypto().subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n /* extractable */ false,\n ['encrypt', 'decrypt'],\n )\n // Double-check inside one readwrite transaction: another tab may have created\n // a key while ours was generating. Losing that race and overwriting would\n // leave the other tab's secrets permanently undecryptable.\n const tx = db.transaction(KEYS_STORE, 'readwrite')\n const winner = (await tx.store.get(KEY_ID)) as CryptoKey | undefined\n if (winner) {\n await tx.done\n return winner\n }\n await tx.store.put(key, KEY_ID)\n await tx.done\n return key\n}\n\nconst keyCache = new Map<string, Promise<CryptoKey>>()\n\n/**\n * Fetch (or lazily create) the vault's AES-GCM key. The key is generated\n * NON-EXTRACTABLE and stored as a live `CryptoKey` in IndexedDB — a CryptoKey\n * is structured-cloneable, so it persists across reloads WITHOUT its raw bytes\n * ever being exposed to JavaScript. Not even in-page script can read it out; it\n * can only be used to encrypt / decrypt. That is what makes at-rest storage of\n * the secrets meaningful (see IndexedDBVault's threat model).\n *\n * Concurrent callers share one in-flight promise per DB, and creation is\n * double-checked in a single IDB transaction, so two racing writers can never\n * end up encrypting under different keys.\n */\nexport const getOrCreateVaultKey = (dbName?: string): Promise<CryptoKey> => {\n const cacheKey = dbName ?? 'agent-web'\n let p = keyCache.get(cacheKey)\n if (!p) {\n p = loadOrCreateKey(dbName)\n keyCache.set(cacheKey, p)\n p.catch(() => {\n if (keyCache.get(cacheKey) === p) keyCache.delete(cacheKey)\n })\n }\n return p\n}\n\nexport interface EncryptedBlob {\n /** 96-bit random IV, fresh per write. */\n iv: Uint8Array\n ciphertext: ArrayBuffer\n}\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n/** Encrypt a JSON-serialisable value with a fresh 96-bit IV (AES-GCM). */\nexport const encryptJSON = async (key: CryptoKey, value: unknown): Promise<EncryptedBlob> => {\n const c = webcrypto()\n const iv = c.getRandomValues(new Uint8Array(12))\n const data = textEncoder.encode(JSON.stringify(value))\n const ciphertext = await c.subtle.encrypt({ name: 'AES-GCM', iv }, key, data)\n return { iv, ciphertext }\n}\n\n/** Decrypt a blob produced by encryptJSON. Throws if the key or blob don't match. */\nexport const decryptJSON = async <T = unknown>(key: CryptoKey, blob: EncryptedBlob): Promise<T> => {\n // Copy the IV into a fresh ArrayBuffer-backed view: after a round-trip through\n // IndexedDB its element buffer is typed as ArrayBufferLike, which no longer\n // satisfies BufferSource under TS's stricter typed-array generics.\n const iv = new Uint8Array(blob.iv)\n const plain = await webcrypto().subtle.decrypt({ name: 'AES-GCM', iv }, key, blob.ciphertext)\n return JSON.parse(textDecoder.decode(plain)) as T\n}\n","import { openAgentWebDB, SECRETS_STORE } from '../storage/db.js'\nimport { decryptJSON, encryptJSON, getOrCreateVaultKey, type EncryptedBlob } from './crypto.js'\n\nexport interface VaultOptions {\n /** Database name, forwarded to the shared IDB owner (default 'agent-web'). */\n dbName?: string\n}\n\n/**\n * Encrypted key/value secret store backed by IndexedDB. Values are encrypted at\n * rest with the non-extractable AES-GCM vault key (see crypto.ts).\n *\n * ── THREAT MODEL (read before shipping any app-owned key to a browser) ──\n * This vault PROTECTS secrets **at rest** — an IndexedDB / disk dump yields\n * only ciphertext — and against **casual DevTools inspection** — no plaintext\n * key is stored, and the AES key cannot be exported even by in-page script.\n *\n * It does **NOT** defend against **active XSS on your origin**: any script that\n * already runs on the page can call `getSecret()`, or use the live `CryptoKey`\n * to decrypt. Browser storage is not a secrets manager.\n *\n * Therefore this vault is for the **end user's OWN key on their OWN device**\n * (bring-your-own-key). A shared, app-owned key must NEVER reach the client —\n * put it behind a server proxy (`ProviderModelSpec.baseURL`) or the Vercel AI\n * Gateway instead.\n */\nexport class IndexedDBVault {\n private readonly dbName?: string\n\n constructor(opts: VaultOptions = {}) {\n this.dbName = opts.dbName\n }\n\n private key(): Promise<CryptoKey> {\n return getOrCreateVaultKey(this.dbName)\n }\n\n /** Encrypt and store a secret string under `id`. */\n async setSecret(id: string, value: string): Promise<void> {\n const blob = await encryptJSON(await this.key(), value)\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.put(SECRETS_STORE, blob, id)\n }\n\n /** Fetch and decrypt a secret, or undefined if absent. */\n async getSecret(id: string): Promise<string | undefined> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n const blob = (await db.get(SECRETS_STORE, id)) as EncryptedBlob | undefined\n if (!blob) return undefined\n return decryptJSON<string>(await this.key(), blob)\n }\n\n async deleteSecret(id: string): Promise<void> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.delete(SECRETS_STORE, id)\n }\n\n async listSecretIds(): Promise<string[]> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n return (await db.getAllKeys(SECRETS_STORE)).map(String)\n }\n}\n"],"mappings":";AAAA,SAAS,cAAiC;AAOnC,IAAM,aAAa;AACnB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,aAAa;AAG1B,IAAM,aAAa;AAEnB,IAAI,QAAQ,oBAAI,IAAmC;AAS5C,IAAM,iBAAiB,CAAC,OAA0B,CAAC,MAA6B;AACrF,QAAM,OAAO,KAAK,UAAU;AAC5B,MAAI,IAAI,MAAM,IAAI,IAAI;AACtB,MAAI,CAAC,GAAG;AACN,QAAI,OAAO,MAAM,YAAY;AAAA,MAC3B,QAAQ,IAAI;AAEV,YAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,EAAG,IAAG,kBAAkB,UAAU;AAC9E,YAAI,CAAC,GAAG,iBAAiB,SAAS,aAAa,EAAG,IAAG,kBAAkB,aAAa;AACpF,YAAI,CAAC,GAAG,iBAAiB,SAAS,cAAc,EAAG,IAAG,kBAAkB,cAAc;AACtF,YAAI,CAAC,GAAG,iBAAiB,SAAS,WAAW,EAAG,IAAG,kBAA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AAE;AAC5C,QAAI,CAAC,KAAM,QAAO;AAClB,WAAO,YAAoB,MAAM,KAAK,IAAI,GAAG,IAAI;AAAA,EACnD;AAAA,EAEA,MAAM,aAAa,IAA2B;AAC5C,UAAM,KAAK,MAAM,eAAe,EAAE,QAAQ,KAAK,OAAO,CAAC;AACvD,UAAM,GAAG,OAAO,eAAe,EAAE;AAAA,EACnC;AAAA,EAEA,MAAM,gBAAmC;AACvC,UAAM,KAAK,MAAM,eAAe,EAAE,QAAQ,KAAK,OAAO,CAAC;AACvD,YAAQ,MAAM,GAAG,WAAW,aAAa,GAAG,IAAI,MAAM;AAAA,EACxD;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/providers/webllm.ts","../src/context-window.ts","../src/images.ts","../src/llm/generate.ts","../src/llm/util.ts","../src/memory/compress.ts"],"sourcesContent":["import { generateText, type LanguageModel } from 'ai'\nimport { withWebLLMContextWindow, type WebLLMAppConfigLike } from '../context-window.js'\n\n/** WebGPU feature-detect — WebLLM requires it. Call before offering local models. */\nexport const isWebGPUAvailable = (): boolean =>\n typeof navigator !== 'undefined' && 'gpu' in navigator\n\nexport interface WebLLMModelOptions {\n /**\n * Progress callback for weight download / engine init. `report.progress` is\n * 0..1. Forwarded to WebLLM's `initProgressCallback`.\n */\n initProgressCallback?: (report: { progress: number; text: string }) => void\n /**\n * Download the weights and initialize the engine NOW (default true).\n *\n * The underlying provider initializes lazily on the first generation — with\n * a multi-GB model that means the download would silently happen on the\n * user's first message, with `initProgressCallback` never firing at a moment\n * the host can show it. Preloading runs a 1-token warm-up so the returned\n * model is truly ready and progress is reported during creation. Re-creating\n * an already-downloaded model is fast (weights live in the browser cache).\n *\n * Set to `false` to keep the lazy behavior.\n */\n preload?: boolean\n /**\n * The context window to load the model with, in tokens. WebLLM loads its\n * prebuilt models with 4096 (to save VRAM), far below what Qwen3 or Llama\n * 3.x were trained on; a larger window costs KV-cache memory, not a new\n * download. Applied through `engineConfig.appConfig` (WebLLM's prebuilt\n * config with this model's `context_window_size` overridden) unless you pass\n * an `appConfig` of your own; see `withWebLLMContextWindow`.\n */\n contextWindowTokens?: number\n /** Any other @browser-ai/web-llm setting (temperature, worker handler, …). */\n [k: string]: unknown\n}\n\n/**\n * Force a model to download its weights and initialize its engine by running\n * a 1-token generation. Exposed for hosts that create models with\n * `preload: false` and want to warm them up later (e.g. behind their own UI).\n */\nexport const preloadWebLLMModel = async (model: LanguageModel): Promise<void> => {\n await generateText({ model, prompt: 'ok', maxOutputTokens: 1 })\n}\n\n/**\n * Best-effort release of a model's GPU memory (call when switching models —\n * an abandoned engine otherwise holds its buffers until the page reloads).\n *\n * `@browser-ai/web-llm` keeps its MLCEngine private and exposes no public\n * `unload()`, so this reaches into the instance defensively; it is a no-op on\n * an uninitialized model or if the provider's internals change shape.\n */\nexport const unloadWebLLMModel = async (model: LanguageModel): Promise<void> => {\n const engine = (model as { engine?: { unload?: () => Promise<void> } }).engine\n try {\n await engine?.unload?.()\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * Build an AI SDK `LanguageModel` backed by WebLLM (WebGPU) via the community\n * provider `@browser-ai/web-llm` (an optional peer, dynamically imported so it\n * is code-split and never loads until a local model is actually used). Accepts\n * any WebLLM prebuilt model id, e.g. \"Llama-3.2-3B-Instruct-q4f16_1-MLC\".\n *\n * By default the weights are downloaded eagerly with progress (see\n * `WebLLMModelOptions.preload`).\n */\nexport const createWebLLMModel = async (\n model: string,\n options?: WebLLMModelOptions,\n): Promise<LanguageModel> => {\n let mod: typeof import('@browser-ai/web-llm')\n try {\n mod = await import('@browser-ai/web-llm')\n } catch {\n throw new Error(\n 'Local models require \"@browser-ai/web-llm\" and its peer \"@mlc-ai/web-llm\". Install: npm install @browser-ai/web-llm @mlc-ai/web-llm',\n )\n }\n const { preload = true, contextWindowTokens, ...settings } = options ?? {}\n if (contextWindowTokens) {\n const engineConfig = (settings.engineConfig ?? {}) as { appConfig?: WebLLMAppConfigLike }\n let base = engineConfig.appConfig\n if (!base) {\n try {\n const spec = '@mlc-ai/web-llm'\n base = (\n (await import(/* webpackIgnore: true */ /* @vite-ignore */ spec)) as {\n prebuiltAppConfig: WebLLMAppConfigLike\n }\n ).prebuiltAppConfig\n } catch {\n throw new Error(\n 'contextWindowTokens needs \"@mlc-ai/web-llm\" (for its prebuilt model list), or pass engineConfig.appConfig yourself.',\n )\n }\n }\n settings.engineConfig = {\n ...engineConfig,\n appConfig: withWebLLMContextWindow(base, model, contextWindowTokens),\n }\n }\n // webLLM(modelId, settings) returns a LanguageModel. The model id is a strict\n // union in the provider's types; we accept any string and cast at the seam.\n const languageModel = mod.webLLM(\n model as Parameters<typeof mod.webLLM>[0],\n settings as Parameters<typeof mod.webLLM>[1],\n )\n if (preload) await preloadWebLLMModel(languageModel)\n return languageModel\n}\n","import { asSchema, type ToolSet } from 'ai'\nimport { modelLabel } from './images.js'\nimport {\n estimateTokens,\n type CompactionConfig,\n type ResolvedCompaction,\n} from './memory/compress.js'\n\n/**\n * The model's context window is a hard limit: a prompt that does not fit is\n * refused outright (WebLLM: \"Prompt tokens exceed context window size\"). The\n * agent sizes everything that grows — compaction thresholds, tool-result\n * clearing, the cap on one tool result, whether tools are listed or searched —\n * from the window, so it has to be the model's real one.\n *\n * Cloud windows are large and the host states them (`compaction.\n * contextWindowTokens`); a local WebLLM model's window is small (4096 tokens\n * by default — WebLLM's choice to save VRAM, not the model's limit) and is read\n * from the model itself.\n */\n\ninterface WebLLMRecordLike {\n model_id: string\n overrides?: { context_window_size?: number } & Record<string, unknown>\n}\n\n/** The shape of a WebLLM `AppConfig` this module touches. */\nexport interface WebLLMAppConfigLike {\n model_list: WebLLMRecordLike[]\n}\n\n/** WebLLM's default window for its prebuilt models. */\nexport const WEBLLM_DEFAULT_CONTEXT_WINDOW = 4096\n\n/**\n * A copy of a WebLLM app config (e.g. `prebuiltAppConfig` from\n * `@mlc-ai/web-llm`) with one model's context window set. Pass it as\n * `engineConfig.appConfig` when building the model: the weights are the same,\n * only the KV cache (VRAM) grows with the window. Models trained on long\n * contexts (Qwen3, Llama 3.x) take far more than the default 4096; models\n * trained on 4k (Llama 2) don't.\n */\nexport const withWebLLMContextWindow = <T extends WebLLMAppConfigLike>(\n appConfig: T,\n modelId: string,\n tokens: number,\n): T => ({\n ...appConfig,\n model_list: appConfig.model_list.map((r) =>\n r.model_id === modelId\n ? { ...r, overrides: { ...r.overrides, context_window_size: tokens } }\n : r,\n ),\n})\n\ninterface WebLLMModelLike {\n provider?: string\n modelId?: string\n engine?: {\n loadedModelIdToPipeline?: { get?: (id: string) => { contextWindowSize?: number } | undefined }\n }\n config?: { options?: { engineConfig?: { appConfig?: WebLLMAppConfigLike } } }\n}\n\n/**\n * The context window of a WebLLM model (`@browser-ai/web-llm`), or undefined\n * for any other model. Read from the loaded engine when it runs in this\n * thread, else from the app config it was built with, else WebLLM's defaults\n * (1024 for its \"-1k\" builds, 4096 otherwise). The provider keeps these\n * private, so this reaches in defensively.\n */\nexport const webLLMContextWindow = (model: unknown): number | undefined => {\n const m = model as WebLLMModelLike | undefined\n if (!m || typeof m !== 'object' || m.provider !== 'web-llm') return undefined\n const id = String(m.modelId ?? '')\n try {\n const live = m.engine?.loadedModelIdToPipeline?.get?.(id)?.contextWindowSize\n if (typeof live === 'number' && live > 0) return live\n } catch {\n /* the engine lives in a worker, or changed shape */\n }\n const record = m.config?.options?.engineConfig?.appConfig?.model_list?.find(\n (r) => r.model_id === id,\n )\n const configured = record?.overrides?.context_window_size\n if (typeof configured === 'number' && configured > 0) return configured\n return /-1k$/i.test(id) ? 1024 : WEBLLM_DEFAULT_CONTEXT_WINDOW\n}\n\n/**\n * The model's own context window when it can be known (local models), else\n * undefined: WebLLM's (see above), or the browser's built-in model's\n * (`@browser-ai/core` reports it once its session exists).\n */\nexport const contextWindowOf = (model: unknown): number | undefined => {\n const webllm = webLLMContextWindow(model)\n if (webllm !== undefined) return webllm\n const m = model as { provider?: string; getContextWindow?: () => number | undefined } | undefined\n if (m && typeof m === 'object' && m.provider === 'browser-ai') {\n try {\n const w = m.getContextWindow?.()\n return typeof w === 'number' && w > 0 ? w : undefined\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\n/**\n * Fit the compaction settings to the model's window: the window in use is the\n * configured one, never larger than the model's own, and every size derived\n * from it shrinks with it — also a size the host set for a larger window.\n */\nexport const fitCompactionToWindow = (\n resolved: ResolvedCompaction,\n configured: CompactionConfig | undefined,\n modelWindow: number | undefined,\n): ResolvedCompaction => {\n const window = Math.min(\n configured?.contextWindowTokens ?? modelWindow ?? resolved.contextWindowTokens,\n modelWindow ?? Infinity,\n )\n if (window === resolved.contextWindowTokens && modelWindow === undefined) return resolved\n const quarter = Math.floor(window / 4)\n const clearAfter = configured?.clearToolResultsAfterTokens\n return {\n ...resolved,\n contextWindowTokens: window,\n // A threshold the host set for a larger window comes down with the window: never past 95%\n // of what the model really has (the answer and a step's growth need the rest).\n thresholdTokens: Math.min(\n configured?.thresholdTokens ?? Math.floor(window * resolved.thresholdRatio),\n Math.floor(window * 0.95),\n ),\n // 0 = never stays never.\n clearToolResultsAfterTokens: clearAfter === 0 ? 0 : Math.min(clearAfter ?? quarter, quarter),\n // One result may take a quarter of the window (~4 chars per token).\n maxToolOutputChars:\n configured?.maxToolOutputChars === 0\n ? 0\n : Math.min(configured?.maxToolOutputChars ?? 20_000, window),\n // A small window holds fewer verbatim results.\n keepToolResults:\n configured?.keepToolResults ?? Math.max(1, Math.min(3, Math.floor(window / 8192))),\n }\n}\n\n/**\n * Estimated tokens of the tool definitions a model is sent (name, description,\n * JSON schema of the input) — for tools natively, or rendered into the prompt.\n */\nexport const toolDefinitionTokens = async (tools: ToolSet): Promise<number> => {\n const sizes = await Promise.all(\n Object.entries(tools).map(async ([name, t]) => {\n let parameters: unknown\n try {\n parameters = await asSchema(t.inputSchema as never).jsonSchema\n } catch {\n parameters = undefined\n }\n return estimateTokens(JSON.stringify({ name, description: t.description ?? '', parameters }))\n }),\n )\n return sizes.reduce((a, b) => a + b, 0)\n}\n\n/** What every call carries whatever the transcript: stage instructions, the goal, the plan, the state. */\nexport const BASE_PROMPT_TOKENS = 1500\n/** Under tool search the model is sent only the built-ins and the tools found so far. */\nexport const SEARCH_TOOLS_ALLOWANCE = 3000\n\n/**\n * The tokens of a call's prompt that do not come from the transcript or the step log - the\n * stage instructions, the tool definitions, the skills - so that compaction can judge how full the\n * window really is (history + log alone say nothing about a 15k-token tool catalogue).\n */\nexport const promptOverheadTokens = (p: {\n systemPrompt?: string\n /** `toolDefinitionTokens` of everything the agent could offer. */\n toolTokens: number\n /** Tool search: only a few definitions are sent at a time. */\n searching: boolean\n /** The rendered skills index and the active skills' instructions. */\n skillsText: string\n}): number =>\n BASE_PROMPT_TOKENS +\n estimateTokens(p.systemPrompt ?? '') +\n (p.searching ? Math.min(p.toolTokens, SEARCH_TOOLS_ALLOWANCE) : p.toolTokens) +\n estimateTokens(p.skillsText)\n\n/** 'auto' switches to tool search once the definitions would take this share of the window. */\nexport const TOOL_SEARCH_WINDOW_SHARE = 0.25\n\n/** Raised when a prompt does not fit the model's context window. */\nexport class ContextWindowExceededError extends Error {\n /** The prompt's size as the provider counted it, when it said. */\n readonly promptTokens?: number\n /** The model's window as the provider reported it, when it said. */\n readonly contextWindowTokens?: number\n constructor(model: string, promptTokens?: number, contextWindowTokens?: number) {\n const sizes =\n promptTokens && contextWindowTokens\n ? ` (${promptTokens} tokens; the window is ${contextWindowTokens})`\n : ''\n super(\n `The conversation no longer fits the context window of \"${model}\"${sizes}. Start a new chat or compact this one, connect fewer tools, or switch to a model with a larger window.`,\n )\n this.name = 'ContextWindowExceededError'\n this.promptTokens = promptTokens\n this.contextWindowTokens = contextWindowTokens\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n// What providers say when the prompt is too long: WebLLM, OpenAI\n// (context_length_exceeded), Anthropic, Gemini, llama.cpp, vLLM / OpenRouter.\nconst OVERFLOW_RE =\n /prompt tokens exceed context window|context window size|context_length_exceeded|maximum context length|prompt is too long|input token count.*exceeds|exceeds the maximum number of tokens|exceeds the available context size|context length exceeded|too many tokens in (the )?(prompt|input)/i\nconst WEBLLM_SIZES_RE = /number of prompt tokens:\\s*(\\d+);\\s*context window size:\\s*(\\d+)/i\n\n/**\n * The clear error to raise when a provider refused a prompt for its length\n * (else undefined) — instead of the provider's raw text.\n */\nexport const contextOverflowOf = (\n err: unknown,\n model: unknown,\n): ContextWindowExceededError | undefined => {\n if (err instanceof ContextWindowExceededError) return err\n const text = err instanceof Error ? `${err.name} ${err.message}` : String(err)\n if (!OVERFLOW_RE.test(text)) return undefined\n const sizes = WEBLLM_SIZES_RE.exec(text)\n return new ContextWindowExceededError(\n modelLabel(model),\n sizes ? Number(sizes[1]) : undefined,\n sizes ? Number(sizes[2]) : (webLLMContextWindow(model) ?? undefined),\n )\n}\n","import type { FilePart } from 'ai'\n\n/**\n * Attachments sent with a run: images, PDFs and other files the provider can\n * read, given as bytes / base64 / a data URL — or as an http(s) URL, which\n * providers that accept links (Gemini, Claude, OpenAI) fetch themselves and the\n * AI SDK downloads for the rest (from the browser: subject to CORS).\n */\nexport interface RunFile {\n /** Base64 (no prefix), a data URL (\"data:image/png;base64,…\"), raw bytes, or an http(s) URL. */\n data: string | Uint8Array | URL\n /** e.g. \"image/png\", \"application/pdf\" — read from a data URL when omitted. */\n mediaType?: string\n /** Shown in the transcript, in memory and in errors. */\n name?: string\n}\n\n/** An image attachment (same shape; kept as its own name for clarity). */\nexport type RunImage = RunFile\n\n/** The kinds of attachment the agent reasons about separately. */\nexport type AttachmentKind = 'image' | 'pdf' | 'file'\n\nconst DATA_URL_RE = /^data:([^;,]+)?;base64,(.*)$/s\nconst HTTP_RE = /^https?:\\/\\//i\n\n/** The media type of an attachment (declared, from a data URL, or from a URL's extension). */\nexport const mediaTypeOf = (f: RunFile): string | undefined => {\n if (f.mediaType) return f.mediaType\n if (typeof f.data === 'string') {\n const m = DATA_URL_RE.exec(f.data)\n if (m?.[1]) return m[1]\n }\n const url = f.data instanceof URL ? f.data.href : typeof f.data === 'string' ? f.data : ''\n if (HTTP_RE.test(url) || f.name) {\n const ext = (f.name ?? new URL(url, 'http://x').pathname).split('.').pop()?.toLowerCase()\n if (ext === 'pdf') return 'application/pdf'\n if (ext && ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {\n return `image/${ext === 'jpg' ? 'jpeg' : ext}`\n }\n }\n return undefined\n}\n\nexport const attachmentKind = (f: RunFile): AttachmentKind => {\n const mt = mediaTypeOf(f) ?? ''\n if (mt.startsWith('image/')) return 'image'\n if (mt === 'application/pdf') return 'pdf'\n return 'file'\n}\n\nconst KIND_LABEL: Record<AttachmentKind, string> = {\n image: 'images',\n pdf: 'PDF files',\n file: 'file attachments',\n}\n\nconst KIND_HINT: Record<AttachmentKind, string> = {\n image:\n 'Remove the image, or switch to a vision-capable model such as Gemini, Claude or GPT-4o/GPT-5.',\n pdf: 'Convert the PDF to text first (e.g. PDF → Markdown), or switch to a model that reads PDFs such as Gemini, Claude or GPT-4o/GPT-5.',\n file: 'Paste its text instead, or switch to a model that accepts this file type.',\n}\n\n/** Raised when attachments are sent to a model that cannot take them. */\nexport class AttachmentsNotSupportedError extends Error {\n readonly kind: AttachmentKind\n constructor(model: string, kind: AttachmentKind, detail?: string) {\n super(\n `The model \"${model}\" can't take ${KIND_LABEL[kind]}${detail ? ` (${detail})` : ''}. ${KIND_HINT[kind]}`,\n )\n this.name = 'AttachmentsNotSupportedError'\n this.kind = kind\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n/** The image flavour of {@link AttachmentsNotSupportedError}. */\nexport class ImagesNotSupportedError extends AttachmentsNotSupportedError {\n constructor(model: string, detail?: string) {\n super(model, 'image', detail)\n this.name = 'ImagesNotSupportedError'\n }\n}\n\n/** The error for a kind: images get the dedicated class. */\nexport const unsupportedAttachment = (\n model: string,\n kind: AttachmentKind,\n detail?: string,\n): AttachmentsNotSupportedError =>\n kind === 'image'\n ? new ImagesNotSupportedError(model, detail)\n : new AttachmentsNotSupportedError(model, kind, detail)\n\nconst dataOf = (f: RunFile): string | Uint8Array | URL => {\n if (typeof f.data === 'string') {\n const m = DATA_URL_RE.exec(f.data)\n if (m) return m[2]\n if (HTTP_RE.test(f.data)) return new URL(f.data)\n }\n return f.data\n}\n\n/**\n * An AI SDK file part (images included — the v7 SDK deprecates the separate\n * image part). An http(s) URL is passed as a URL: providers that accept links\n * fetch it themselves, and the SDK downloads it for the rest.\n */\nexport const toFilePart = (f: RunFile): FilePart => {\n const kind = attachmentKind(f)\n const mediaType = mediaTypeOf(f) ?? (kind === 'image' ? 'image' : 'application/octet-stream')\n return {\n type: 'file',\n data: dataOf(f),\n mediaType,\n ...(f.name ? { filename: f.name } : {}),\n }\n}\n\n/** Back-compat name. */\nexport const toImagePart = toFilePart\n\n/** A short, human label of a model for messages. */\nexport const modelLabel = (model: unknown): string => {\n if (typeof model === 'string') return model\n const m = model as { provider?: string; modelId?: string } | undefined\n return m?.modelId ? `${m.modelId}${m.provider ? ` (${m.provider})` : ''}` : 'this model'\n}\n\nconst REFUSAL_RE =\n /image|vision|multimodal|multi-modal|media type|mediatype|pdf|document|unsupported (file|content|part|mime)|does not support (file|content)|invalid content type|image_url|inline_?data|file_?data/i\n\n/** Does a provider error look like a refusal of attachment input? */\nexport const isAttachmentRefusal = (err: unknown): boolean =>\n REFUSAL_RE.test(err instanceof Error ? `${err.name} ${err.message}` : String(err))\n\n/** Back-compat name. */\nexport const isImageRefusal = isAttachmentRefusal\n","import {\n generateObject,\n generateText,\n streamText,\n type LanguageModel,\n type ModelMessage,\n type SystemModelMessage,\n type ToolSet,\n} from 'ai'\nimport type { ZodType } from 'zod'\nimport type { ProviderOptionsMap, ThinkingLevel } from '../thinking.js'\nimport { promptOf, timeoutSignal } from './util.js'\n\n/** Options shared by the low-level generation helpers. Provide `prompt` OR `messages`. */\nexport interface GenerateOptions {\n /** The system prompt — a string, or a SystemModelMessage (e.g. with a cache breakpoint). */\n system?: string | SystemModelMessage\n prompt?: string\n messages?: ModelMessage[]\n tools?: ToolSet\n maxOutputTokens?: number\n temperature?: number\n /** Portable thinking level (see `resolveThinking`). */\n reasoning?: ThinkingLevel\n /** Provider-keyed options (thinking budgets, cache keys, …). */\n providerOptions?: ProviderOptionsMap\n abortSignal?: AbortSignal\n /** Time-box the call; combined with `abortSignal` (0/undefined = no timeout). */\n timeoutMs?: number\n}\n\n/** The settings every helper forwards; omits undefined keys the SDK would reject. */\nconst callSettings = (opts: GenerateOptions) => ({\n ...(opts.system !== undefined ? { instructions: opts.system } : {}),\n maxOutputTokens: opts.maxOutputTokens,\n temperature: opts.temperature,\n ...(opts.reasoning ? { reasoning: opts.reasoning } : {}),\n ...(opts.providerOptions ? { providerOptions: opts.providerOptions as never } : {}),\n abortSignal: timeoutSignal(opts.abortSignal, opts.timeoutMs),\n})\n\n/**\n * One-shot text generation. Thin, provider-agnostic wrapper over the AI SDK's\n * `generateText` — the same call works against a cloud model, a local WebLLM\n * model, or Chrome/Edge built-in AI. Returns the full AI SDK result (`.text`,\n * `.usage`, `.toolCalls`, `.steps`, …).\n */\nexport const generate = (\n model: LanguageModel,\n opts: GenerateOptions = {},\n): ReturnType<typeof generateText> =>\n generateText({\n model,\n ...callSettings(opts),\n ...promptOf(opts),\n tools: opts.tools,\n })\n\n/** Streaming text generation. Returns the AI SDK `streamText` result (`.textStream`, `.fullStream`). */\nexport const stream = (\n model: LanguageModel,\n opts: GenerateOptions = {},\n): ReturnType<typeof streamText> =>\n streamText({\n model,\n ...callSettings(opts),\n ...promptOf(opts),\n tools: opts.tools,\n })\n\n/**\n * Structured output constrained to a Zod schema, via the AI SDK's\n * `generateObject`. Cloud models and WebLLM both support this; tiny local\n * models can be unreliable — the agent's prompted mode is the fallback.\n * Returns the AI SDK result (`.object`, `.usage`).\n */\nexport const generateStructured = <OBJECT>(\n model: LanguageModel,\n schema: ZodType<OBJECT>,\n opts: GenerateOptions = {},\n) =>\n generateObject({\n model,\n schema,\n ...callSettings(opts),\n ...promptOf(opts),\n })\n","import type { ModelMessage } from 'ai'\nimport type { IUsage } from '../agent/loop-types.js'\n\n/** Truncate to `max` characters, ellipsising the overflow. */\nexport const clip = (s: string, max: number): string =>\n s.length > max ? `${s.slice(0, max - 1)}…` : s\n\n/**\n * The AI SDK prompt is `{ prompt } XOR { messages }` — passing both keys (even\n * with one undefined) breaks the discriminated union. Pick exactly one.\n */\nexport const promptOf = (opts: {\n prompt?: string\n messages?: ModelMessage[]\n}): { prompt: string } | { messages: ModelMessage[] } =>\n opts.messages ? { messages: opts.messages } : { prompt: opts.prompt ?? '' }\n\n/** The AI SDK usage shape, every field optional (providers omit what they don't report). */\nexport interface SdkUsageLike {\n inputTokens?: number\n outputTokens?: number\n totalTokens?: number\n inputTokenDetails?: { cacheReadTokens?: number; cacheWriteTokens?: number }\n outputTokenDetails?: { reasoningTokens?: number }\n /** Pre-v6 flat fields, still emitted by some providers. */\n reasoningTokens?: number\n cachedInputTokens?: number\n}\n\n/** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */\n/**\n * What a call that FAILED still cost. The AI SDK puts the usage on the error it throws when a\n * structured answer cannot be parsed (`NoObjectGeneratedError.usage`); the tokens were spent\n * all the same, and a fallback call must not hide them.\n */\nexport const usageOfError = (err: unknown): IUsage => {\n const u = (err as { usage?: SdkUsageLike } | null | undefined)?.usage\n return normalizeUsage(u && typeof u === 'object' ? u : undefined)\n}\n\nexport const normalizeUsage = (u?: SdkUsageLike): IUsage => {\n const inputTokens = u?.inputTokens ?? 0\n const outputTokens = u?.outputTokens ?? 0\n return {\n inputTokens,\n outputTokens,\n totalTokens: u?.totalTokens ?? inputTokens + outputTokens,\n reasoningTokens: u?.outputTokenDetails?.reasoningTokens ?? u?.reasoningTokens ?? 0,\n cachedInputTokens: u?.inputTokenDetails?.cacheReadTokens ?? u?.cachedInputTokens ?? 0,\n cacheWriteTokens: u?.inputTokenDetails?.cacheWriteTokens ?? 0,\n }\n}\n\n/**\n * Combine the caller's AbortSignal with a timeout so a hung generation can't\n * freeze a run. Returns the original signal when no timeout is set. Uses the\n * standard `AbortSignal.timeout`/`AbortSignal.any` (Node ≥ 20, modern browsers).\n */\nexport const timeoutSignal = (signal?: AbortSignal, ms?: number): AbortSignal | undefined => {\n if (!ms || ms <= 0) return signal\n const timeout = AbortSignal.timeout(ms)\n if (!signal) return timeout\n return typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, timeout]) : signal\n}\n","import type { LanguageModel } from 'ai'\nimport { generate } from '../llm/generate.js'\nimport { normalizeUsage } from '../llm/util.js'\nimport type { IUsage } from '../agent/loop-types.js'\nimport type { StoredMessage } from './store.js'\n\n/**\n * Context compaction. A model's window is finite and every token in it is paid\n * for on every call, so long transcripts and long runs are folded into a\n * summary: the oldest material is summarised by a model, the most recent is\n * kept verbatim.\n */\nexport interface CompactionConfig {\n /** Compact automatically before planning and between steps (default true). */\n auto?: boolean\n /** The model's context window, in tokens (default 128 000). */\n contextWindowTokens?: number\n /**\n * Compact once the estimated context - the fixed prompt (system, tools, skills), the transcript\n * and the run's step log together - exceeds this many tokens. Default: `thresholdRatio` of the\n * window.\n */\n thresholdTokens?: number\n /**\n * The same threshold as a share of the window, 0 < ratio <= 1 (default 0.85). `thresholdTokens`\n * wins when both are set; it follows the window if the model turns out to have a smaller one.\n */\n thresholdRatio?: number\n /** Transcript messages kept verbatim (default 4). */\n keepRecentTurns?: number\n /** Executed steps kept verbatim in the run's trace (default 3). */\n keepRecentSteps?: number\n /** Output cap of a summary call (default 1024). */\n summaryMaxTokens?: number\n /** Cap on ONE tool result as the model sees it, in chars (default 20 000; 0 = no cap). */\n maxToolOutputChars?: number\n /**\n * Inside one step's tool loop: once its context passes this many tokens,\n * replace the oldest tool results with one-line stubs (context editing;\n * default: a quarter of the window; 0 = never).\n */\n clearToolResultsAfterTokens?: number\n /** Most recent tool results kept verbatim when clearing (default 3). */\n keepToolResults?: number\n}\n\nexport interface ResolvedCompaction {\n auto: boolean\n contextWindowTokens: number\n thresholdTokens: number\n thresholdRatio: number\n keepRecentTurns: number\n keepRecentSteps: number\n summaryMaxTokens: number\n maxToolOutputChars: number\n clearToolResultsAfterTokens: number\n keepToolResults: number\n}\n\n/**\n * Compaction starts at this share of the window unless configured. The estimate leans high (see\n * `estimateTokens`), so on a Claude model this is roughly 70-75% really used - the rest is room\n * for the answer and for what one step adds before the next check.\n */\nexport const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85\n\nconst ratioOf = (r: number | undefined): number =>\n typeof r === 'number' && r > 0 && r <= 1 ? r : DEFAULT_COMPACTION_THRESHOLD_RATIO\n\nexport const resolveCompaction = (c: CompactionConfig | undefined): ResolvedCompaction => {\n const contextWindowTokens = c?.contextWindowTokens ?? 128_000\n const thresholdRatio = ratioOf(c?.thresholdRatio)\n return {\n auto: c?.auto ?? true,\n contextWindowTokens,\n thresholdTokens: c?.thresholdTokens ?? Math.floor(contextWindowTokens * thresholdRatio),\n thresholdRatio,\n keepRecentTurns: c?.keepRecentTurns ?? 4,\n keepRecentSteps: c?.keepRecentSteps ?? 3,\n summaryMaxTokens: c?.summaryMaxTokens ?? 1024,\n maxToolOutputChars: c?.maxToolOutputChars ?? 20_000,\n clearToolResultsAfterTokens:\n c?.clearToolResultsAfterTokens ?? Math.floor(contextWindowTokens / 4),\n keepToolResults: c?.keepToolResults ?? 3,\n }\n}\n\n// Chinese / Japanese / Korean characters and the halves of a surrogate pair (emoji): about a\n// token each. Other non-ASCII text (Cyrillic, Greek, accented Latin...) about two characters.\nconst isWide = (c: number): boolean =>\n (c >= 0x3040 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af) || (c >= 0xd800 && c <= 0xdfff)\n\n/**\n * Cheap, provider-independent token estimate, by kind of character - because text is not one\n * thing: letters run ~2.5 to a token (prose is kinder; code, markdown and JSON are not), digits\n * and punctuation about one each (JSON, tables, ids), a space a quarter, a newline one, other\n * scripts (Russian...) two characters, CJK and emoji one. Calibrated against Claude's tokenizer,\n * the most token-hungry in use, over prose, markdown, code, JSON, a table, Russian and a mix: it\n * comes out 1.1-1.4x the real count and never below it (a flat \"4 characters a token\" was\n * 0.4-0.7x for everything but Russian). It errs high ON PURPOSE: it decides when to compact, and\n * compacting a little early is cheap while overflowing the window is a failed run. A tokenizer\n * that packs tighter (OpenAI, Gemini) makes it higher still - then raise `thresholdRatio`.\n */\nexport const estimateTokens = (text: string): number => {\n const s = text ?? ''\n let letters = 0\n let digits = 0\n let spaces = 0\n let newlines = 0\n let punct = 0\n let other = 0\n let wide = 0\n for (let i = 0; i < s.length; i += 1) {\n const c = s.charCodeAt(i)\n if (c < 128) {\n if ((c >= 97 && c <= 122) || (c >= 65 && c <= 90)) letters += 1\n else if (c >= 48 && c <= 57) digits += 1\n else if (c === 32 || c === 9) spaces += 1\n else if (c === 10) newlines += 1\n else punct += 1\n } else if (isWide(c)) wide += 1\n else other += 1\n }\n // In thousandths of a token, so the arithmetic is exact: 1.1 x (letters / 2.5 + digits +\n // punctuation x 1.1 + spaces / 4 + newlines + other / 2 + wide).\n return Math.ceil(\n (440 * letters +\n 1100 * digits +\n 1210 * punct +\n 275 * spaces +\n 1100 * newlines +\n 550 * other +\n 1100 * wide) /\n 1000,\n )\n}\n\nconst messageTokens = (msgs: StoredMessage[]): number =>\n msgs.reduce((n, m) => n + estimateTokens(`${m.role}: ${m.content}\\n`), 0)\n\n/**\n * The lines joined, keeping the NEWEST ones that fit `maxTokens` (estimated); with no budget the\n * historical cut: the last 48 000 characters.\n */\nconst newestWithin = (lines: string[], maxTokens: number | undefined): string => {\n if (maxTokens === undefined) return lines.join('\\n').slice(-48_000)\n const kept: string[] = []\n let used = 0\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const t = estimateTokens(lines[i]) + 1\n if (used + t > maxTokens) {\n // A single line larger than the budget: its tail, rather than nothing.\n if (kept.length === 0) kept.push(lines[i].slice(-Math.max(1, maxTokens) * 2))\n break\n }\n kept.unshift(lines[i])\n used += t\n }\n return kept.join('\\n')\n}\n\nexport interface CompressOptions {\n /** Compress once the transcript exceeds this many characters (0 = never). */\n maxChars?: number\n /** Compress once the transcript's estimated tokens exceed this (wins over maxChars). */\n thresholdTokens?: number\n /** How many most-recent messages to keep verbatim. */\n keepRecent?: number\n /** Output cap of the summary call. */\n summaryMaxTokens?: number\n /**\n * The most the summariser is shown, in estimated tokens (the newest part is kept). Default: a\n * fixed 48 000 characters. The agent passes a share of the window, so a long transcript is\n * summarised whole instead of cut to its last few pages first.\n */\n maxInputTokens?: number\n /** Compact even when below the threshold (manual \"compact now\"). */\n force?: boolean\n /** Time-box the summarisation call so it can never hang the caller. */\n timeoutMs?: number\n abortSignal?: AbortSignal\n /** Receives the summary call's token usage. */\n onUsage?: (usage: IUsage) => void\n}\n\nconst SUMMARY_SYSTEM =\n 'Summarize the following conversation into a compact set of durable facts, decisions, ' +\n 'identifiers, open tasks and user preferences. Keep names, numbers and IDs verbatim. ' +\n 'Output plain text only.'\n\n/**\n * When the transcript grows too long, summarise everything except the last\n * `keepRecent` messages into a single system message (via the model), so the\n * session stays within the model's context window. Returns the same array\n * unchanged when no compression is needed; never throws.\n */\nexport const compressHistory = async (\n messages: StoredMessage[],\n model: LanguageModel,\n opts: CompressOptions = {},\n): Promise<StoredMessage[]> => {\n const keepRecent = opts.keepRecent ?? 6\n if (messages.length <= keepRecent + 1) return messages\n if (!opts.force) {\n if (opts.thresholdTokens !== undefined) {\n if (opts.thresholdTokens <= 0 || messageTokens(messages) <= opts.thresholdTokens) {\n return messages\n }\n } else {\n const maxChars = opts.maxChars ?? 12_000\n const chars = messages.reduce((n, m) => n + m.content.length, 0)\n if (maxChars <= 0 || chars <= maxChars) return messages\n }\n }\n const head = messages.slice(0, messages.length - keepRecent)\n const tail = messages.slice(messages.length - keepRecent)\n // The newest part of the head matters most; keep the tail end of it when it\n // has to be cut to fit the summariser's own window.\n const transcript = newestWithin(\n head.map((m) => `${m.role}: ${m.content}`),\n opts.maxInputTokens,\n )\n try {\n const result = await generate(model, {\n system: SUMMARY_SYSTEM,\n prompt: transcript,\n maxOutputTokens: opts.summaryMaxTokens ?? 400,\n timeoutMs: opts.timeoutMs,\n abortSignal: opts.abortSignal,\n })\n opts.onUsage?.(normalizeUsage(result.usage))\n const clean = (result.text || '').trim()\n if (!clean) return messages\n const summaryMsg: StoredMessage = {\n role: 'system',\n content: `Summary of earlier conversation:\\n${clean}`,\n ts: head[0]?.ts,\n }\n return [summaryMsg, ...tail]\n } catch {\n return messages\n }\n}\n\n/** Alias with the sibling package's name; same behaviour as compressHistory. */\nexport const compactHistory = compressHistory\n\nconst TRACE_SYSTEM =\n 'Summarize these completed agent steps into a compact progress note: what was done, ' +\n 'what was found (keep names, numbers and IDs verbatim) and what failed. Plain text only.'\n\n/**\n * Fold the oldest entries of a run's step log into one summary entry, keeping\n * the last `keepRecent` verbatim. Returns the input unchanged when it fits the\n * threshold or on any failure; never throws.\n */\nexport const compactSteps = async (\n done: string[],\n model: LanguageModel,\n opts: CompressOptions & { thresholdTokens: number },\n): Promise<string[]> => {\n const keepRecent = opts.keepRecent ?? 3\n if (done.length <= keepRecent + 1) return done\n if (!opts.force && estimateTokens(done.join('\\n')) <= opts.thresholdTokens) return done\n const head = done.slice(0, done.length - keepRecent)\n try {\n const result = await generate(model, {\n system: TRACE_SYSTEM,\n prompt: newestWithin(\n head.map((d, i) => `${i + 1}. ${d}`),\n opts.maxInputTokens ?? 1e9,\n ),\n maxOutputTokens: opts.summaryMaxTokens ?? 600,\n timeoutMs: opts.timeoutMs,\n abortSignal: opts.abortSignal,\n })\n opts.onUsage?.(normalizeUsage(result.usage))\n const clean = (result.text || '').trim()\n if (!clean) return done\n return [`Summary of ${head.length} earlier step(s): ${clean}`, ...done.slice(head.length)]\n } catch {\n return done\n }\n}\n\nexport { messageTokens as estimateMessagesTokens }\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAwC;;;ACAjD,SAAS,gBAA8B;;;ACuBvC,IAAM,cAAc;AACpB,IAAM,UAAU;AAGT,IAAM,cAAc,CAAC,MAAmC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