@dudko.dev/agent-web 0.0.42 → 0.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +150 -4
  2. package/dist/agent-web.js +155 -155
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/{chunk-DAREMCXF.js → chunk-236RCVAZ.js} +40 -8
  5. package/dist/chunk-236RCVAZ.js.map +1 -0
  6. package/dist/{chunk-2MLHZ6LQ.js → chunk-Y4MIIBPB.js} +2 -2
  7. package/dist/{chunk-ZSZSSJS4.js → chunk-Y6CD3WOK.js} +176 -10
  8. package/dist/chunk-Y6CD3WOK.js.map +1 -0
  9. package/dist/{chunk-YPCHD6DV.js → chunk-YGWIOO27.js} +31 -12
  10. package/dist/chunk-YGWIOO27.js.map +1 -0
  11. package/dist/index.cjs +1248 -108
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +1777 -1643
  14. package/dist/index.d.ts +1777 -1643
  15. package/dist/index.js +996 -89
  16. package/dist/index.js.map +1 -1
  17. package/dist/mcp.cjs +136 -5
  18. package/dist/mcp.cjs.map +1 -1
  19. package/dist/mcp.d.cts +5 -2
  20. package/dist/mcp.d.ts +5 -2
  21. package/dist/mcp.js +19 -8
  22. package/dist/mcp.js.map +1 -1
  23. package/dist/pipeline-engine.cjs +1130 -0
  24. package/dist/pipeline-engine.cjs.map +1 -0
  25. package/dist/pipeline-engine.d.cts +226 -0
  26. package/dist/pipeline-engine.d.ts +226 -0
  27. package/dist/pipeline-engine.js +1094 -0
  28. package/dist/pipeline-engine.js.map +1 -0
  29. package/dist/{sandbox-3VRX47UY.js → sandbox-7CGSIIIZ.js} +4 -4
  30. package/dist/sandbox-worker.cjs +30 -11
  31. package/dist/sandbox-worker.cjs.map +1 -1
  32. package/dist/sandbox-worker.js +1 -1
  33. package/dist/{elicitation-DS-84_bF.d.cts → vault-Mar2CY0J.d.cts} +526 -526
  34. package/dist/{elicitation-DS-84_bF.d.ts → vault-Mar2CY0J.d.ts} +526 -526
  35. package/package.json +13 -3
  36. package/dist/chunk-DAREMCXF.js.map +0 -1
  37. package/dist/chunk-YPCHD6DV.js.map +0 -1
  38. package/dist/chunk-ZSZSSJS4.js.map +0 -1
  39. /package/dist/{chunk-2MLHZ6LQ.js.map → chunk-Y4MIIBPB.js.map} +0 -0
  40. /package/dist/{sandbox-3VRX47UY.js.map → sandbox-7CGSIIIZ.js.map} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent-web",
3
- "version": "0.0.42",
3
+ "version": "0.0.44",
4
4
  "description": "Headless, configurable in-browser LLM agent on the Vercel AI SDK: multi-provider bring-your-own-key (OpenAI, Anthropic, Google, xAI, DeepSeek, gateway, openai-compatible) AND local WebGPU/WebLLM, native + prompted tool-calling, structured output, an encrypted IndexedDB token vault, and a plan → execute → replan → synthesize loop. UI-agnostic.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -53,6 +53,16 @@
53
53
  "default": "./dist/sandbox-worker.cjs"
54
54
  }
55
55
  },
56
+ "./pipeline-engine": {
57
+ "import": {
58
+ "types": "./dist/pipeline-engine.d.ts",
59
+ "default": "./dist/pipeline-engine.js"
60
+ },
61
+ "require": {
62
+ "types": "./dist/pipeline-engine.d.cts",
63
+ "default": "./dist/pipeline-engine.cjs"
64
+ }
65
+ },
56
66
  "./bundle": {
57
67
  "types": "./dist/index.d.ts",
58
68
  "import": "./dist/agent-web.js"
@@ -140,7 +150,7 @@
140
150
  "node": ">=20"
141
151
  },
142
152
  "dependencies": {
143
- "ai": "^7.0.183",
153
+ "ai": "^7.0.184",
144
154
  "idb": "^8.0.4",
145
155
  "zod": "^4.6.7"
146
156
  },
@@ -193,7 +203,7 @@
193
203
  }
194
204
  },
