@dudko.dev/agent-web 0.0.45 → 0.0.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/agent-web.js +153 -149
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-236RCVAZ.js → chunk-PTJA7V23.js} +3 -2
- package/dist/chunk-PTJA7V23.js.map +1 -0
- package/dist/index.cjs +563 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +228 -2
- package/dist/index.d.ts +228 -2
- package/dist/index.js +516 -32
- package/dist/index.js.map +1 -1
- package/dist/{sandbox-7CGSIIIZ.js → sandbox-ZXWD5IWZ.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-236RCVAZ.js.map +0 -1
- /package/dist/{sandbox-7CGSIIIZ.js.map → sandbox-ZXWD5IWZ.js.map} +0 -0
|
@@ -567,7 +567,8 @@ var wrapToolsForRun = (tools, o) => {
|
|
|
567
567
|
...o.elicitations ? { elicitations: o.elicitations } : {},
|
|
568
568
|
...o.clock ? { clock: o.clock } : {},
|
|
569
569
|
...o.mcpSkills ? { mcpSkills: o.mcpSkills } : {},
|
|
570
|
-
...o.sessionLocks ? { sessionLocks: o.sessionLocks } : {}
|
|
570
|
+
...o.sessionLocks ? { sessionLocks: o.sessionLocks } : {},
|
|
571
|
+
...o.askUser ? { askUser: o.askUser } : {}
|
|
571
572
|
};
|
|
572
573
|
return execute.call(t, input, { ...options, agentRun });
|
|
573
574
|
};
|
|
@@ -961,4 +962,4 @@ export {
|
|
|
961
962
|
fileToolBindingOf,
|
|
962
963
|
createFileTools
|
|
963
964
|
};
|
|
964
|
-
//# sourceMappingURL=chunk-
|
|
965
|
+
//# sourceMappingURL=chunk-PTJA7V23.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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\n/** Why `{ park: true }` is a denial here: parking is the server package's (docs/design.md). */\nexport const PARK_REFUSED_REASON =\n \"parking ({ park: true }) is the server package's (@dudko.dev/agent): a run in a page cannot wait for an answer outside it, so the call is denied\"\n\nconst normalizeDecision = (\n d: ToolApprovalDecision,\n): { approved: boolean; reason?: string; remember?: boolean } =>\n typeof d === 'boolean'\n ? { approved: d }\n : // A host ported from the server agent: the call is denied as before, and now says why.\n (d as { park?: unknown } | null)?.park === true\n ? { approved: false, reason: PARK_REFUSED_REASON }\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'\nimport type { AskUserChannel } from './ask-user.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 * Internal - the session locks the run holds (its own and its callers', `sessionLock`): an\n * in-process subagent runs under them rather than wait for its own parent.\n */\n sessionLocks?: () => readonly string[]\n /**\n * Internal - the run's way to the person (`config.askUser`): `ask_user` asks through it, a\n * helper the run starts shares it, and a subagent the host defined asks through it too.\n */\n askUser?: AskUserChannel\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 /** The session locks the run holds, handed to tools through their run context. */\n sessionLocks?: () => readonly string[]\n /** The run's way to the person (`config.askUser`), handed to tools through their run context. */\n askUser?: AskUserChannel\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 ...(o.sessionLocks ? { sessionLocks: o.sessionLocks } : {}),\n ...(o.askUser ? { askUser: o.askUser } : {}),\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'\nimport { postStorageChangeFrom } from '../sync/notices.js'\nimport { currentTab, type Tab } from '../sync/tab.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 /**\n * The IndexedDB database the files live in - and the name the other tabs hear of a change\n * under (`files` notices, see `onStorageChange`). Undefined for an in-memory file system:\n * nothing of it is shared.\n */\n readonly dbName: string | undefined\n /** Isolates several file systems in one database: a `files` notice carries it. */\n readonly namespace: string\n private readonly memory?: Map<string, VirtualFile>\n private readonly ns: string\n private readonly maxFileBytes: number\n private readonly listeners = new Set<VfsListener>()\n private readonly tab: Tab\n\n constructor(opts: VirtualFileSystemOptions = {}) {\n if (opts.memory) this.memory = new Map()\n this.dbName = opts.memory ? undefined : (opts.dbName ?? 'agent-web')\n this.ns = opts.namespace ?? 'default'\n this.namespace = this.ns\n this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024\n this.tab = currentTab()\n }\n\n private key(path: string): string {\n return `${this.ns}:${path}`\n }\n\n /** After a write committed: the other tabs hear which file (never its content). */\n private announce(op: 'put' | 'delete', path: string): void {\n postStorageChangeFrom(this.tab, this.dbName, {\n kind: 'files',\n op,\n key: path,\n namespace: this.ns,\n })\n }\n\n /**\n * Subscribe to writes and deletes made through THIS file system (e.g. to refresh a file list).\n * Another tab's changes come as `files` notices (`onStorageChange(vfs.dbName, ...)`). Returns\n * an unsubscribe.\n */\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 this.announce('put', 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 if (existed) this.announce('delete', 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,OAAQ,QAAO;AACpB,MAAI,KAAK,MAAM,aAAa,OAAO,cAAc,GAAG;AAClD,WAAO,EAAE,MAAM,SAAS,QAAQ,MAAM,aAAa,KAAK,OAAO,eAAyB;AAAA,EAC1F;AACA,MAAI,KAAK,MAAM,aAAa,OAAO,cAAc,GAAG;AAClD,WAAO,EAAE,MAAM,SAAS,QAAQ,MAAM,aAAa,KAAK,OAAO,eAAyB;AAAA,EAC1F;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