195
205
  "devDependencies": {
196
- "@ai-sdk/anthropic": "^4.0.110",
206
+ "@ai-sdk/anthropic": "^4.0.111",
197
207
  "@ai-sdk/deepseek": "^3.0.91",
198
208
  "@ai-sdk/google": "^4.0.128",
199
209
  "@ai-sdk/openai": "^4.0.125",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/limits.ts","../src/tools/approval.ts","../src/tiers.ts","../src/tools/types.ts","../src/tools/wrap.ts","../src/files/vfs.ts","../src/files/tools.ts"],"sourcesContent":["import type { IUsage } from './agent/loop-types.js'\n\n/**\n * Run-level token budgets. Every cap is cumulative over one `run()` and soft:\n * it is checked between steps and at every tool-calling round inside a step,\n * so a run stops at the next boundary after crossing it and then writes its\n * final answer (synthesis still runs, bounded by `perCall.synthesizer`).\n */\nexport interface TokenLimits {\n /** Cumulative input (prompt) tokens per run. */\n maxInputTokens?: number\n /** Cumulative output tokens per run, thinking included. */\n maxOutputTokens?: number\n /** Cumulative thinking tokens per run. */\n maxReasoningTokens?: number\n /** Cumulative input + output tokens per run. */\n maxTotalTokens?: number\n /** Max output tokens of ONE model call, per phase (wins over the legacy `budgets`). */\n perCall?: {\n planner?: number\n executor?: number\n replanner?: number\n synthesizer?: number\n compaction?: number\n }\n}\n\nexport type LimitKind = 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls'\n\nexport interface LimitBreach {\n kind: LimitKind\n tokens: number\n cap: number\n}\n\nconst over = (value: number | undefined, cap: number | undefined): boolean =>\n typeof cap === 'number' && cap > 0 && (value ?? 0) >= cap\n\n/**\n * The first cap the usage has reached, or undefined. Order: total, input,\n * output, reasoning — the broadest budget is reported first. Pure.\n */\nexport const checkLimits = (\n usage: IUsage,\n limits: TokenLimits | undefined,\n): LimitBreach | undefined => {\n if (!limits) return undefined\n if (over(usage.totalTokens, limits.maxTotalTokens)) {\n return { kind: 'total', tokens: usage.totalTokens, cap: limits.maxTotalTokens as number }\n }\n if (over(usage.inputTokens, limits.maxInputTokens)) {\n return { kind: 'input', tokens: usage.inputTokens, cap: limits.maxInputTokens as number }\n }\n if (over(usage.outputTokens, limits.maxOutputTokens)) {\n return { kind: 'output', tokens: usage.outputTokens, cap: limits.maxOutputTokens as number }\n }\n if (over(usage.reasoningTokens, limits.maxReasoningTokens)) {\n return {\n kind: 'reasoning',\n tokens: usage.reasoningTokens ?? 0,\n cap: limits.maxReasoningTokens as number,\n }\n }\n return undefined\n}\n\n/** Raised by a tool call that would exceed `maxToolCalls`. */\nexport class ToolBudgetError extends Error {\n constructor(cap: number) {\n super(\n `Tool-call budget exhausted (${cap} per run). Do not call more tools; report what you have.`,\n )\n this.name = 'ToolBudgetError'\n }\n\n toJSON(): string {\n return this.message\n }\n}\n","import type { Tool } from 'ai'\nimport type { IPlanStep } from '../agent/loop-types.js'\nimport {\n createMcpSkillGrants,\n type McpSkillConsentView,\n type McpSkillGrants,\n} from '../mcp/skills.js'\n\n/**\n * Tool consent. Every tool call passes a gate that decides allow / ask / deny:\n *\n * - `autopilot` — run everything (default; explicit `rules` still apply);\n * - `ask-writes` — run read-only tools, ask before anything that may change state;\n * - `ask-all` — ask before every call;\n * - `read-only` — run read-only tools, refuse the rest without asking.\n *\n * A tool is read-only when its MCP annotations say so (`readOnlyHint`) or the\n * host marked it (`defineTool({ readOnly: true })` / `markReadOnly`). Unknown =\n * may write: the safe assumption.\n */\nexport type ToolApprovalMode = 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only'\nexport type ToolPermission = 'allow' | 'ask' | 'deny'\n\nexport const TOOL_APPROVAL_MODES: readonly ToolApprovalMode[] = [\n 'autopilot',\n 'ask-writes',\n 'ask-all',\n 'read-only',\n]\n\nexport interface ToolApprovalRequest {\n /** Unique per request — echo it back from a UI. */\n id: string\n toolName: string\n input: unknown\n readOnly: boolean\n step?: IPlanStep\n /**\n * Set when the call comes from a helper the model started (`subagents.dynamic`), not from the\n * run itself: the helper's id (as in its `subagent.start` event) and its depth.\n */\n subagent?: { id: string; depth: number }\n /**\n * Set when the call comes from an MCP App (`Agent.approveAppToolCall`), not from the model:\n * a UI says so (\"The app “travel” wants to run …\"). `toolName` above is then the name the\n * agent's rules match (`server__tool`), `app.tool` the server's own name for it.\n */\n app?: ToolApprovalApp\n /**\n * Set when the call runs code (`run_js`, or a tool marked with `markCodeExecution`) while the\n * run acts on skills an MCP server served: those skills, by name. Such a call is ALWAYS asked,\n * whatever the mode, a rule or an earlier \"always allow\" say (the Skills extension: a server's\n * skill must not lead to code running here without a person's approval).\n */\n mcpSkills?: string[]\n /**\n * Set when the request is not about a tool call but about an MCP server's skill that is about\n * to enter the model's context (`load_skill`, the planner's pick, a resumed run; `skills` on a\n * server, consent `'ask'` / `'once-per-skill'`): the server, the skill, its description and\n * size and the very text the model would read - the SERVER's words, to show as plain text.\n * `toolName` is `'load_skill'`. Approve to let it in (`remember: true` = every skill of that\n * server for the agent's life, nested ones excepted), deny to keep it out. Asked whatever the\n * approval mode and the rules say.\n */\n skill?: McpSkillConsentView\n}\n\n/** Who asks when an MCP App asks (see `ToolApprovalRequest.app`). */\nexport interface ToolApprovalApp {\n /** The MCP server the app came from (its tools are the only ones it may call). */\n server: string\n /** The tool's own name on that server. */\n tool: string\n /** The app's `ui://` resource. */\n resourceUri: string\n}\n\n/** What the gate hands `onRequest` beside the request. */\nexport interface ToolApprovalContext {\n /**\n * Aborted when the question ends WITHOUT your answer: no decision within `timeoutMs`\n * (`signal.reason` is an Error named 'TimeoutError'), the run was stopped ('AbortError'), or\n * the handler failed. Take the prompt down then: an answer given later is ignored. Never\n * aborted once you have answered.\n */\n signal: AbortSignal\n}\n\n/**\n * `true`/`false`, or an object. `remember: true` on an approval allows this\n * tool for the rest of the agent's life (\"always allow\").\n */\nexport type ToolApprovalDecision =\n boolean | { approved: boolean; reason?: string; remember?: boolean }\n\nexport interface ToolApprovalConfig {\n /** Default policy (default 'autopilot'). */\n mode?: ToolApprovalMode\n /**\n * Per-tool overrides by exact name or `*` glob, e.g. `{ 'github__delete_*': 'deny' }`.\n * They win over the mode — an explicit 'ask' still asks under autopilot.\n */\n rules?: Record<string, ToolPermission>\n /** Resolves an approval request (a UI prompt, a policy service, …). */\n onRequest?: (\n req: ToolApprovalRequest,\n ctx: ToolApprovalContext,\n ) => ToolApprovalDecision | Promise<ToolApprovalDecision>\n /**\n * No decision within this many ms → deny. Default 300 000 ({@link TOOL_APPROVAL_TIMEOUT_MS}).\n * `0` or `Infinity`: no bound - the question waits until the run is stopped; so does a value\n * above 2^31 - 1 (about 24.8 days, the most a timer holds). Negative or NaN: `createAgent`\n * throws. The only bound on the wait: the step's `chatTimeoutMs` (and a subagent's\n * `timeoutMs`) stop while a person decides.\n */\n timeoutMs?: number\n}\n\n/** How long a question waits for a decision when `toolApproval.timeoutMs` is not set: 5 minutes. */\nexport const TOOL_APPROVAL_TIMEOUT_MS = 300_000\n\n// The longest delay a timer holds (2^31 - 1 ms, about 24.8 days). `setTimeout` fires a longer one\n// - Infinity included - after about 1 ms, so a bound past it is taken as no bound at all.\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * `toolApproval.timeoutMs` as the gate uses it: absent = {@link TOOL_APPROVAL_TIMEOUT_MS}; `0`,\n * `Infinity` or more than a timer holds = no bound (0: the question waits until the run is\n * stopped). Anything that is not a number of at least 0 is a configuration error.\n */\nexport const resolveApprovalTimeout = (value: unknown): number => {\n if (value === undefined || value === null) return TOOL_APPROVAL_TIMEOUT_MS\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n throw new Error(\n `toolApproval.timeoutMs must be a number of milliseconds of at least 0 (0 or Infinity: no limit), got: ${typeof value === 'number' ? String(value) : JSON.stringify(value)}`,\n )\n }\n return value === 0 || value > MAX_TIMER_MS ? 0 : Math.max(1, Math.floor(value))\n}\n\n/** Raised by a denied tool call; recorded as a failed call the replanner sees. */\nexport class ToolDeniedError extends Error {\n constructor(reason?: string) {\n super(\n `Tool call denied by the user${reason ? `: ${reason}` : ''}. Do not retry it; continue without it, or report what is blocked.`,\n )\n this.name = 'ToolDeniedError'\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n/** Mark a tool as read-only so `ask-writes` / `read-only` let it through. Returns it. */\nexport const markReadOnly = <T extends object>(tool: T, readOnly = true): T => {\n ;(tool as { readOnly?: boolean }).readOnly = readOnly\n return tool\n}\n\n/**\n * Mark a tool as one that runs code (the sandbox's `run_js` is): while a run acts on an MCP\n * server's skill, every call of it is asked (`decideToolPermission`).\n */\nexport const markCodeExecution = <T extends object>(tool: T, codeExecution = true): T => {\n ;(tool as { codeExecution?: boolean }).codeExecution = codeExecution\n return tool\n}\n\nexport const isCodeExecutionTool = (tool: unknown): boolean =>\n (tool as { codeExecution?: unknown } | undefined)?.codeExecution === true\n\nexport const isReadOnlyTool = (tool: Tool | undefined): boolean =>\n (tool as { readOnly?: unknown } | undefined)?.readOnly === true\n\nconst globToRegExp = (glob: string): RegExp =>\n new RegExp(\n `^${glob\n .split('*')\n .map((s) => s.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('.*')}$`,\n )\n\n/** The most specific matching rule: an exact name, else the longest glob. Pure. */\nexport const matchRule = (\n rules: Record<string, ToolPermission> | undefined,\n toolName: string,\n): ToolPermission | undefined => {\n if (!rules) return undefined\n if (Object.hasOwn(rules, toolName)) return rules[toolName]\n let best: { len: number; perm: ToolPermission } | undefined\n for (const [pattern, perm] of Object.entries(rules)) {\n if (!pattern.includes('*')) continue\n if (!globToRegExp(pattern).test(toolName)) continue\n const len = pattern.replace(/\\*/g, '').length\n if (!best || len > best.len) best = { len, perm }\n }\n return best?.perm\n}\n\n/**\n * What the gate does for one call, before any human is involved. Order:\n * remembered \"always allow\" → most specific rule → mode default. Pure.\n * Then one rule that only ever tightens: a call that runs code (`codeExecution`) while the run\n * acts on an MCP server's skill (`mcpSkills`) is asked when it would have been allowed - by the\n * mode, a rule or an \"always allow\" alike. A deny stays a deny.\n */\nexport const decideToolPermission = (opts: {\n toolName: string\n readOnly: boolean\n mode: ToolApprovalMode\n rules?: Record<string, ToolPermission>\n remembered?: ReadonlySet<string>\n codeExecution?: boolean\n mcpSkills?: readonly string[]\n}): ToolPermission => {\n const permission = decideByPolicy(opts)\n return permission === 'allow' && opts.codeExecution && opts.mcpSkills?.length ? 'ask' : permission\n}\n\nconst decideByPolicy = (opts: {\n toolName: string\n readOnly: boolean\n mode: ToolApprovalMode\n rules?: Record<string, ToolPermission>\n remembered?: ReadonlySet<string>\n}): ToolPermission => {\n if (opts.remembered?.has(opts.toolName)) return 'allow'\n const rule = matchRule(opts.rules, opts.toolName)\n if (rule) return rule\n switch (opts.mode) {\n case 'autopilot':\n return 'allow'\n case 'read-only':\n return opts.readOnly ? 'allow' : 'deny'\n case 'ask-writes':\n return opts.readOnly ? 'allow' : 'ask'\n case 'ask-all':\n return 'ask'\n }\n}\n\nconst normalizeDecision = (\n d: ToolApprovalDecision,\n): { approved: boolean; reason?: string; remember?: boolean } =>\n typeof d === 'boolean'\n ? { approved: d }\n : { approved: Boolean(d?.approved), reason: d?.reason, remember: d?.remember }\n\n/** Mutable approval state shared by every run of one agent. */\nexport interface ApprovalState {\n mode: ToolApprovalMode\n readonly config: ToolApprovalConfig\n /** The wait's bound, `config.timeoutMs` resolved (resolveApprovalTimeout): 0 = none. */\n readonly timeoutMs: number\n /** Tools the user chose to \"always allow\". */\n readonly remembered: Set<string>\n /** What a person allowed of MCP servers' skills for the agent's life (helpers share it). */\n readonly mcpSkillGrants: McpSkillGrants\n}\n\n/** Throws on a `timeoutMs` that is not a usable number: a configuration error, at `createAgent`. */\nexport const createApprovalState = (config: ToolApprovalConfig | undefined): ApprovalState => ({\n mode: config?.mode ?? 'autopilot',\n config: config ?? {},\n timeoutMs: resolveApprovalTimeout(config?.timeoutMs),\n remembered: new Set<string>(),\n mcpSkillGrants: createMcpSkillGrants(),\n})\n\nlet seq = 0\n\nexport interface ApprovalEvents {\n requested: (req: ToolApprovalRequest) => void\n resolved: (r: {\n id: string\n name: string\n approved: boolean\n reason?: string\n automatic: boolean\n }) => void\n /**\n * A person is being asked (right after `requested`): stop the run's time limits - the step's,\n * a subagent's - for the length of the wait. Returns what starts them again (wait-clock.ts).\n */\n wait?: () => () => void\n}\n\n/**\n * Run the gate for one call. Resolves when the call may proceed; throws\n * {@link ToolDeniedError} otherwise. `alwaysAllow` short-circuits (built-ins).\n */\nexport const gateToolCall = async (\n state: ApprovalState,\n call: {\n toolName: string\n input: unknown\n readOnly: boolean\n step?: IPlanStep\n subagent?: { id: string; depth: number }\n app?: ToolApprovalApp\n /** The tool runs code: asked while the run acts on an MCP server's skill (`mcpSkills`). */\n codeExecution?: boolean\n /** The MCP skills the run acts on (with `codeExecution` only). */\n mcpSkills?: string[]\n },\n events: ApprovalEvents,\n signal?: AbortSignal,\n): Promise<void> => {\n const { codeExecution, mcpSkills: acting, ...shown } = call\n const permission = decideToolPermission({\n toolName: call.toolName,\n readOnly: call.readOnly,\n mode: state.mode,\n rules: state.config.rules,\n remembered: state.remembered,\n ...(codeExecution ? { codeExecution } : {}),\n ...(acting?.length ? { mcpSkills: acting } : {}),\n })\n if (permission === 'allow') return\n // Asked only because the run acts on an MCP server's skill: the request says which.\n const bySkill =\n Boolean(codeExecution && acting?.length) &&\n decideByPolicy({\n toolName: call.toolName,\n readOnly: call.readOnly,\n mode: state.mode,\n rules: state.config.rules,\n remembered: state.remembered,\n }) === 'allow'\n const id = `approval-${Date.now().toString(36)}-${(seq += 1)}`\n if (permission === 'deny') {\n const reason =\n state.mode === 'read-only' && !matchRule(state.config.rules, call.toolName)\n ? 'the agent is in read-only mode'\n : 'blocked by policy'\n events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true })\n throw new ToolDeniedError(reason)\n }\n const onRequest = state.config.onRequest\n if (!onRequest) {\n const reason = bySkill\n ? \"code runs only with a person's approval while the run acts on an MCP server's skill, and no approval handler is configured\"\n : 'no approval handler configured'\n events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true })\n throw new ToolDeniedError(reason)\n }\n const req: ToolApprovalRequest = { id, ...shown, ...(bySkill ? { mcpSkills: acting } : {}) }\n events.requested(req)\n let decision: { approved: boolean; reason?: string; remember?: boolean }\n // The host's own signal: aborted when the question ends without its answer (the bound, a\n // stop, a failed handler), so a prompt left open can be taken down. Never after an answer.\n const asked = new AbortController()\n // A person is being asked: the step's limit is about models and tools, and does not run\n // meanwhile. The wait has its own bound, `timeoutMs`, and a stop still ends it at once.\n const resume = events.wait?.()\n try {\n decision = normalizeDecision(\n await withDeadline(\n Promise.resolve(onRequest(req, { signal: asked.signal })),\n state.timeoutMs,\n signal,\n ),\n )\n } catch (err) {\n // Before the resolved event: a host that closes its prompt hears of it first.\n asked.abort(err)\n resume?.()\n const reason = err instanceof Error ? err.message : String(err)\n events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true })\n throw new ToolDeniedError(reason)\n }\n resume?.()\n if (decision.approved && decision.remember) state.remembered.add(call.toolName)\n events.resolved({\n id,\n name: call.toolName,\n approved: decision.approved,\n reason: decision.reason,\n automatic: false,\n })\n if (!decision.approved) throw new ToolDeniedError(decision.reason)\n}\n\n/**\n * Ask the person whether an MCP server's skill may enter the model's context: the same\n * `onRequest`, `timeoutMs` and events as a tool call (the request carries `skill`, `toolName` is\n * `load_skill`), but no mode, no rule and no \"always allow\" of the tools' - a yes with `remember`\n * is \"Always for this server\", kept by the caller. Resolves with the answer (`by` says whether a\n * person gave it); throws only when the run was stopped.\n */\nexport const askMcpSkillConsent = async (\n state: ApprovalState,\n call: {\n input: unknown\n skill: McpSkillConsentView\n step?: IPlanStep\n subagent?: { id: string; depth: number }\n },\n events: ApprovalEvents,\n signal?: AbortSignal,\n): Promise<{\n approved: boolean\n remember?: boolean\n reason?: string\n by: 'person' | 'no-handler' | 'no-answer'\n}> => {\n const id = `approval-${Date.now().toString(36)}-${(seq += 1)}`\n const name = 'load_skill'\n const onRequest = state.config.onRequest\n if (!onRequest) {\n const reason = 'no approval handler configured'\n events.resolved({ id, name, approved: false, reason, automatic: true })\n return { approved: false, reason, by: 'no-handler' }\n }\n const req: ToolApprovalRequest = {\n id,\n toolName: name,\n input: call.input,\n readOnly: true,\n ...(call.step ? { step: call.step } : {}),\n ...(call.subagent ? { subagent: call.subagent } : {}),\n skill: call.skill,\n }\n events.requested(req)\n const asked = new AbortController()\n const resume = events.wait?.()\n let decision: { approved: boolean; reason?: string; remember?: boolean }\n try {\n decision = normalizeDecision(\n await withDeadline(\n Promise.resolve(onRequest(req, { signal: asked.signal })),\n state.timeoutMs,\n signal,\n ),\n )\n } catch (err) {\n asked.abort(err)\n resume?.()\n const reason = err instanceof Error ? err.message : String(err)\n events.resolved({ id, name, approved: false, reason, automatic: true })\n if (signal?.aborted) throw err\n return { approved: false, reason, by: 'no-answer' }\n }\n resume?.()\n events.resolved({\n id,\n name,\n approved: decision.approved,\n reason: decision.reason,\n automatic: false,\n })\n return {\n approved: decision.approved,\n ...(decision.remember ? { remember: true } : {}),\n ...(decision.reason ? { reason: decision.reason } : {}),\n by: 'person',\n }\n}\n\n// Named like the reasons of `AbortSignal.timeout` / `abort()`: they are the host signal's too.\nconst namedError = (message: string, name: string): Error =>\n Object.assign(new Error(message), { name })\n\n// `timeoutMs` is resolved (resolveApprovalTimeout): 0 = no bound, else what a timer can hold.\nexport const withDeadline = <T>(\n p: Promise<T>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<T> => {\n if (!(timeoutMs > 0) && !signal) return p\n return new Promise<T>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const done = () => {\n if (timer !== undefined) clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n }\n const onAbort = () => {\n done()\n reject(namedError('the run was stopped while waiting for approval', 'AbortError'))\n }\n if (signal?.aborted) return onAbort()\n signal?.addEventListener('abort', onAbort, { once: true })\n if (timeoutMs > 0) {\n timer = setTimeout(() => {\n done()\n reject(namedError(`no approval decision within ${timeoutMs} ms`, 'TimeoutError'))\n }, timeoutMs)\n }\n p.then(\n (v) => {\n done()\n resolve(v)\n },\n (e) => {\n done()\n reject(e)\n },\n )\n })\n}\n","import type {\n EscalationConfig,\n EscalationReason,\n IStepResult,\n ModelTier,\n StepComplexity,\n TierReason,\n} from './agent/loop-types.js'\n\n// Model tiers (config.executorTiers) and escalation (config.escalation): the pure rules. Which\n// tier a step runs on, which tier is tried after a failure, what counts as a failure a stronger\n// model could fix, and what the stronger model is shown of the attempt before it. The Node\n// sibling's src/tiers.ts carries the same rules under the same names: change both, with tests.\n\n// Weakest first: the order escalation climbs.\nexport const MODEL_TIERS: readonly ModelTier[] = ['light', 'standard', 'strong']\n\nexport const STEP_COMPLEXITIES: readonly StepComplexity[] = ['low', 'medium', 'high']\n\nconst TIER_OF: Record<StepComplexity, ModelTier> = {\n low: 'light',\n medium: 'standard',\n high: 'strong',\n}\n\nexport const isStepComplexity = (v: unknown): v is StepComplexity =>\n typeof v === 'string' && (STEP_COMPLEXITIES as readonly string[]).includes(v)\n\n/**\n * The tier a step runs on. The planner's complexity names the tier it wants (low -> light,\n * medium -> standard, high -> strong); a step the planner did not mark runs on `standard`.\n * A tier the host did not configure falls back to the NEAREST configured one, and of two equally\n * near the STRONGER: a step is never handed to a model weaker than it has to be. `standard` is\n * always configured (it is the agent's own model), so in practice a missing `light` or `strong`\n * means `standard` - the rule is general so that it stays true if that ever changes.\n */\nexport const pickTier = (\n complexity: StepComplexity | undefined,\n configured: ReadonlySet<ModelTier>,\n): { tier: ModelTier; reason: TierReason } => {\n const wanted: ModelTier = complexity ? TIER_OF[complexity] : 'standard'\n if (configured.has(wanted)) {\n return { tier: wanted, reason: complexity ? 'planned' : 'default' }\n }\n const at = MODEL_TIERS.indexOf(wanted)\n let best: ModelTier | undefined\n let bestDistance = Infinity\n for (const tier of MODEL_TIERS) {\n if (!configured.has(tier)) {\n continue\n }\n const distance = Math.abs(MODEL_TIERS.indexOf(tier) - at)\n // `<=`: the list runs weakest first, so on a tie the later (stronger) tier wins.\n if (distance <= bestDistance) {\n best = tier\n bestDistance = distance\n }\n }\n if (!best) {\n throw new Error('no executor tier is configured')\n }\n return { tier: best, reason: 'fallback' }\n}\n\n// The next configured tier above `tier`, or undefined when it is the strongest one.\nexport const nextStrongerTier = (\n tier: ModelTier,\n configured: ReadonlySet<ModelTier>,\n): ModelTier | undefined =>\n MODEL_TIERS.slice(MODEL_TIERS.indexOf(tier) + 1).find((t) => configured.has(t))\n\nexport interface IResolvedEscalation {\n enabled: boolean\n maxPerStep: number\n maxPerRun: number\n}\n\nexport const DEFAULT_ESCALATIONS_PER_STEP = 1\nexport const DEFAULT_ESCALATIONS_PER_RUN = 3\n\nconst cap = (v: number | undefined, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : fallback\n\n/**\n * Escalation is ON by default once tiers are configured, and cannot be on without them. A host\n * that routes easy steps to a light model has accepted that the planner's rating may be wrong;\n * without escalation a mis-rated step fails outright and the replanner (another paid call) has\n * to plan around a failure that a model the host already configured would not have had. The cost\n * is bounded: one retry per step and three per run unless the host says otherwise.\n */\nexport const resolveEscalation = (\n setting: boolean | EscalationConfig | undefined,\n tiersActive: boolean,\n): IResolvedEscalation => {\n const cfg = typeof setting === 'object' && setting !== null ? setting : {}\n const maxPerStep = cap(cfg.maxPerStep, DEFAULT_ESCALATIONS_PER_STEP)\n const maxPerRun = cap(cfg.maxPerRun, DEFAULT_ESCALATIONS_PER_RUN)\n return {\n enabled: tiersActive && setting !== false && maxPerStep > 0 && maxPerRun > 0,\n maxPerStep,\n maxPerRun,\n }\n}\n\nconst nameOf = (v: unknown): string =>\n v && typeof v === 'object' && typeof (v as { name?: unknown }).name === 'string'\n ? (v as { name: string }).name\n : ''\n\nconst textOf = (v: unknown): string => {\n if (typeof v === 'string') {\n return v\n }\n if (v && typeof v === 'object' && typeof (v as { message?: unknown }).message === 'string') {\n return (v as { message: string }).message\n }\n return ''\n}\n\n// A failed call the USER (or the approval policy) refused: a bigger model must not get a second\n// go at something a person said no to.\nexport const isDeniedOutput = (output: unknown): boolean =>\n nameOf(output) === 'ToolDeniedError' || /Tool call denied by the user/.test(textOf(output))\n\n// A failed call the run's tool-call budget refused.\nexport const isBudgetOutput = (output: unknown): boolean =>\n nameOf(output) === 'ToolBudgetError' || /tool-call budget exhausted/i.test(textOf(output))\n\n// A failed call whose ARGUMENTS the model got wrong (they did not parse, or did not match the\n// tool's schema) - the AI SDK's InvalidToolInputError (which reaches the trace as its text), or\n// the prompted path's own message.\nexport const isInvalidArgumentsOutput = (output: unknown): boolean =>\n /InvalidToolInput|InvalidToolArguments|ToolCallRepair/.test(nameOf(output)) ||\n /InvalidToolInputError|Invalid input for tool |^invalid args for \"/i.test(textOf(output))\n\n// \"Repeatedly\": the same tool was called with bad arguments at least twice in the attempt and\n// never got a good call in after the last of them.\nconst argumentsKeptFailing = (calls: IStepResult['toolCalls']): boolean => {\n const bad = new Map<string, number[]>()\n calls.forEach((c, i) => {\n if (!c.ok && isInvalidArgumentsOutput(c.output)) {\n bad.set(c.name, [...(bad.get(c.name) ?? []), i])\n }\n })\n return [...bad].some(\n ([name, at]) =>\n at.length >= 2 && !calls.slice(at[at.length - 1] + 1).some((c) => c.ok && c.name === name),\n )\n}\n\n// What one executor attempt at a step came to, as far as escalation needs to know.\nexport interface IAttemptOutcome {\n toolCalls: IStepResult['toolCalls']\n blocked: boolean\n // The model wrote no text at all.\n empty: boolean\n // The last model call ended on the output cap (finishReason 'length').\n cut: boolean\n // A run-level budget (tokens, tool calls) stopped the attempt.\n stopped: boolean\n}\n\n/**\n * Why an attempt that RETURNED should be retried on a stronger model, or undefined when it should\n * not. Never for an attempt a budget stopped, or one in which the user (or the approval policy)\n * denied a tool: those are not the model's failures.\n */\nexport const escalationReasonOf = (o: IAttemptOutcome): EscalationReason | undefined => {\n if (o.stopped || o.toolCalls.some((c) => !c.ok && isBudgetOutput(c.output))) {\n return undefined\n }\n if (o.toolCalls.some((c) => !c.ok && isDeniedOutput(c.output))) {\n return undefined\n }\n if (o.cut) {\n return 'output-cut'\n }\n if (o.blocked) {\n return 'blocked'\n }\n if (argumentsKeptFailing(o.toolCalls)) {\n return 'tool-arguments'\n }\n if (o.empty && !o.toolCalls.some((c) => c.ok)) {\n return 'empty-result'\n }\n return undefined\n}\n\nconst statusIn = (\n err: unknown,\n match: (status: number) => boolean,\n seen: Set<unknown> = new Set(),\n): boolean => {\n if (!err || typeof err !== 'object' || seen.has(err)) {\n return false\n }\n seen.add(err)\n const e = err as { statusCode?: number; status?: number; cause?: unknown; lastError?: unknown }\n const status = e.statusCode ?? e.status\n if (typeof status === 'number' && match(status)) {\n return true\n }\n return statusIn(e.cause, match, seen) || statusIn(e.lastError, match, seen)\n}\n\n/**\n * Whether an attempt that THREW may be retried on a stronger model. Not a stop or a timeout (the\n * call was cut, not wrong), not refused credentials (401 / 403: the next call fails the same way\n * and the host must hear about it), not a rate limit (429: that is for retry and backoff, and a\n * bigger model on the same account is the last thing to send), not a denial or a spent budget.\n */\nexport const isEscalatableError = (err: unknown): boolean => {\n const name = nameOf(err)\n if (name === 'AbortError' || name === 'TimeoutError') {\n return false\n }\n if (isDeniedOutput(err) || isBudgetOutput(err)) {\n return false\n }\n return !statusIn(err, (s) => s === 401 || s === 403 || s === 429)\n}\n\n// One attempt at a step that a stronger model now continues.\nexport interface IEarlierAttempt {\n tier: ModelTier\n reason: EscalationReason\n // What the attempt said (its summary, or the error it died of).\n summary: string\n toolCalls: IStepResult['toolCalls']\n}\n\nconst INPUT_CHARS = 400\nconst OUTPUT_CHARS = 1500\n\nconst asText = (v: unknown, max: number): string => {\n let s: string\n try {\n s = typeof v === 'string' ? v : (JSON.stringify(v) ?? String(v))\n } catch {\n s = String(v)\n }\n return s.length > max ? `${s.slice(0, max)}... [truncated, ${s.length - max} chars]` : s\n}\n\nconst WHY: Record<EscalationReason, string> = {\n blocked: 'it reported that it was blocked',\n 'empty-result': 'it produced no result',\n 'tool-arguments': 'it kept calling a tool with arguments that did not parse',\n 'output-cut': 'its output was cut off by the output cap',\n error: 'its model call failed',\n}\n\n/**\n * What the stronger model is shown of the attempts before it - in the USER prompt, so the system\n * prompt stays run-stable. It names every tool call with its arguments and result, because the\n * calls that succeeded HAPPENED: the step continues from them, it does not start over.\n */\nexport const renderEarlierAttempts = (attempts: IEarlierAttempt[]): string => {\n if (attempts.length === 0) {\n return ''\n }\n const blocks = attempts.map((a, i) => {\n const calls = a.toolCalls.length\n ? a.toolCalls\n .map(\n (c) =>\n ` - ${c.name} ${asText(c.input, INPUT_CHARS)} -> ${c.ok ? 'ok' : 'FAILED'}: ${asText(c.output, OUTPUT_CHARS)}`,\n )\n .join('\\n')\n : ' (no tool calls)'\n return [\n `Attempt ${i + 1} (${a.tier} model) stopped because ${WHY[a.reason]}.`,\n ` It said: ${asText(a.summary, OUTPUT_CHARS) || '(nothing)'}`,\n ' Tool calls it made:',\n calls,\n ].join('\\n')\n })\n return [\n 'EARLIER ATTEMPT AT THIS STEP - a smaller model started this step and did not finish it. You are continuing it, not starting over.',\n 'Every tool call below marked ok was REALLY executed and its effect is already in place: do not make it again, use its result. Redo only what FAILED or is still missing.',\n ...blocks,\n ].join('\\n')\n}\n\nconst stable = (v: unknown): unknown => {\n if (Array.isArray(v)) {\n return v.map(stable)\n }\n if (v && typeof v === 'object') {\n return Object.fromEntries(\n Object.keys(v as object)\n .sort()\n .map((k) => [k, stable((v as Record<string, unknown>)[k])]),\n )\n }\n return v\n}\n\n// Identity of a tool call: its name and its arguments, key order aside.\nexport const toolCallKey = (name: string, input: unknown): string => {\n try {\n return `${name}\\u0000${JSON.stringify(stable(input)) ?? ''}`\n } catch {\n return `${name}\\u0000${String(input)}`\n }\n}\n\n/**\n * The writes of the step in flight, kept while it may be escalated. A stronger model continuing\n * the step is TOLD what was already done; this is what makes it true even if it does not listen:\n * a call to a tool that is not read-only, with the same arguments as a call that already\n * succeeded in an EARLIER attempt at this step, is not executed again - it gets the earlier\n * result back. Within one attempt nothing changes (a model may repeat a call there as it always\n * could), and read-only tools are never held back.\n */\nexport interface IStepWrites {\n // 0 for the first attempt, +1 per escalation.\n attempt: number\n done: Map<string, { attempt: number; output: unknown }>\n}\n\nexport const createStepWrites = (): IStepWrites => ({ attempt: 0, done: new Map() })\n\n// The earlier result to hand back instead of running the call, or undefined to run it.\nexport const replayedWrite = (\n writes: IStepWrites | undefined,\n name: string,\n input: unknown,\n): { output: unknown } | undefined => {\n const hit = writes?.done.get(toolCallKey(name, input))\n return hit && hit.attempt < writes!.attempt ? { output: hit.output } : undefined\n}\n\nexport const recordWrite = (\n writes: IStepWrites | undefined,\n name: string,\n input: unknown,\n output: unknown,\n): void => {\n writes?.done.set(toolCallKey(name, input), { attempt: writes.attempt, output })\n}\n\nexport const REPLAY_NOTE =\n '[not run again: this exact call already succeeded in an earlier attempt at this step, and its effect is in place. Its result then:]'\n\nexport const replayOutput = (output: unknown): string => `${REPLAY_NOTE} ${asText(output, 20_000)}`\n\n/**\n * Whether a tool call's `output` (in a `step.tool-result` event or a step's `toolCalls`) is the\n * answer to a write that was NOT run again: the same call already succeeded in an earlier attempt\n * at the step, and the model was handed that result under `REPLAY_NOTE`. For a UI that marks such\n * a call instead of showing it as a second execution.\n */\nexport const isReplayedToolOutput = (output: unknown): boolean =>\n typeof output === 'string' && output.startsWith(REPLAY_NOTE)\n","import type { Tool, ToolSet } from 'ai'\n\n/**\n * The canonical tool shape is the AI SDK `Tool` — the same object the native\n * tool-calling path passes straight to `streamText({ tools })`, and the same\n * shape MCP tools take. We add one optional field, `promptHint`, a short\n * human-readable parameter hint (e.g. \"{ text: string, x?: number }\") used only\n * by the prompted/salvage path when it renders the tool catalogue into a text\n * prompt for weak local models.\n */\nexport type AgentTool = Tool & { promptHint?: string; readOnly?: boolean }\n\n/** A named collection of tools — a plain AI SDK ToolSet, usable directly. */\nexport type AgentToolSet = ToolSet\n\n/** Read the optional promptHint attached by defineTool, if any. */\nexport const promptHintOf = (tool: Tool): string | undefined =>\n typeof (tool as { promptHint?: unknown }).promptHint === 'string'\n ? (tool as { promptHint?: string }).promptHint\n : undefined\n","import { asSchema, type Tool, type ToolSet } from 'ai'\nimport type { IPlanStep, IUsage } from '../agent/loop-types.js'\nimport type { RunControlPort } from '../agent/control.js'\nimport type { AgentEvent, UsagePhase } from '../events.js'\nimport { ToolBudgetError } from '../limits.js'\nimport {\n decideToolPermission,\n gateToolCall,\n isCodeExecutionTool,\n isReadOnlyTool,\n type ApprovalState,\n} from './approval.js'\nimport { recordWrite, replayOutput, replayedWrite, type IStepWrites } from '../tiers.js'\nimport { promptHintOf } from './types.js'\nimport type { SpawnRun } from '../subagent/dynamic.js'\nimport type { IWaitClock } from '../wait-clock.js'\n\n/**\n * What a tool's `execute` can reach of the run that called it, passed as\n * `options.agentRun`. Subagent tools use it to stream nested events and to\n * charge their usage to the parent run.\n */\nexport interface ToolRunContext {\n emit: (event: AgentEvent) => void\n /** The plan step being executed, when there is one. */\n step?: IPlanStep\n signal?: AbortSignal\n /**\n * Add what was spent on the parent's behalf to the run: a subagent's tokens (the default\n * phase, 'subagent'), a media model's call (phase 'media'), or a grounded search's tokens\n * (phase 'search').\n */\n addUsage: (usage: IUsage, phase?: UsagePhase) => void\n /** The run's usage so far (media tools read their per-run call count from it). */\n usage?: () => IUsage\n /**\n * Run the agent's consent gate for a call made on its behalf (e.g. a host\n * tool a subagent calls). Resolves when allowed, throws ToolDeniedError.\n */\n approve: (toolName: string, input: unknown, readOnly: boolean) => Promise<void>\n /** The run's control, when the host passed one: subagents register here so they can be listed and stopped. */\n control?: RunControlPort\n /** The run's id (for provenance). */\n runId?: string\n /** Pages web_fetch read in this run (origin + path), kept as provenance for any lesson the run writes. */\n fetched?: string[]\n /** Internal - what the built-in `spawn_subagent` tool reads of the run (`subagents.dynamic`). */\n spawn?: SpawnRun\n /**\n * Set on the run of a helper the model started (`subagents.dynamic`): the call is the\n * helper's, not the run's the host started. An MCP tool reads it to decide whether the call\n * may ask the user something (`onElicitation`, `elicitation.subagents`).\n */\n subagent?: { id: string; depth: number }\n /**\n * The questions MCP servers asked the user in this run (`onElicitation`): one object per run,\n * shared with the helpers it starts (`elicitation.maxPerRun`).\n */\n elicitations?: { count: number }\n /**\n * Internal - the run's clock (wait-clock.ts): the step's `chatTimeoutMs` and the time limits\n * of the subagents the run's tool calls start are deadlines of it, and whoever asks a person\n * something on the run's behalf (the consent gate, an MCP question) pauses it for the wait.\n */\n clock?: IWaitClock\n /**\n * Internal - the skills of MCP servers the run acts on, its callers' included: a call of a\n * tool that runs code is asked while there is one (`decideToolPermission`). A helper the model\n * starts inherits it.\n */\n mcpSkills?: () => string[]\n}\n\n/** Read the run context the agent passes to a tool's execute (undefined outside a run). */\nexport const toolRunContextOf = (options: unknown): ToolRunContext | undefined =>\n (options as { agentRun?: ToolRunContext } | undefined)?.agentRun\n\nconst truncated = (s: string, max: number): string =>\n s.length > max ? `${s.slice(0, max)}… [truncated ${s.length - max} chars]` : s\n\nconst toText = (v: unknown): string => {\n if (typeof v === 'string') return v\n try {\n return JSON.stringify(v) ?? String(v)\n } catch {\n return String(v)\n }\n}\n\ntype ToModelOutput = NonNullable<Tool['toModelOutput']>\n\n/**\n * Cap what the MODEL sees of a tool result at `maxChars` (the raw output still\n * reaches events and the trace). A tool's own `toModelOutput` runs first.\n */\nexport const limitModelOutput = (\n original: Tool['toModelOutput'],\n maxChars: number,\n): ToModelOutput =>\n (async (opts: Parameters<ToModelOutput>[0]) => {\n const base = original\n ? await original(opts)\n : typeof opts.output === 'string'\n ? ({ type: 'text', value: opts.output } as const)\n : ({ type: 'json', value: (opts.output ?? null) as never } as const)\n if (base.type === 'text' || base.type === 'error-text') {\n return { ...base, value: truncated(base.value, maxChars) }\n }\n if (base.type === 'json' || base.type === 'error-json') {\n const text = toText(base.value)\n if (text.length <= maxChars) return base\n return {\n type: base.type === 'json' ? 'text' : 'error-text',\n value: truncated(text, maxChars),\n }\n }\n return base\n }) as ToModelOutput\n\nexport interface WrapToolsOptions {\n approval: ApprovalState\n /** Names that skip the gate and the call budget (built-in meta-tools). */\n builtins: ReadonlySet<string>\n emit: (event: AgentEvent) => void\n step: () => IPlanStep | undefined\n signal?: AbortSignal\n addUsage: (usage: IUsage, phase?: UsagePhase) => void\n /** The run's usage so far, handed to tools through their run context. */\n usage?: () => IUsage\n /** Called before each counted call; throw to refuse it. */\n countCall: () => void\n maxToolOutputChars: number\n /** The run's control, handed to tools through their run context. */\n control?: RunControlPort\n runId?: string\n /** Shared with every call of the run, so a lesson can name what the run read. */\n fetched?: string[]\n /**\n * The writes of the step in flight, while that step may be escalated to a stronger tier (else\n * undefined, and nothing changes): a write that already succeeded in an EARLIER attempt at the\n * step is not executed again - the call gets the earlier result back (see `tiers.ts`).\n */\n stepWrites?: () => IStepWrites | undefined\n /** The run's place among the helpers the model starts, handed to tools through their run context. */\n spawn?: SpawnRun\n /** Set on a helper's own run: every consent request it makes carries it. */\n subagent?: { id: string; depth: number }\n /** The run's count of questions asked of the user, handed to tools through their run context. */\n elicitations?: { count: number }\n /** The run's clock: the gate pauses it while a person decides; handed to tools too. */\n clock?: IWaitClock\n /**\n * The skills of MCP servers the run acts on (its callers' included): while there is one, a\n * call of a tool that runs code (`isCodeExecutionTool`) is asked whatever the mode says.\n */\n mcpSkills?: () => string[]\n}\n\nconst isAsyncIterable = (v: unknown): v is AsyncIterable<unknown> =>\n typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n\n/** Record a call's result once it is known, without changing what `execute` returns or when. */\nconst recording = (out: unknown, record: (value: unknown) => void): unknown => {\n if (isAsyncIterable(out)) {\n return (async function* () {\n let last: unknown\n for await (const value of out) {\n last = value\n yield value\n }\n record(last)\n })()\n }\n if (out && typeof (out as { then?: unknown }).then === 'function') {\n return (out as Promise<unknown>).then((value) => {\n record(value)\n return value\n })\n }\n record(out)\n return out\n}\n\n/**\n * Wrap every tool for one run: the consent gate, the tool-call budget, the\n * model-facing output cap, and the run context passed as `options.agentRun`.\n * When the gate allows a call synchronously, `execute` is invoked without an\n * extra await, so a streaming tool keeps returning its iterable.\n */\nexport const wrapToolsForRun = (tools: ToolSet, o: WrapToolsOptions): ToolSet => {\n const out: ToolSet = {}\n const gate = (\n toolName: string,\n input: unknown,\n readOnly: boolean,\n signal?: AbortSignal,\n codeExecution?: boolean,\n ) =>\n gateToolCall(\n o.approval,\n {\n toolName,\n input,\n readOnly,\n step: o.step(),\n ...(o.subagent ? { subagent: o.subagent } : {}),\n ...(codeExecution ? { codeExecution, mcpSkills: o.mcpSkills?.() ?? [] } : {}),\n },\n {\n requested: (req) =>\n o.emit({\n type: 'tool.approval-requested',\n id: req.id,\n name: req.toolName,\n input: req.input,\n readOnly: req.readOnly,\n step: req.step,\n ...(req.subagent ? { subagent: req.subagent } : {}),\n ...(req.mcpSkills ? { mcpSkills: req.mcpSkills } : {}),\n }),\n resolved: (r) => o.emit({ type: 'tool.approval-resolved', ...r }),\n ...(o.clock ? { wait: o.clock.pause } : {}),\n },\n signal ?? o.signal,\n )\n for (const [name, t] of Object.entries(tools)) {\n const execute = (t as { execute?: (input: unknown, options: unknown) => unknown }).execute\n const builtin = o.builtins.has(name)\n const readOnly = builtin || isReadOnlyTool(t)\n const codeExecution = !builtin && isCodeExecutionTool(t)\n const wrapped: Record<string, unknown> = { ...t }\n if (o.maxToolOutputChars > 0) {\n wrapped.toModelOutput = limitModelOutput(t.toModelOutput, o.maxToolOutputChars)\n }\n if (typeof execute === 'function') {\n wrapped.execute = (input: unknown, options: unknown) => {\n // A read-only or built-in tool is never held back or recorded.\n const writes = readOnly ? undefined : o.stepWrites?.()\n // Before the consent gate and the budget: a call that is not made costs neither.\n const earlier = replayedWrite(writes, name, input)\n if (earlier) return replayOutput(earlier.output)\n const call = (): unknown => {\n if (!builtin) o.countCall()\n const agentRun: ToolRunContext = {\n emit: o.emit,\n step: o.step(),\n signal: o.signal,\n addUsage: o.addUsage,\n ...(o.usage ? { usage: o.usage } : {}),\n approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),\n ...(o.control ? { control: o.control } : {}),\n ...(o.runId ? { runId: o.runId } : {}),\n ...(o.fetched ? { fetched: o.fetched } : {}),\n ...(o.spawn ? { spawn: o.spawn } : {}),\n ...(o.subagent ? { subagent: o.subagent } : {}),\n ...(o.elicitations ? { elicitations: o.elicitations } : {}),\n ...(o.clock ? { clock: o.clock } : {}),\n ...(o.mcpSkills ? { mcpSkills: o.mcpSkills } : {}),\n }\n return execute.call(t, input, { ...(options as object), agentRun })\n }\n const run = (): unknown =>\n writes ? recording(call(), (value) => recordWrite(writes, name, input, value)) : call()\n if (builtin) return run()\n const permission = decideToolPermission({\n toolName: name,\n readOnly,\n mode: o.approval.mode,\n rules: o.approval.config.rules,\n remembered: o.approval.remembered,\n ...(codeExecution ? { codeExecution, mcpSkills: o.mcpSkills?.() ?? [] } : {}),\n })\n if (permission === 'allow') return run()\n return gate(\n name,\n input,\n readOnly,\n (options as { abortSignal?: AbortSignal } | undefined)?.abortSignal,\n codeExecution,\n ).then(run)\n }\n }\n out[name] = wrapped as Tool\n }\n return out\n}\n\n/** Throws ToolBudgetError once `cap` calls were made (cap ≤ 0 = unlimited). */\nexport const createCallCounter = (cap: number | undefined, initial = 0) => {\n // `initial` is a resumed run's count: the cap is per RUN, not per process.\n let calls = Math.max(0, Math.floor(initial))\n return {\n count: (): void => {\n if (cap && cap > 0 && calls >= cap) throw new ToolBudgetError(cap)\n calls += 1\n },\n get calls() {\n return calls\n },\n get exhausted() {\n return Boolean(cap && cap > 0 && calls >= cap)\n },\n }\n}\n\ntype JsonSchemaLike = {\n type?: string | string[]\n properties?: Record<string, JsonSchemaLike>\n required?: string[]\n items?: JsonSchemaLike\n enum?: unknown[]\n}\n\nconst typeHint = (s: JsonSchemaLike | undefined, depth: number): string => {\n if (!s) return 'any'\n if (Array.isArray(s.enum) && s.enum.length > 0 && s.enum.length <= 8) {\n return s.enum.map((v) => JSON.stringify(v)).join(' | ')\n }\n const type = Array.isArray(s.type) ? s.type.find((x) => x !== 'null') : s.type\n if (type === 'array') return `${typeHint(s.items, depth)}[]`\n if (type === 'object' || s.properties) {\n if (depth > 1 || !s.properties) return 'object'\n return objectHint(s, depth + 1)\n }\n return type ?? 'any'\n}\n\nconst objectHint = (s: JsonSchemaLike, depth = 0): string => {\n const required = new Set(s.required ?? [])\n const props = Object.entries(s.properties ?? {})\n if (props.length === 0) return '{}'\n return `{ ${props\n .slice(0, 12)\n .map(([k, v]) => `${k}${required.has(k) ? '' : '?'}: ${typeHint(v, depth)}`)\n .join(', ')}${props.length > 12 ? ', …' : ''} }`\n}\n\n/**\n * A short parameter hint (\"{ text: string, x?: number }\") derived from a\n * tool's JSON schema — so tools without a hand-written `promptHint` (every MCP\n * tool) still tell a prompted model what to pass. Undefined when unknown.\n */\nexport const schemaHintOf = async (t: Tool): Promise<string | undefined> => {\n const own = promptHintOf(t)\n if (own) return own\n try {\n const schema = (await asSchema(t.inputSchema as never).jsonSchema) as JsonSchemaLike\n return schema && typeof schema === 'object' ? objectHint(schema) : undefined\n } catch {\n return undefined\n }\n}\n","import { FILES_STORE, openAgentWebDB } from '../storage/db.js'\n\n/**\n * A small virtual file system for the browser — the agent's (and the user's)\n * workspace: attachments the user drops in, reports the agent writes, images\n * pasted into the chat. Persistent in IndexedDB by default, in-memory on\n * request (tests, private mode). Paths are POSIX-like and always absolute\n * (\"/notes/todo.md\"); there are no real directories — a \"directory\" is a path\n * prefix.\n */\nexport interface VirtualFile {\n path: string\n /** Text, or base64 for binary content (see `encoding`). */\n content: string\n encoding: 'utf8' | 'base64'\n mimeType: string\n /** Size of the decoded content in bytes. */\n size: number\n updatedAt: number\n}\n\n/** A listing entry (no content). */\nexport type VirtualFileInfo = Omit<VirtualFile, 'content'>\n\nexport interface VirtualFileSystemOptions {\n /** Keep files in memory only (default false: IndexedDB). */\n memory?: boolean\n /** IndexedDB database name, forwarded to the shared owner (default 'agent-web'). */\n dbName?: string\n /** Isolates several file systems in one database (default 'default'). */\n namespace?: string\n /** Refuse a single file larger than this many bytes (default 10 MB). */\n maxFileBytes?: number\n}\n\nexport type VfsListener = (change: { type: 'write' | 'delete'; path: string }) => void\n\nconst MIME: Record<string, string> = {\n txt: 'text/plain',\n md: 'text/markdown',\n json: 'application/json',\n csv: 'text/csv',\n html: 'text/html',\n css: 'text/css',\n js: 'text/javascript',\n ts: 'text/typescript',\n svg: 'image/svg+xml',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n pdf: 'application/pdf',\n xml: 'application/xml',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n}\n\n/** A best-effort MIME type from a file name. */\nexport const mimeFromPath = (path: string): string =>\n MIME[path.split('.').pop()?.toLowerCase() ?? ''] ?? 'application/octet-stream'\n\n/** True for MIME types the agent can read as text. */\nexport const isTextMime = (mime: string): boolean =>\n /^text\\/|json|xml|yaml|javascript|typescript|svg/.test(mime)\n\n/**\n * Normalise a path: absolute, forward slashes, no \".\" / \"..\" / empty segments.\n * Throws on a path that escapes the root.\n */\nexport const normalizePath = (input: string): string => {\n const parts: string[] = []\n for (const seg of String(input ?? '')\n .replace(/\\\\/g, '/')\n .split('/')) {\n if (!seg || seg === '.') continue\n if (seg === '..') {\n if (parts.length === 0) throw new Error(`path \"${input}\" escapes the root`)\n parts.pop()\n continue\n }\n parts.push(seg)\n }\n if (parts.length === 0) throw new Error('a file path is required')\n return `/${parts.join('/')}`\n}\n\nconst byteLength = (content: string, encoding: VirtualFile['encoding']): number =>\n encoding === 'base64'\n ? Math.floor((content.replace(/=+$/, '').length * 3) / 4)\n : new TextEncoder().encode(content).length\n\n/** Base64 of bytes, chunked so a large file can't blow the call stack. */\nexport const bytesToBase64 = (bytes: Uint8Array): string => {\n let bin = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(bin)\n}\n\nexport class VirtualFileSystem {\n private readonly memory?: Map<string, VirtualFile>\n private readonly dbName?: string\n private readonly ns: string\n private readonly maxFileBytes: number\n private readonly listeners = new Set<VfsListener>()\n\n constructor(opts: VirtualFileSystemOptions = {}) {\n if (opts.memory) this.memory = new Map()\n this.dbName = opts.dbName\n this.ns = opts.namespace ?? 'default'\n this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024\n }\n\n private key(path: string): string {\n return `${this.ns}:${path}`\n }\n\n /** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */\n onChange(listener: VfsListener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n private notify(type: 'write' | 'delete', path: string): void {\n for (const l of this.listeners) {\n try {\n l({ type, path })\n } catch {\n /* a bad listener must not break a write */\n }\n }\n }\n\n async write(\n path: string,\n content: string | Uint8Array,\n opts: { mimeType?: string; encoding?: VirtualFile['encoding'] } = {},\n ): Promise<VirtualFileInfo> {\n const p = normalizePath(path)\n const binary = content instanceof Uint8Array\n const encoding = binary ? 'base64' : (opts.encoding ?? 'utf8')\n const text = binary ? bytesToBase64(content) : content\n const size = binary ? content.length : byteLength(text, encoding)\n if (size > this.maxFileBytes) {\n throw new Error(`\"${p}\" is ${size} bytes; the limit is ${this.maxFileBytes}`)\n }\n const file: VirtualFile = {\n path: p,\n content: text,\n encoding,\n mimeType: opts.mimeType ?? mimeFromPath(p),\n size,\n updatedAt: Date.now(),\n }\n if (this.memory) this.memory.set(p, file)\n else {\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.put(FILES_STORE, file, this.key(p))\n }\n this.notify('write', p)\n const { content: _drop, ...info } = file\n return info\n }\n\n /** Store a data URL (\"data:image/png;base64,…\") as a file. */\n async writeDataUrl(path: string, dataUrl: string): Promise<VirtualFileInfo> {\n const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(dataUrl)\n if (!m) throw new Error('not a data URL')\n const mimeType = m[1] ?? 'application/octet-stream'\n return m[2]\n ? this.write(path, m[3], { mimeType, encoding: 'base64' })\n : this.write(path, decodeURIComponent(m[3]), { mimeType })\n }\n\n async read(path: string): Promise<VirtualFile | undefined> {\n const p = normalizePath(path)\n if (this.memory) return this.memory.get(p)\n const db = await openAgentWebDB({ dbName: this.dbName })\n return (await db.get(FILES_STORE, this.key(p))) as VirtualFile | undefined\n }\n\n /** The file as a data URL (for <img src>, downloads). */\n async readDataUrl(path: string): Promise<string | undefined> {\n const f = await this.read(path)\n if (!f) return undefined\n return f.encoding === 'base64'\n ? `data:${f.mimeType};base64,${f.content}`\n : `data:${f.mimeType};charset=utf-8,${encodeURIComponent(f.content)}`\n }\n\n async delete(path: string): Promise<boolean> {\n const p = normalizePath(path)\n let existed: boolean\n if (this.memory) existed = this.memory.delete(p)\n else {\n const db = await openAgentWebDB({ dbName: this.dbName })\n existed = (await db.get(FILES_STORE, this.key(p))) !== undefined\n await db.delete(FILES_STORE, this.key(p))\n }\n if (existed) this.notify('delete', p)\n return existed\n }\n\n /** Files under a prefix (\"/\" = all), sorted by path. */\n async list(prefix = '/'): Promise<VirtualFileInfo[]> {\n const dir = prefix === '/' ? '/' : `${normalizePath(prefix)}/`\n let files: VirtualFile[]\n if (this.memory) files = [...this.memory.values()]\n else {\n const db = await openAgentWebDB({ dbName: this.dbName })\n const range = IDBKeyRange.bound(`${this.ns}:`, `${this.ns}:￿`)\n files = (await db.getAll(FILES_STORE, range)) as VirtualFile[]\n }\n return files\n .filter((f) => dir === '/' || f.path.startsWith(dir))\n .map(({ content: _drop, ...info }) => info)\n .sort((a, b) => a.path.localeCompare(b.path))\n }\n\n /** Remove every file (of this namespace). */\n async clear(): Promise<void> {\n for (const f of await this.list()) await this.delete(f.path)\n }\n}\n","import { jsonSchema, tool, type ToolSet } from 'ai'\nimport { markReadOnly } from '../tools/approval.js'\nimport { toolRunContextOf } from '../tools/wrap.js'\nimport { isTextMime, normalizePath, type VirtualFileSystem } from './vfs.js'\n\nexport interface FileToolsOptions {\n /** Tool-name prefix (default 'fs_' → fs_list, fs_read, fs_write, fs_delete). */\n prefix?: string\n /** Mount only the read tools (default false). */\n readOnly?: boolean\n /** Cap on the text fs_read returns (default 50 000 chars; the rest is cut with a marker). */\n maxReadChars?: number\n}\n\nconst FILE_TOOL = Symbol.for('@dudko.dev/agent-web:file-tool')\n\n/** What one of these tools does, and on which file system (read by `config.sandbox`). */\nexport interface FileToolBinding {\n vfs: VirtualFileSystem\n op: 'list' | 'read' | 'write' | 'delete'\n}\n\nconst bind = <T extends object>(t: T, binding: FileToolBinding): T => {\n Object.defineProperty(t, FILE_TOOL, { value: binding, enumerable: false })\n return t\n}\n\n/** The file-system binding of a tool made by `createFileTools` (undefined for any other tool). */\nexport const fileToolBindingOf = (t: unknown): FileToolBinding | undefined =>\n t && typeof t === 'object' ? (t as { [FILE_TOOL]?: FileToolBinding })[FILE_TOOL] : undefined\n\n/**\n * Tools that give the agent the virtual file system: list, read, write and\n * delete. Listing and reading are marked read-only, so the `ask-writes`\n * consent mode lets them through and asks before writes and deletes.\n */\nexport const createFileTools = (vfs: VirtualFileSystem, opts: FileToolsOptions = {}): ToolSet => {\n const p = opts.prefix ?? 'fs_'\n const maxRead = opts.maxReadChars ?? 50_000\n const tools: ToolSet = {\n [`${p}list`]: markReadOnly(\n tool({\n description:\n 'List the files in the workspace (attachments the user added, files you wrote). Optionally only under a directory prefix.',\n inputSchema: jsonSchema<{ prefix?: string }>({\n type: 'object',\n properties: { prefix: { type: 'string', description: 'Directory prefix, e.g. \"/docs\"' } },\n additionalProperties: false,\n }),\n execute: async ({ prefix }) =>\n (await vfs.list(prefix || '/')).map((f) => ({\n path: f.path,\n mimeType: f.mimeType,\n size: f.size,\n })),\n }),\n ),\n [`${p}read`]: markReadOnly(\n tool({\n description: 'Read a text file from the workspace by its path.',\n inputSchema: jsonSchema<{ path: string }>({\n type: 'object',\n properties: { path: { type: 'string', description: 'Absolute path, e.g. \"/notes.md\"' } },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async ({ path }) => {\n const f = await vfs.read(path)\n if (!f) {\n const known = (await vfs.list()).map((x) => x.path).slice(0, 30)\n throw new Error(`no file \"${path}\"; files: ${known.join(', ') || 'none'}`)\n }\n if (f.encoding === 'base64' && !isTextMime(f.mimeType)) {\n return `\"${f.path}\" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`\n }\n const text = f.encoding === 'base64' ? atob(f.content) : f.content\n return text.length > maxRead\n ? `${text.slice(0, maxRead)}… [truncated ${text.length - maxRead} chars]`\n : text\n },\n }),\n ),\n }\n bind(tools[`${p}list`], { vfs, op: 'list' })\n bind(tools[`${p}read`], { vfs, op: 'read' })\n if (opts.readOnly) return tools\n tools[`${p}write`] = tool({\n description:\n 'Write a text file to the workspace (creates or replaces it). Use it for reports, drafts, data the user should be able to open.',\n inputSchema: jsonSchema<{ path: string; content: string; mimeType?: string }>({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path, e.g. \"/reports/summary.md\"' },\n content: { type: 'string', description: 'The full file content' },\n mimeType: { type: 'string', description: 'Optional MIME type (guessed from the name)' },\n },\n required: ['path', 'content'],\n additionalProperties: false,\n }),\n execute: async ({ path, content, mimeType }, options) => {\n const info = await vfs.write(path, content, mimeType ? { mimeType } : {})\n // Tell the run what was written (a UI shows it in the turn). Only after the write succeeded.\n const run = toolRunContextOf(options)\n run?.emit({\n type: 'file.written',\n path: info.path,\n mediaType: info.mimeType,\n bytes: info.size,\n ...(run.step ? { step: run.step } : {}),\n })\n return { written: info.path, size: info.size }\n },\n })\n tools[`${p}delete`] = tool({\n description: 'Delete a file from the workspace.',\n inputSchema: jsonSchema<{ path: string }>({\n type: 'object',\n properties: { path: { type: 'string' } },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async ({ path }, options) => {\n const deleted = await vfs.delete(path)\n const run = toolRunContextOf(options)\n if (deleted) {\n run?.emit({\n type: 'file.deleted',\n path: normalizePath(path),\n ...(run.step ? { step: run.step } : {}),\n })\n }\n return { deleted }\n },\n })\n bind(tools[`${p}write`], { vfs, op: 'write' })\n bind(tools[`${p}delete`], { vfs, op: 'delete' })\n return tools\n}\n"],"mappings":";;;;;;;AAmCA,IAAM,OAAO,CAAC,OAA2BA,SACvC,OAAOA,SAAQ,YAAYA,OAAM,MAAM,SAAS,MAAMA;AAMjD,IAAM,cAAc,CACzB,OACA,WAC4B;AAC5B,MAAI,CAAC,O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A,IACb,aAAa,WAA6B;AAAA,MACxC,MAAM;AAAA,MACN,YAAY,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE;AAAA,MACvC,UAAU,CAAC,MAAM;AAAA,MACjB,sBAAsB;AAAA,IACxB,CAAC;AAAA,IACD,SAAS,OAAO,EAAE,KAAK,GAAG,YAAY;AACpC,YAAM,UAAU,MAAM,IAAI,OAAO,IAAI;AACrC,YAAM,MAAM,iBAAiB,OAAO;AACpC,UAAI,SAAS;AACX,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,MAAM,cAAc,IAAI;AAAA,UACxB,GAAI,IAAI,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;AAAA,QACvC,CAAC;AAAA,MACH;AACA,aAAO,EAAE,QAAQ;AAAA,IACnB;AAAA,EACF,CAAC;AACD,OAAK,MAAM,GAAG,CAAC,OAAO,GAAG,EAAE,KAAK,IAAI,QAAQ,CAAC;AAC7C,OAAK,MAAM,GAAG,CAAC,QAAQ,GAAG,EAAE,KAAK,IAAI,SAAS,CAAC;AAC/C,SAAO;AACT;","names":["cap","tool","tool","cap"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sandbox/engine.ts"],"sourcesContent":["// The JavaScript sandbox behind `config.sandbox` / the `run_js` tool: the guest runs in QuickJS\n// compiled to WebAssembly (the optional peer `quickjs-emscripten`), never in the host's own\n// JavaScript engine. This file is the part both packages share - limits, the guest's runtime,\n// the module resolver, the worker protocol and what is allowed back across the boundary.\n//\n// It is pure (no imports, no node:* and no DOM) and is a COPY, byte for byte, of the sibling\n// package's file: `packages/agent/src/sandbox-engine.ts` = `packages/agent-web/src/sandbox/engine.ts`.\n// Change both; the Node package's `tests/sandbox-engine.test.ts` compares them.\n//\n// Security boundary. What the guest can reach is exactly what `bootstrap` hands it: console,\n// timers, and - only when the host passes them - a module map and named file operations. Every\n// value that crosses is a string produced inside the guest and re-parsed here, never a host\n// reference. Every guard has a test and a mutation check (see the two packages' sandbox tests).\n\nexport const RUN_JS_TOOL = 'run_js'\nexport const SANDBOX_PACKAGE = 'quickjs-emscripten'\n\nexport interface ISandboxConfig {\n // Time one run may take, in ms (default 5000, at most 60000), counted from the program's first\n // instruction: starting the worker and the engine does not count, and neither does waiting for\n // a file operation - a consent prompt included.\n timeoutMs?: number\n // The guest's memory, in bytes: the whole WebAssembly memory of its engine instance, the\n // engine's own 16 MiB included (default 32 MiB, at least 16 MiB, at most 256 MiB).\n memoryLimitBytes?: number\n // What a run returns to the model, stdout and result together, in characters (default 8000).\n maxOutputChars?: number\n // The longest program accepted, in characters (default 100000).\n maxCodeChars?: number\n // Let the guest import / require workspace files and use `fs` (default true where the agent\n // has a workspace; without one there is nothing to bind and this is ignored).\n files?: boolean\n}\n\nexport interface ISandboxLimits {\n timeoutMs: number\n memoryLimitBytes: number\n maxOutputChars: number\n maxCodeChars: number\n}\n\nconst MIB = 1024 * 1024\n\nexport const SANDBOX_DEFAULTS: ISandboxLimits = {\n timeoutMs: 5000,\n memoryLimitBytes: 32 * MIB,\n maxOutputChars: 8000,\n maxCodeChars: 100_000,\n}\n\n// A host cannot configure past these: the tool is for checking a piece of code, not for hosting one.\nexport const SANDBOX_CAPS: ISandboxLimits = {\n timeoutMs: 60_000,\n memoryLimitBytes: 256 * MIB,\n maxOutputChars: 100_000,\n maxCodeChars: 1_000_000,\n}\n\nconst SANDBOX_FLOORS: ISandboxLimits = {\n timeoutMs: 50,\n // What the engine's WebAssembly module asks for before it runs anything.\n memoryLimitBytes: 16 * MIB,\n maxOutputChars: 200,\n maxCodeChars: 100,\n}\n\n// One module the guest may load, and all of them together (characters).\nexport const SANDBOX_MAX_MODULES = 64\nexport const SANDBOX_MAX_MODULE_CHARS_TOTAL = 2_000_000\n// A file the guest reads or writes through `fs` (characters), and the calls of one run.\nexport const SANDBOX_MAX_FILE_CHARS = 1_000_000\nexport const SANDBOX_MAX_HOST_CALLS = 500\nexport const SANDBOX_MODULE_EXTENSIONS: readonly string[] = ['.js', '.mjs', '.json']\n\nconst MAX_TIMERS = 1000\n// QuickJS's own stack check. Small on purpose: wasm frames live on the host thread's native\n// stack, and a deeper guest recursion would overflow THAT before QuickJS noticed.\nconst GUEST_STACK_BYTES = 256 * 1024\nconst ERROR_NAME_CHARS = 200\nconst ERROR_TEXT_CHARS = 4000\n\nconst bounded = (value: unknown, key: keyof ISandboxLimits): number => {\n const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : NaN\n if (Number.isNaN(n) || n <= 0) {\n return SANDBOX_DEFAULTS[key]\n }\n return Math.min(SANDBOX_CAPS[key], Math.max(SANDBOX_FLOORS[key], n))\n}\n\nexport const resolveSandboxLimits = (config: ISandboxConfig | undefined): ISandboxLimits => ({\n timeoutMs: bounded(config?.timeoutMs, 'timeoutMs'),\n memoryLimitBytes: bounded(config?.memoryLimitBytes, 'memoryLimitBytes'),\n maxOutputChars: bounded(config?.maxOutputChars, 'maxOutputChars'),\n maxCodeChars: bounded(config?.maxCodeChars, 'maxCodeChars'),\n})\n\nexport interface ISandboxError {\n name: string\n message: string\n // Guest frames only: the host's own frames never cross.\n stack?: string\n}\n\n// What `run_js` returns to the model.\nexport interface ISandboxResult {\n ok: boolean\n // console.log / info / warn / error, in the order they were called.\n stdout: string\n // The value of the last expression (a module's default export), as JSON-like data.\n result?: unknown\n error?: ISandboxError\n // stdout or result was cut to fit `maxOutputChars`.\n truncated: boolean\n durationMs: number\n}\n\nexport type SandboxHostOp = 'readFile' | 'writeFile' | 'readdir'\n\n// One run, as it is posted to the engine. Structured-cloneable.\nexport interface ISandboxRequest {\n code: string\n // The path the code is evaluated as (stack traces, the base of relative imports).\n filename?: string\n limits: ISandboxLimits\n // Workspace files the guest may `import` / `require`, by absolute path. Absent = no loader.\n modules?: Record<string, string>\n // The `fs` functions the host serves. Absent or empty = no `fs`.\n hostOps?: SandboxHostOp[]\n}\n\n// Serves one `fs` call of the guest. Arguments and the answer are JSON-like data.\nexport type SandboxHostCall = (op: string, args: unknown[]) => Promise<unknown>\n\nexport class SandboxUnavailableError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SandboxUnavailableError'\n }\n}\n\nexport const sandboxPeerMissing = (detail?: string): SandboxUnavailableError =>\n new SandboxUnavailableError(\n `The sandbox (${RUN_JS_TOOL}) needs the optional package \"${SANDBOX_PACKAGE}\", which is not installed. ` +\n `Add it to your app: npm install ${SANDBOX_PACKAGE}${detail ? ` (${detail})` : ''}`,\n )\n\n// The run-stable sentences the stage prompts carry when the sandbox is on (both packages say the same).\nexport const sandboxPromptNote = (files: boolean): string =>\n `${RUN_JS_TOOL} runs JavaScript you wrote in an isolated sandbox and returns what it printed (console.log) and the value of its last expression. ` +\n `It is plain JavaScript on QuickJS (ES2023, top-level await), not Node and not a browser: no network, no npm packages, no process${\n files\n ? '; workspace files are reachable by relative path (import / require of .js, .mjs, .json) and through the async fs.readFile / fs.writeFile / fs.readdir'\n : ', no files'\n }. ` +\n `Never say that code was run, tested or printed something unless ${RUN_JS_TOOL} was called and returned it: quote its real output, and if it was not run, say so.`\n\nexport const SANDBOX_PLANNER_NOTE = `When the request needs code to be run, tested or checked on data, or a calculation that is easier to compute than to reason about, plan a step that calls ${RUN_JS_TOOL} for it.`\n\nexport const SANDBOX_SYNTHESIZER_NOTE = `Report the output of running code only when a ${RUN_JS_TOOL} call returned it; if the code was written but not run, say it was not run.`\n\nconst clip = (text: string, max: number): string => (text.length > max ? text.slice(0, max) : text)\n\nconst errorText = (err: unknown): string => {\n if (err instanceof Error) {\n return `${err.name}: ${err.message}`\n }\n return typeof err === 'string' ? err : 'unknown error'\n}\n\nconst dirname = (path: string): string => {\n const i = path.lastIndexOf('/')\n return i <= 0 ? '/' : path.slice(0, i)\n}\n\n// Resolve what the guest asked to load against the file that asked. Throws (with a message for\n// the model) on anything that is not a workspace file by path: a package, a Node built-in, a\n// path that climbs out of the root, an extension outside the allowed three.\nexport const resolveModulePath = (base: string, specifier: string): string => {\n const spec = String(specifier)\n if (!/^(\\.{1,2}\\/|\\/)/.test(spec) || /[\\\\\\0]/.test(spec)) {\n throw new Error(\n `Cannot load \"${clip(spec, 200)}\": the sandbox has no packages and no Node or browser modules - only workspace files by path (\"./lib.js\")`,\n )\n }\n const parts: string[] = spec.startsWith('/') ? [] : dirname(base).split('/').filter(Boolean)\n for (const seg of spec.split('/')) {\n if (!seg || seg === '.') {\n continue\n }\n if (seg === '..') {\n if (parts.length === 0) {\n throw new Error(`Cannot load \"${clip(spec, 200)}\": the path leaves the workspace`)\n }\n parts.pop()\n continue\n }\n parts.push(seg)\n }\n const path = `/${parts.join('/')}`\n if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) {\n throw new Error(\n `Cannot load \"${clip(path, 200)}\": only ${SANDBOX_MODULE_EXTENSIONS.join(', ')} files can be imported`,\n )\n }\n return path\n}\n\n// The literal specifiers a source names (import / export-from / import() / require). Used by the\n// host to hand the guest exactly the files a program refers to. A regex, not a parser: a match\n// inside a string or a comment only costs one more read of a real workspace file.\nexport const moduleSpecifiersOf = (source: string): string[] => {\n const found = new Set<string>()\n const patterns = [\n /\\bimport\\s*(?:[\\w$*{}\\s,]*?\\bfrom\\s*)?(['\"])([^'\"\\n]+)\\1/g,\n /\\bexport\\s*[\\w$*{}\\s,]*?\\bfrom\\s*(['\"])([^'\"\\n]+)\\1/g,\n /\\b(?:import|require)\\s*\\(\\s*(['\"])([^'\"\\n]+)\\1\\s*\\)/g,\n ]\n for (const re of patterns) {\n for (const m of source.matchAll(re)) {\n found.add(m[2])\n }\n }\n return [...found]\n}\n\n// Static import / export declarations make the program an ES module (its result is then the\n// default export); everything else is a script whose result is its last expression.\nconst looksLikeModule = (code: string): boolean =>\n /(^|[\\n;])\\s*(import\\s*[\\w$*{'\"]|export\\s+[\\w$*{])/.test(code)\n\n// JS_EVAL_FLAG_ASYNC: a script may use top-level await; its completion value arrives wrapped.\nconst EVAL_SCRIPT_ASYNC = 128\n\n// The guest's own runtime, evaluated inside it before the program. It may be tampered with by\n// the program (it shares its realm) - which only ever damages the program's own output: the\n// host takes nothing from it but strings.\nconst BOOTSTRAP = `(function (host, cfg) {\n 'use strict';\n var g = globalThis, J = JSON, S = String, E = Error, P = Promise, M = Map, R = Reflect;\n var hostLog = host.log, hostTimer = host.timer, hostClear = host.clear;\n var hostCall = host.call, hostResolve = host.resolve, hostCompile = host.compile;\n function inspect(v, depth, seen) {\n var t = typeof v;\n if (t === 'string') return depth ? J.stringify(v) : v;\n if (t === 'bigint') return S(v) + 'n';\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';\n if (t !== 'object' || v === null) return S(v);\n if (v instanceof E) return S(v.name) + ': ' + S(v.message) + (v.stack ? '\\\\n' + S(v.stack).replace(/\\\\n$/, '') : '');\n if (seen.indexOf(v) >= 0) return '[Circular]';\n if (depth > 4) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (v instanceof Date) return isNaN(v) ? 'Invalid Date' : v.toISOString();\n if (v instanceof RegExp) return S(v);\n seen.push(v);\n var parts = [], out, i, keys;\n if (Array.isArray(v)) {\n for (i = 0; i < v.length && i < 100; i++) parts.push(inspect(v[i], depth + 1, seen));\n if (v.length > 100) parts.push('... ' + (v.length - 100) + ' more');\n out = parts.length ? '[ ' + parts.join(', ') + ' ]' : '[]';\n } else if (v instanceof M) {\n v.forEach(function (val, key) { if (parts.length < 50) parts.push(inspect(key, depth + 1, seen) + ' => ' + inspect(val, depth + 1, seen)); });\n out = 'Map(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';\n } else if (v instanceof Set) {\n v.forEach(function (val) { if (parts.length < 50) parts.push(inspect(val, depth + 1, seen)); });\n out = 'Set(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';\n } else {\n keys = Object.keys(v);\n for (i = 0; i < keys.length && i < 50; i++) parts.push(keys[i] + ': ' + inspect(v[keys[i]], depth + 1, seen));\n if (keys.length > 50) parts.push('... ' + (keys.length - 50) + ' more');\n out = parts.length ? '{ ' + parts.join(', ') + ' }' : '{}';\n }\n seen.pop();\n return out;\n }\n function print(level) {\n return function () {\n var s = '', i;\n try {\n for (i = 0; i < arguments.length && s.length <= cfg.max; i++) s += (i ? ' ' : '') + inspect(arguments[i], 0, []);\n } catch (e) { s += '[unprintable]'; }\n hostLog(level, s.length > cfg.max ? s.slice(0, cfg.max + 1) : s);\n };\n }\n g.console = { log: print(''), info: print(''), debug: print(''), trace: print(''), warn: print('warn'), error: print('error') };\n function plain(v, depth, seen, budget) {\n var t = typeof v, out, i, keys;\n if ((budget.n -= 1) < 0) { budget.cut = true; return '[Truncated]'; }\n if (v === null || t === 'boolean' || t === 'undefined') return v;\n if (t === 'string') { if (v.length > cfg.max) { budget.cut = true; return v.slice(0, cfg.max); } return v; }\n if (t === 'number') return isFinite(v) ? v : S(v);\n if (t === 'bigint') return S(v) + 'n';\n if (t === 'symbol') return S(v);\n if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';\n if (v instanceof E) return { name: S(v.name), message: S(v.message) };\n if (seen.indexOf(v) >= 0) return '[Circular]';\n if (depth >= 8) return Array.isArray(v) ? '[Array]' : '[Object]';\n if (v instanceof Date) return isNaN(v) ? null : v.toISOString();\n seen.push(v);\n if (v instanceof M) { out = []; v.forEach(function (val, key) { out.push([plain(key, depth + 1, seen, budget), plain(val, depth + 1, seen, budget)]); }); }\n else if (v instanceof Set) { out = []; v.forEach(function (val) { out.push(plain(val, depth + 1, seen, budget)); }); }\n else if (Array.isArray(v)) { out = []; for (i = 0; i < v.length && budget.n >= 0; i++) out.push(plain(v[i], depth + 1, seen, budget)); }\n else { out = {}; keys = Object.keys(v); for (i = 0; i < keys.length && budget.n >= 0; i++) out[keys[i]] = plain(v[keys[i]], depth + 1, seen, budget); }\n seen.pop();\n return out;\n }\n function serialize(v, max) {\n if (v === undefined) return '';\n var budget = { n: 20000, cut: false }, text;\n try { text = J.stringify(plain(v, 0, [], budget)); } catch (e) { text = J.stringify('[unserializable]'); }\n if (text === undefined) return '';\n if (text.length > max) return 'T' + text.slice(0, max);\n return (budget.cut ? 'C' : 'J') + text;\n }\n function describe(e) {\n var name = 'Error', message = '', stack = '';\n try {\n if (e instanceof E || (e && typeof e === 'object' && typeof e.message === 'string')) {\n name = S(e.name || 'Error'); message = S(e.message); stack = typeof e.stack === 'string' ? e.stack : '';\n } else { message = 'thrown: ' + inspect(e, 1, []); }\n } catch (x) { message = '[unprintable error]'; }\n return J.stringify([name.slice(0, cfg.nameMax), message.slice(0, cfg.textMax), stack.slice(0, cfg.textMax)]);\n }\n var timers = new M(), nextTimer = 1;\n function timer(repeat) {\n return function (fn, ms) {\n if (typeof fn !== 'function') throw new TypeError('the first argument must be a function');\n if (timers.size >= cfg.maxTimers) throw new RangeError('too many timers');\n var id = nextTimer++;\n ms = +ms; if (!(ms >= 0)) ms = 0; if (ms > 2147483647) ms = 2147483647;\n if (repeat && ms < 1) ms = 1;\n timers.set(id, { fn: fn, args: Array.prototype.slice.call(arguments, 2), ms: ms, repeat: repeat });\n hostTimer(id, ms);\n return id;\n };\n }\n function clear(id) { if (timers.delete(id)) hostClear(id); }\n function fire(id) {\n var t = timers.get(id);\n if (!t) return;\n if (t.repeat) hostTimer(id, t.ms); else timers.delete(id);\n R.apply(t.fn, undefined, t.args);\n }\n g.setTimeout = timer(false); g.setInterval = timer(true);\n g.clearTimeout = clear; g.clearInterval = clear;\n g.queueMicrotask = function (fn) { P.resolve().then(fn); };\n if (cfg.ops.length) {\n var fs = {};\n cfg.ops.forEach(function (op) {\n fs[op] = function () {\n var text;\n try { text = J.stringify(Array.prototype.slice.call(arguments)); } catch (e) { return P.reject(new TypeError('fs.' + op + ': the arguments must be plain data')); }\n if (text.length > cfg.maxCall) return P.reject(new RangeError('fs.' + op + ': the arguments are too large'));\n return hostCall(op, text).then(function (r) { return r === '' ? undefined : J.parse(r); });\n };\n });\n g.fs = fs;\n }\n var loaded = new M();\n function requireFrom(base) {\n return function require(spec) {\n var path = hostResolve(base, S(spec)), mod = loaded.get(path), made;\n if (mod) return mod.exports;\n mod = { exports: {} };\n loaded.set(path, mod);\n made = hostCompile(path);\n if (typeof made === 'string') mod.exports = J.parse(made);\n else made.call(mod.exports, mod, mod.exports, requireFrom(path), path, path.slice(0, Math.max(1, path.lastIndexOf('/'))));\n return mod.exports;\n };\n }\n g.require = requireFrom(cfg.filename);\n return { fire: fire, serialize: serialize, describe: describe };\n})`\n\nconst BOOTSTRAP_FILE = '<sandbox>'\nconst REFUSED = '\\u0001refused:'\n\n// The slice of quickjs-emscripten this file uses. Typed loosely on purpose: the package is an\n// optional peer, so its types must not appear in what this package publishes.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Any = any\nexport interface ISandboxLib {\n RELEASE_SYNC: Any\n newVariant: (base: Any, options: { wasmMemory: Any }) => Any\n newQuickJSWASMModuleFromVariant: (variant: Any) => Promise<Any>\n}\n\nconst WASM_PAGE = 65536\n\n// The memory limit. QuickJS's own accounting (`setMemoryLimit`) cannot be relied on in this\n// build: without malloc_usable_size it counts 8 bytes per allocation, so a 2 MiB \"limit\" let a\n// guest take 490 MB (measured). The bound that holds is the WebAssembly memory itself: the\n// engine is instantiated on a Memory with a maximum, and the wasm runtime refuses to grow past\n// it - whatever the guest, or a bug in the engine, asks for.\nconst newBoundedModule = (lib: ISandboxLib, limitBytes: number): Promise<Any> => {\n const wasm = (globalThis as Any).WebAssembly\n const wasmMemory = new wasm.Memory({\n initial: SANDBOX_FLOORS.memoryLimitBytes / WASM_PAGE,\n maximum: Math.floor(limitBytes / WASM_PAGE),\n })\n return lib.newQuickJSWASMModuleFromVariant(lib.newVariant(lib.RELEASE_SYNC, { wasmMemory }))\n}\n\nexport interface IRunGuestOptions {\n hostCall?: SandboxHostCall\n // Called once the engine is loaded, right before the program is evaluated (the clock starts here).\n onStart?: () => void\n}\n\n/**\n * Run one program in a fresh QuickJS instance (its own WebAssembly module, so its own memory)\n * and resolve with what it printed and returned. Never rejects for anything the GUEST did - a\n * throw, a timeout, running out of memory are results. It rejects only when the engine itself\n * cannot be created.\n *\n * It runs on the calling thread: the interrupt handler stops JavaScript that loops, but not a\n * single long native call (a 16 MiB `indexOf`). The hard stop is the caller's - see `runInWorker`.\n */\nexport const runGuest = async (\n lib: ISandboxLib,\n request: ISandboxRequest,\n options: IRunGuestOptions = {},\n): Promise<ISandboxResult> => {\n const { limits } = request\n const filename = request.filename ?? '/main.js'\n const modules = request.modules\n const hostOps = options.hostCall ? (request.hostOps ?? []) : []\n const mod = await newBoundedModule(lib, limits.memoryLimitBytes)\n const rt = mod.newRuntime()\n // Makes one oversized allocation fail at once; the bound itself is the module's memory.\n rt.setMemoryLimit(limits.memoryLimitBytes)\n rt.setMaxStackSize(GUEST_STACK_BYTES)\n const ctx = rt.newContext()\n\n return new Promise<ISandboxResult>((resolve) => {\n const startedAt = Date.now()\n // The limit's clock starts with the program (`onStart`), not here: what runs before it is the\n // engine's own start (the host functions, the bootstrap) - our code, the same for every run,\n // and nothing of the guest's. On a busy machine that start alone can outlast a short limit;\n // a worker's start is bounded by `startupMs` instead.\n let programAt = 0\n let finished = false\n let interrupted = false\n // Time spent inside the guest, and time spent waiting for the host to serve a file call.\n let cpuMs = 0\n let entryAt = 0\n let waitMs = 0\n let waitingSince = 0\n let pendingCalls = 0\n let hostCalls = 0\n let watchdog: ReturnType<typeof setTimeout> | undefined\n const hostTimers = new Map<number, ReturnType<typeof setTimeout>>()\n const out: string[] = []\n let outChars = 0\n let truncated = false\n let internals: Any\n let main: Any\n // 'script' = the async-script wrapper ({ value }), 'module' = a namespace, 'value' = the result itself.\n let mainKind: 'script' | 'module' | 'value' = 'value'\n\n const cpuUsed = (): number => cpuMs + (entryAt ? Date.now() - entryAt : 0)\n const wallUsed = (): number =>\n programAt === 0\n ? 0\n : Date.now() - programAt - waitMs - (waitingSince ? Date.now() - waitingSince : 0)\n const overTime = (): boolean =>\n cpuUsed() > limits.timeoutMs || (pendingCalls === 0 && wallUsed() > limits.timeoutMs)\n\n rt.setInterruptHandler(() => {\n if (finished || overTime()) {\n interrupted = true\n return true\n }\n return false\n })\n\n const finish = (error?: ISandboxError, result?: { value: unknown }): void => {\n if (finished) {\n return\n }\n finished = true\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n }\n for (const t of hostTimers.values()) {\n clearTimeout(t)\n }\n hostTimers.clear()\n // The instance is not disposed handle by handle: nothing of it is reused, and dropping the\n // module frees its memory with it.\n resolve({\n ok: !error,\n stdout: out.join(''),\n ...(result ? { result: result.value } : {}),\n ...(error ? { error } : {}),\n truncated,\n durationMs: Date.now() - startedAt,\n })\n }\n\n const timedOut = (): ISandboxError => ({\n name: 'TimeoutError',\n message: `the run was stopped after ${limits.timeoutMs} ms (timeoutMs)`,\n })\n\n // Read a guest error. Runs guest code (getters), so it is skipped after an interrupt.\n const describe = (handle: Any): ISandboxError => {\n if (interrupted) {\n return timedOut()\n }\n try {\n let raw: unknown\n if (internals) {\n const r = ctx.callFunction(internals.describe, ctx.undefined, handle)\n raw = r.error ? undefined : JSON.parse(ctx.getString(r.value))\n }\n if (!Array.isArray(raw)) {\n const d = ctx.dump(handle) as { name?: unknown; message?: unknown; stack?: unknown }\n raw = [d?.name ?? 'Error', d?.message ?? String(d), d?.stack ?? '']\n }\n const [name, message, stack] = raw as unknown[]\n const frames = String(stack ?? '')\n .split('\\n')\n .filter((line) => line.trim() && !line.includes(BOOTSTRAP_FILE))\n .join('\\n')\n return {\n name: clip(String(name || 'Error'), ERROR_NAME_CHARS),\n message: clip(String(message ?? ''), ERROR_TEXT_CHARS),\n ...(frames ? { stack: clip(frames, ERROR_TEXT_CHARS) } : {}),\n }\n } catch {\n return interrupted\n ? timedOut()\n : { name: 'Error', message: 'the program threw an error that could not be read' }\n }\n }\n\n // Something escaped the engine as a HOST exception (the native stack ran out under a deep\n // guest recursion, or the engine trapped). The instance is not trusted after that.\n const engineFailure = (err: unknown): void => {\n if (interrupted) {\n finish(timedOut())\n } else if (err instanceof RangeError) {\n finish({ name: 'RangeError', message: 'Maximum call stack size exceeded' })\n } else {\n finish({ name: 'SandboxError', message: clip(errorText(err), ERROR_TEXT_CHARS) })\n }\n }\n\n const armWatchdog = (): void => {\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n watchdog = undefined\n }\n if (finished || pendingCalls > 0) {\n return\n }\n watchdog = setTimeout(\n () => {\n watchdog = undefined\n if (overTime()) {\n interrupted = true\n finish(timedOut())\n } else {\n armWatchdog()\n }\n },\n Math.max(1, limits.timeoutMs - wallUsed() + 1),\n )\n }\n\n // Look at the program's promise: done, failed, or still waiting on a timer / a file call.\n const settle = (): void => {\n while (!finished) {\n if (interrupted) {\n finish(timedOut())\n return\n }\n const state = ctx.getPromiseState(main)\n if (state.type === 'rejected') {\n finish(describe(state.error))\n return\n }\n if (state.type === 'pending') {\n if (hostTimers.size === 0 && pendingCalls === 0) {\n finish({\n name: 'Error',\n message:\n 'the program awaits a promise that can never settle (nothing is left to run)',\n })\n }\n return\n }\n if (mainKind !== 'value') {\n main = ctx.getProp(state.value, mainKind === 'script' ? 'value' : 'default')\n mainKind = 'value'\n continue\n }\n if (!state.notAPromise) {\n main = state.value\n continue\n }\n // Like Node, the run ends when nothing is left to run - not when the last line is reached.\n if (hostTimers.size > 0 || pendingCalls > 0) {\n return\n }\n const max = Math.max(200, limits.maxOutputChars - outChars)\n const r = ctx.callFunction(\n internals.serialize,\n ctx.undefined,\n state.value,\n ctx.newNumber(max),\n )\n if (r.error) {\n finish(describe(r.error))\n return\n }\n const text = ctx.getString(r.value) as string\n if (text === '') {\n finish()\n } else if (text[0] === 'T') {\n truncated = true\n finish(undefined, { value: clip(text.slice(1), max) })\n } else {\n truncated ||= text[0] === 'C'\n finish(undefined, { value: JSON.parse(text.slice(1)) })\n }\n return\n }\n }\n\n // Every entry into the guest goes through here: timed, drained, then judged.\n const enter = (fn: () => void): void => {\n if (finished) {\n return\n }\n entryAt = Date.now()\n try {\n fn()\n while (!finished && !interrupted) {\n const jobs = rt.executePendingJobs()\n if (jobs.error) {\n const error = describe(jobs.error)\n cpuMs += Date.now() - entryAt\n entryAt = 0\n finish(error)\n return\n }\n if (!rt.hasPendingJob()) {\n break\n }\n }\n cpuMs += Date.now() - entryAt\n entryAt = 0\n settle()\n } catch (err) {\n cpuMs += Date.now() - entryAt\n entryAt = 0\n engineFailure(err)\n }\n }\n\n const guestError = (name: string, message: string): Error =>\n Object.assign(new Error(message), { name })\n\n const host = ctx.newObject()\n const expose = (name: string, fn: (...args: Any[]) => Any): void => {\n ctx.setProp(host, name, ctx.newFunction(name, fn))\n }\n expose('log', (levelHandle, textHandle) => {\n if (outChars >= limits.maxOutputChars) {\n truncated = true\n return\n }\n const level = ctx.getString(levelHandle) as string\n let line = `${level ? `[${level}] ` : ''}${ctx.getString(textHandle) as string}\\n`\n if (outChars + line.length > limits.maxOutputChars) {\n line = line.slice(0, limits.maxOutputChars - outChars)\n truncated = true\n }\n out.push(line)\n outChars += line.length\n })\n expose('timer', (idHandle, msHandle) => {\n const id = ctx.getNumber(idHandle) as number\n const ms = ctx.getNumber(msHandle) as number\n const previous = hostTimers.get(id)\n if (previous !== undefined) {\n clearTimeout(previous)\n } else if (hostTimers.size >= MAX_TIMERS) {\n throw guestError('RangeError', 'too many timers')\n }\n hostTimers.set(\n id,\n setTimeout(\n () => {\n hostTimers.delete(id)\n enter(() => {\n const r = ctx.callFunction(internals.fire, ctx.undefined, ctx.newNumber(id))\n if (r.error) {\n // An exception nobody caught in a timer callback ends the run, as it would a process.\n finish(describe(r.error))\n }\n })\n },\n // A timer past the deadline never fires: the watchdog ends the run first.\n Math.min(Math.max(0, ms), limits.timeoutMs + 1),\n ),\n )\n })\n expose('clear', (idHandle) => {\n const id = ctx.getNumber(idHandle) as number\n const t = hostTimers.get(id)\n if (t !== undefined) {\n clearTimeout(t)\n hostTimers.delete(id)\n }\n })\n expose('call', (opHandle, argsHandle) => {\n const op = ctx.getString(opHandle) as string\n if (!hostOps.includes(op as SandboxHostOp) || !options.hostCall) {\n throw guestError('Error', `fs.${clip(op, 40)} is not available in this sandbox`)\n }\n if ((hostCalls += 1) > SANDBOX_MAX_HOST_CALLS) {\n throw guestError(\n 'RangeError',\n `too many file operations in one run (limit ${SANDBOX_MAX_HOST_CALLS})`,\n )\n }\n const args = JSON.parse(ctx.getString(argsHandle) as string) as unknown[]\n const deferred = ctx.newPromise()\n if (pendingCalls === 0) {\n waitingSince = Date.now()\n if (watchdog !== undefined) {\n clearTimeout(watchdog)\n watchdog = undefined\n }\n }\n pendingCalls += 1\n const done = (settleGuest: () => void): void => {\n pendingCalls -= 1\n if (pendingCalls === 0) {\n waitMs += Date.now() - waitingSince\n waitingSince = 0\n }\n if (finished) {\n return\n }\n armWatchdog()\n enter(settleGuest)\n }\n options.hostCall(op, args).then(\n (value) =>\n done(() => {\n const text = value === undefined ? '' : JSON.stringify(value)\n deferred.resolve(ctx.newString(text ?? ''))\n }),\n (err: unknown) =>\n done(() => {\n deferred.reject(\n ctx.newError({\n name: 'Error',\n message: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS),\n }),\n )\n }),\n )\n return deferred.handle\n })\n const load = (path: string): string => {\n if (!modules) {\n throw guestError('Error', `Cannot load \"${clip(path, 200)}\": this sandbox has no files`)\n }\n if (!Object.hasOwn(modules, path)) {\n throw guestError(\n 'Error',\n `Cannot load \"${clip(path, 200)}\": no such file in the workspace (a module must exist before the run and be named by a literal path)`,\n )\n }\n return modules[path]\n }\n const resolvePath = (base: string, spec: string): string => {\n try {\n return resolveModulePath(base, spec)\n } catch (err) {\n throw guestError('Error', err instanceof Error ? err.message : String(err))\n }\n }\n expose('resolve', (baseHandle, specHandle) =>\n ctx.newString(\n resolvePath(ctx.getString(baseHandle) as string, ctx.getString(specHandle) as string),\n ),\n )\n expose('compile', (pathHandle) => {\n const path = ctx.getString(pathHandle) as string\n const source = load(path)\n if (path.toLowerCase().endsWith('.json')) {\n return ctx.newString(source)\n }\n const r = ctx.evalCode(\n `(function (module, exports, require, __filename, __dirname) {${source}\\n})`,\n path,\n )\n if (r.error) {\n return { error: r.error }\n }\n return r.value\n })\n // `import` (static and dynamic). Always installed, so that `import('node:fs')` fails with a\n // sentence the model can act on instead of an engine default.\n rt.setModuleLoader(\n (path: string) => {\n try {\n if (path.startsWith(REFUSED)) {\n throw new Error(path.slice(REFUSED.length))\n }\n const source = load(path)\n return path.toLowerCase().endsWith('.json')\n ? `export default JSON.parse(${JSON.stringify(source)})`\n : source\n } catch (err) {\n return { error: err as Error }\n }\n },\n (base: string, spec: string) => {\n // A refusal travels as a name the loader then refuses with the same sentence (the\n // engine drops an error returned from here).\n try {\n return resolveModulePath(base, spec)\n } catch (err) {\n return `${REFUSED}${err instanceof Error ? err.message : String(err)}`\n }\n },\n )\n\n try {\n const boot = ctx.evalCode(BOOTSTRAP, BOOTSTRAP_FILE)\n if (boot.error) {\n finish({ name: 'SandboxError', message: 'the sandbox runtime failed to start' })\n return\n }\n const made = ctx.callFunction(\n boot.value,\n ctx.undefined,\n host,\n ctx\n .evalCode(\n `(${JSON.stringify({\n max: limits.maxOutputChars,\n nameMax: ERROR_NAME_CHARS,\n textMax: ERROR_TEXT_CHARS,\n maxTimers: MAX_TIMERS,\n maxCall: SANDBOX_MAX_FILE_CHARS + 2000,\n ops: hostOps,\n filename,\n })})`,\n BOOTSTRAP_FILE,\n )\n .unwrap(),\n )\n if (made.error) {\n finish({ name: 'SandboxError', message: 'the sandbox runtime failed to start' })\n return\n }\n internals = {\n fire: ctx.getProp(made.value, 'fire'),\n serialize: ctx.getProp(made.value, 'serialize'),\n describe: ctx.getProp(made.value, 'describe'),\n }\n } catch (err) {\n engineFailure(err)\n return\n }\n\n programAt = Date.now()\n options.onStart?.()\n armWatchdog()\n enter(() => {\n let evaluated = ctx.evalCode(request.code, filename, EVAL_SCRIPT_ASYNC)\n mainKind = 'script'\n // A script that does not compile has run nothing: when it is written as a module, run it as one.\n if (evaluated.error && !interrupted && looksLikeModule(request.code)) {\n evaluated = ctx.evalCode(request.code, filename, { type: 'module' })\n mainKind = 'module'\n }\n if (evaluated.error) {\n finish(describe(evaluated.error))\n return\n }\n main = evaluated.value\n })\n })\n}\n\n// ── What comes back ──────────────────────────────────────────────────────\n\nconst jsonSafe = (value: unknown, max: number): { value: unknown; cut: boolean } => {\n let text: string | undefined\n try {\n text = JSON.stringify(value)\n } catch {\n return { value: '[unserializable]', cut: true }\n }\n if (text === undefined) {\n return { value: undefined, cut: false }\n }\n if (text.length > max) {\n return { value: text.slice(0, max), cut: true }\n }\n // Re-parsed: what leaves is plain data, whatever was handed in.\n return { value: JSON.parse(text) as unknown, cut: false }\n}\n\n/**\n * The authoritative shape and size of a run's result. The engine already bounds what it\n * produces; this runs on the agent's side of the boundary and trusts none of it (a worker is\n * the guest's side).\n */\nexport const sanitizeSandboxResult = (raw: unknown, limits: ISandboxLimits): ISandboxResult => {\n const r = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n let truncated = r.truncated === true\n let stdout = typeof r.stdout === 'string' ? r.stdout : ''\n if (stdout.length > limits.maxOutputChars) {\n stdout = stdout.slice(0, limits.maxOutputChars)\n truncated = true\n }\n const result: ISandboxResult = { ok: r.ok === true, stdout, truncated, durationMs: 0 }\n if (Object.hasOwn(r, 'result') && r.result !== undefined) {\n const safe = jsonSafe(r.result, Math.max(200, limits.maxOutputChars - stdout.length))\n if (safe.value !== undefined) {\n result.result = safe.value\n }\n truncated ||= safe.cut\n }\n if (r.error && typeof r.error === 'object') {\n const e = r.error as Record<string, unknown>\n result.error = {\n name: clip(typeof e.name === 'string' ? e.name : 'Error', ERROR_NAME_CHARS),\n message: clip(typeof e.message === 'string' ? e.message : '', ERROR_TEXT_CHARS),\n ...(typeof e.stack === 'string' && e.stack ? { stack: clip(e.stack, ERROR_TEXT_CHARS) } : {}),\n }\n result.ok = false\n } else if (!result.ok) {\n result.error = { name: 'Error', message: 'the run failed' }\n }\n result.truncated = truncated\n result.durationMs =\n typeof r.durationMs === 'number' && Number.isFinite(r.durationMs) && r.durationMs >= 0\n ? Math.round(r.durationMs)\n : 0\n return result\n}\n\n// ── The worker protocol ──────────────────────────────────────────────────\n// The guest does not run on the agent's thread. One worker serves one run and is thrown away.\n\nexport type SandboxToWorker =\n | { type: 'run'; request: ISandboxRequest }\n | { type: 'host-result'; id: number; ok: boolean; value?: unknown; error?: string }\n\nexport type SandboxFromWorker =\n | { type: 'started' }\n | { type: 'host-call'; id: number; op: string; args: unknown[] }\n | { type: 'done'; result: unknown }\n | { type: 'failed'; code: 'peer-missing' | 'engine'; message: string }\n\n// A message channel as this file needs it; each package adapts its own worker type to it.\nexport interface ISandboxPort {\n post: (message: unknown) => void\n // `onClose` fires when the other side is gone (a worker that exited or crashed).\n listen: (onMessage: (message: unknown) => void, onClose?: (reason: string) => void) => void\n // The parent's side only: kill the worker.\n terminate?: () => void\n}\n\n/** The worker's side: load the engine, run what is posted, answer. */\nexport const serveSandbox = (port: ISandboxPort, loadLib: () => Promise<ISandboxLib>): void => {\n const waiting = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>()\n let seq = 0\n let busy = false\n const run = async (request: ISandboxRequest): Promise<void> => {\n let lib: ISandboxLib\n try {\n lib = await loadLib()\n } catch (err) {\n port.post({ type: 'failed', code: 'peer-missing', message: errorText(err) })\n return\n }\n try {\n const result = await runGuest(lib, request, {\n onStart: () => port.post({ type: 'started' }),\n hostCall: (op, args) =>\n new Promise((resolve, reject) => {\n const id = (seq += 1)\n waiting.set(id, { resolve, reject })\n port.post({ type: 'host-call', id, op, args })\n }),\n })\n port.post({ type: 'done', result })\n } catch (err) {\n port.post({ type: 'failed', code: 'engine', message: errorText(err) })\n }\n }\n port.listen((message) => {\n const m = message as SandboxToWorker\n if (m?.type === 'run' && !busy) {\n busy = true\n void run(m.request)\n } else if (m?.type === 'host-result') {\n const w = waiting.get(m.id)\n if (w) {\n waiting.delete(m.id)\n if (m.ok) {\n w.resolve(m.value)\n } else {\n w.reject(new Error(typeof m.error === 'string' ? m.error : 'the file operation failed'))\n }\n }\n }\n })\n}\n\nexport interface IRunInWorkerOptions {\n hostCall?: SandboxHostCall\n signal?: AbortSignal\n // How long the worker may take to load the engine before the run is given up (default 20 s).\n startupMs?: number\n // How far past `timeoutMs` the worker lives before it is terminated (default 1000 ms).\n graceMs?: number\n}\n\n/**\n * The agent's side: post one run to a fresh worker and wait for it - or kill it. The engine's\n * own interrupt handler is the soft stop; `terminate()` here is the hard one, and it does not\n * depend on anything the guest does. Rejects only when the sandbox itself is unavailable (the\n * optional peer is missing, the worker never started) or the run was aborted.\n */\nexport const runInWorker = (\n port: ISandboxPort,\n request: ISandboxRequest,\n options: IRunInWorkerOptions = {},\n): Promise<ISandboxResult> =>\n new Promise<ISandboxResult>((resolve, reject) => {\n const { limits } = request\n const startedAt = Date.now()\n const graceMs = options.graceMs ?? 1000\n let over = false\n let serving = 0\n let timer: ReturnType<typeof setTimeout> | undefined\n const stop = (): void => {\n over = true\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n options.signal?.removeEventListener('abort', onAbort)\n try {\n port.terminate?.()\n } catch {\n /* already gone */\n }\n }\n const end = (result: ISandboxResult): void => {\n if (over) {\n return\n }\n stop()\n resolve({ ...result, durationMs: Date.now() - startedAt })\n }\n const fail = (err: Error): void => {\n if (over) {\n return\n }\n stop()\n reject(err)\n }\n const failed = (name: string, message: string): ISandboxResult => ({\n ok: false,\n stdout: '',\n error: { name, message },\n truncated: false,\n durationMs: 0,\n })\n function onAbort(): void {\n fail(Object.assign(new Error('The run was aborted'), { name: 'AbortError' }))\n }\n const arm = (ms: number, onFire: () => void): void => {\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n timer = setTimeout(onFire, ms)\n }\n const armKill = (): void =>\n arm(limits.timeoutMs + graceMs, () =>\n end(\n failed(\n 'TimeoutError',\n `the run was killed after ${limits.timeoutMs} ms (timeoutMs): it did not stop by itself`,\n ),\n ),\n )\n if (options.signal?.aborted) {\n onAbort()\n return\n }\n options.signal?.addEventListener('abort', onAbort, { once: true })\n arm(options.startupMs ?? 20_000, () =>\n fail(new SandboxUnavailableError('the sandbox worker did not start in time')),\n )\n port.listen(\n (message) => {\n if (over) {\n return\n }\n const m = message as SandboxFromWorker\n switch (m?.type) {\n case 'started':\n armKill()\n break\n case 'host-call': {\n const id = m.id\n serving += 1\n // The clock does not run while the agent's side serves a call (it may be asking the user).\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n const answer = (reply: SandboxToWorker): void => {\n serving -= 1\n if (over) {\n return\n }\n if (serving === 0) {\n armKill()\n }\n port.post(reply)\n }\n const call = options.hostCall\n ? options.hostCall(String(m.op), Array.isArray(m.args) ? m.args : [])\n : Promise.reject(new Error('this sandbox has no files'))\n call.then(\n (value) => answer({ type: 'host-result', id, ok: true, value }),\n (err: unknown) =>\n answer({\n type: 'host-result',\n id,\n ok: false,\n error: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS),\n }),\n )\n break\n }\n case 'done':\n end(sanitizeSandboxResult(m.result, limits))\n break\n case 'failed':\n fail(\n m.code === 'peer-missing'\n ? sandboxPeerMissing(clip(String(m.message), 300))\n : new SandboxUnavailableError(\n `the sandbox engine failed: ${clip(String(m.message), 300)}`,\n ),\n )\n break\n }\n },\n (reason) =>\n end(failed('SandboxError', `the sandbox stopped unexpectedly: ${clip(reason, 300)}`)),\n )\n port.post({ type: 'run', request } satisfies SandboxToWorker)\n })\n\n// At most `size` runs at once; the rest wait their turn (each run is a worker and a heap).\nexport const createSandboxQueue = (size: number): (<T>(task: () => Promise<T>) => Promise<T>) => {\n let active = 0\n const waiting: (() => void)[] = []\n return async <T>(task: () => Promise<T>): Promise<T> => {\n if (active >= size) {\n await new Promise<void>((go) => waiting.push(go))\n }\n active += 1\n try {\n return await task()\n } finally {\n active -= 1\n waiting.shift()?.()\n }\n }\n}\n"],"mappings":";AAcO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AA0B/B,IAAM,MAAM,OAAO;AAEZ,IAAM,mBAAmC;AAAA,EA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