@dudko.dev/agent-web 0.0.38 → 0.0.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import {
3
3
  isTextMime,
4
4
  normalizePath,
5
5
  toolRunContextOf
6
- } from "./chunk-AY2BZYZY.js";
6
+ } from "./chunk-TZITKUFW.js";
7
7
  import "./chunk-CTXDKSDD.js";
8
8
  import {
9
9
  RUN_JS_TOOL,
@@ -266,4 +266,4 @@ var createSandbox = (config, mounted = {}, warn = () => {
266
266
  export {
267
267
  createSandbox
268
268
  };
269
- //# sourceMappingURL=sandbox-AMO2SA4X.js.map
269
+ //# sourceMappingURL=sandbox-KG6OUG24.js.map
@@ -3,11 +3,11 @@ import {
3
3
  isWebGPUAvailable,
4
4
  preloadWebLLMModel,
5
5
  unloadWebLLMModel
6
- } from "./chunk-Y7OGKYE5.js";
6
+ } from "./chunk-3V27UZT6.js";
7
7
  export {
8
8
  createWebLLMModel,
9
9
  isWebGPUAvailable,
10
10
  preloadWebLLMModel,
11
11
  unloadWebLLMModel
12
12
  };
13
- //# sourceMappingURL=webllm-PCPDLDQA.js.map
13
+ //# sourceMappingURL=webllm-BEL5A4OF.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent-web",
3
- "version": "0.0.38",
3
+ "version": "0.0.39",
4
4
  "description": "Headless, configurable in-browser LLM agent on the Vercel AI SDK: multi-provider bring-your-own-key (OpenAI, Anthropic, Google, xAI, DeepSeek, gateway, openai-compatible) AND local WebGPU/WebLLM, native + prompted tool-calling, structured output, an encrypted IndexedDB token vault, and a plan → execute → replan → synthesize loop. UI-agnostic.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/limits.ts","../src/tools/approval.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'\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\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?: (req: ToolApprovalRequest) => ToolApprovalDecision | Promise<ToolApprovalDecision>\n /** No decision within this many ms → deny. Default: wait indefinitely. */\n timeoutMs?: number\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\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 */\nexport const decideToolPermission = (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 /** Tools the user chose to \"always allow\". */\n readonly remembered: Set<string>\n}\n\nexport const createApprovalState = (config: ToolApprovalConfig | undefined): ApprovalState => ({\n mode: config?.mode ?? 'autopilot',\n config: config ?? {},\n remembered: new Set<string>(),\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\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: { toolName: string; input: unknown; readOnly: boolean; step?: IPlanStep },\n events: ApprovalEvents,\n signal?: AbortSignal,\n): Promise<void> => {\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 })\n if (permission === 'allow') return\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 = '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, ...call }\n events.requested(req)\n let decision: { approved: boolean; reason?: string; remember?: boolean }\n try {\n decision = normalizeDecision(\n await withDeadline(Promise.resolve(onRequest(req)), state.config.timeoutMs, signal),\n )\n } catch (err) {\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 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\nconst withDeadline = <T>(\n p: Promise<T>,\n timeoutMs: number | undefined,\n signal?: AbortSignal,\n): Promise<T> => {\n if ((!timeoutMs || 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(new Error('the run was stopped while waiting for approval'))\n }\n if (signal?.aborted) return onAbort()\n signal?.addEventListener('abort', onAbort, { once: true })\n if (timeoutMs && timeoutMs > 0) {\n timer = setTimeout(() => {\n done()\n reject(new Error(`no approval decision within ${timeoutMs} ms`))\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 { 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 } from '../events.js'\nimport { ToolBudgetError } from '../limits.js'\nimport {\n decideToolPermission,\n gateToolCall,\n isReadOnlyTool,\n type ApprovalState,\n} from './approval.js'\nimport { promptHintOf } from './types.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 /** Add tokens spent on the parent's behalf (e.g. by a subagent) to the run. */\n addUsage: (usage: IUsage) => void\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}\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) => void\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\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 = (toolName: string, input: unknown, readOnly: boolean, signal?: AbortSignal) =>\n gateToolCall(\n o.approval,\n { toolName, input, readOnly, step: o.step() },\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 }),\n resolved: (r) => o.emit({ type: 'tool.approval-resolved', ...r }),\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 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 const run = (): 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 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 }\n return execute.call(t, input, { ...(options as object), agentRun })\n }\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 })\n if (permission === 'allow') return run()\n return gate(\n name,\n input,\n readOnly,\n (options as { abortSignal?: AbortSignal } | undefined)?.abortSignal,\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 { isTextMime, 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 }) => {\n const info = await vfs.write(path, content, mimeType ? { mimeType } : {})\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 }) => ({ deleted: await vfs.delete(path) }),\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,OAA2B,QACvC,OAAO,QAAQ,YAAY,MAAM,MAAM,SAAS,MAAM;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,e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,wBAAwB;AAAA,QAChE,UAAU,EAAE,MAAM,UAAU,aAAa,6CAA6C;AAAA,MACxF;AAAA,MACA,UAAU,CAAC,QAAQ,SAAS;AAAA,MAC5B,sBAAsB;AAAA,IACxB,CAAC;AAAA,IACD,SAAS,OAAO,EAAE,MAAM,SAAS,SAAS,MAAM;AAC9C,YAAM,OAAO,MAAM,IAAI,MAAM,MAAM,SAAS,WAAW,EAAE,SAAS,IAAI,CAAC,CAAC;AACxE,aAAO,EAAE,SAAS,KAAK,MAAM,MAAM,KAAK,KAAK;AAAA,IAC/C;AAAA,EACF,CAAC;AACD,QAAM,GAAG,CAAC,QAAQ,IAAI,KAAK;AAAA,IACzB,aAAa;AAAA,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,OAAO,EAAE,SAAS,MAAM,IAAI,OAAO,IAAI,EAAE;AAAA,EAClE,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":["tool","tool"]}
@@ -1,124 +0,0 @@
1
- import {
2
- KEYS_STORE,
3
- SECRETS_STORE,
4
- openAgentWebDB
5
- } from "./chunk-CTXDKSDD.js";
6
-
7
- // src/logger.ts
8
- var WEIGHT = {
9
- silent: 0,
10
- error: 1,
11
- warn: 2,
12
- info: 3,
13
- debug: 4
14
- };
15
- var PREFIX = "[agent-web]";
16
- var noop = () => void 0;
17
- var createLogger = (level = "warn", sink = console) => {
18
- const at = (min, fn) => WEIGHT[level] >= WEIGHT[min] ? (...args) => fn.call(sink, PREFIX, ...args) : noop;
19
- return {
20
- level,
21
- error: at("error", sink.error),
22
- warn: at("warn", sink.warn),
23
- info: at("info", sink.info),
24
- debug: at("debug", sink.debug)
25
- };
26
- };
27
-
28
- // src/secrets/crypto.ts
29
- var KEY_ID = "vault-key-v1";
30
- var webcrypto = () => {
31
- const c = globalThis.crypto;
32
- if (!c?.subtle || !c.getRandomValues) {
33
- throw new Error("WebCrypto (crypto.subtle) is unavailable in this environment");
34
- }
35
- return c;
36
- };
37
- var loadOrCreateKey = async (dbName) => {
38
- const db = await openAgentWebDB({ dbName });
39
- const existing = await db.get(KEYS_STORE, KEY_ID);
40
- if (existing) return existing;
41
- const key = await webcrypto().subtle.generateKey(
42
- { name: "AES-GCM", length: 256 },
43
- /* extractable */
44
- false,
45
- ["encrypt", "decrypt"]
46
- );
47
- const tx = db.transaction(KEYS_STORE, "readwrite");
48
- const winner = await tx.store.get(KEY_ID);
49
- if (winner) {
50
- await tx.done;
51
- return winner;
52
- }
53
- await tx.store.put(key, KEY_ID);
54
- await tx.done;
55
- return key;
56
- };
57
- var keyCache = /* @__PURE__ */ new Map();
58
- var getOrCreateVaultKey = (dbName) => {
59
- const cacheKey = dbName ?? "agent-web";
60
- let p = keyCache.get(cacheKey);
61
- if (!p) {
62
- p = loadOrCreateKey(dbName);
63
- keyCache.set(cacheKey, p);
64
- p.catch(() => {
65
- if (keyCache.get(cacheKey) === p) keyCache.delete(cacheKey);
66
- });
67
- }
68
- return p;
69
- };
70
- var textEncoder = new TextEncoder();
71
- var textDecoder = new TextDecoder();
72
- var encryptJSON = async (key, value) => {
73
- const c = webcrypto();
74
- const iv = c.getRandomValues(new Uint8Array(12));
75
- const data = textEncoder.encode(JSON.stringify(value));
76
- const ciphertext = await c.subtle.encrypt({ name: "AES-GCM", iv }, key, data);
77
- return { iv, ciphertext };
78
- };
79
- var decryptJSON = async (key, blob) => {
80
- const iv = new Uint8Array(blob.iv);
81
- const plain = await webcrypto().subtle.decrypt({ name: "AES-GCM", iv }, key, blob.ciphertext);
82
- return JSON.parse(textDecoder.decode(plain));
83
- };
84
-
85
- // src/secrets/vault.ts
86
- var IndexedDBVault = class {
87
- dbName;
88
- constructor(opts = {}) {
89
- this.dbName = opts.dbName;
90
- }
91
- key() {
92
- return getOrCreateVaultKey(this.dbName);
93
- }
94
- /** Encrypt and store a secret string under `id`. */
95
- async setSecret(id, value) {
96
- const blob = await encryptJSON(await this.key(), value);
97
- const db = await openAgentWebDB({ dbName: this.dbName });
98
- await db.put(SECRETS_STORE, blob, id);
99
- }
100
- /** Fetch and decrypt a secret, or undefined if absent. */
101
- async getSecret(id) {
102
- const db = await openAgentWebDB({ dbName: this.dbName });
103
- const blob = await db.get(SECRETS_STORE, id);
104
- if (!blob) return void 0;
105
- return decryptJSON(await this.key(), blob);
106
- }
107
- async deleteSecret(id) {
108
- const db = await openAgentWebDB({ dbName: this.dbName });
109
- await db.delete(SECRETS_STORE, id);
110
- }
111
- async listSecretIds() {
112
- const db = await openAgentWebDB({ dbName: this.dbName });
113
- return (await db.getAllKeys(SECRETS_STORE)).map(String);
114
- }
115
- };
116
-
117
- export {
118
- createLogger,
119
- getOrCreateVaultKey,
120
- encryptJSON,
121
- decryptJSON,
122
- IndexedDBVault
123
- };
124
- //# sourceMappingURL=chunk-T6LZW7ML.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/logger.ts","../src/secrets/crypto.ts","../src/secrets/vault.ts"],"sourcesContent":["/**\n * Leveled logging for the agent. The host passes a console-like sink and a\n * level; everything below the level is a no-op. Default: 'warn' onto the\n * global console — silent in normal operation, but salvage fallbacks, empty\n * plans, degraded tool modes and failed tool calls stay visible.\n *\n * Set `logLevel: 'debug'` to see every phase's raw model output, parsed\n * results and tool dispatches — the first thing to reach for when the agent\n * \"says it did something but nothing happened\".\n */\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\n/** Console-compatible sink (pass `console`, or your own collector). */\nexport interface AgentLoggerSink {\n error(...args: unknown[]): void\n warn(...args: unknown[]): void\n info(...args: unknown[]): void\n debug(...args: unknown[]): void\n}\n\nexport interface AgentLogger extends AgentLoggerSink {\n readonly level: LogLevel\n}\n\nconst WEIGHT: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n}\n\nconst PREFIX = '[agent-web]'\n\nconst noop = (): void => undefined\n\nexport const createLogger = (\n level: LogLevel = 'warn',\n sink: AgentLoggerSink = console,\n): AgentLogger => {\n const at = (min: LogLevel, fn: (...args: unknown[]) => void) =>\n WEIGHT[level] >= WEIGHT[min] ? (...args: unknown[]) => fn.call(sink, PREFIX, ...args) : noop\n return {\n level,\n error: at('error', sink.error),\n warn: at('warn', sink.warn),\n info: at('info', sink.info),\n debug: at('debug', sink.debug),\n }\n}\n","import { KEYS_STORE, openAgentWebDB } from '../storage/db.js'\n\nconst KEY_ID = 'vault-key-v1'\n\nconst webcrypto = (): Crypto => {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (!c?.subtle || !c.getRandomValues) {\n throw new Error('WebCrypto (crypto.subtle) is unavailable in this environment')\n }\n return c\n}\n\nconst loadOrCreateKey = async (dbName?: string): Promise<CryptoKey> => {\n const db = await openAgentWebDB({ dbName })\n const existing = (await db.get(KEYS_STORE, KEY_ID)) as CryptoKey | undefined\n if (existing) return existing\n const key = await webcrypto().subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n /* extractable */ false,\n ['encrypt', 'decrypt'],\n )\n // Double-check inside one readwrite transaction: another tab may have created\n // a key while ours was generating. Losing that race and overwriting would\n // leave the other tab's secrets permanently undecryptable.\n const tx = db.transaction(KEYS_STORE, 'readwrite')\n const winner = (await tx.store.get(KEY_ID)) as CryptoKey | undefined\n if (winner) {\n await tx.done\n return winner\n }\n await tx.store.put(key, KEY_ID)\n await tx.done\n return key\n}\n\nconst keyCache = new Map<string, Promise<CryptoKey>>()\n\n/**\n * Fetch (or lazily create) the vault's AES-GCM key. The key is generated\n * NON-EXTRACTABLE and stored as a live `CryptoKey` in IndexedDB — a CryptoKey\n * is structured-cloneable, so it persists across reloads WITHOUT its raw bytes\n * ever being exposed to JavaScript. Not even in-page script can read it out; it\n * can only be used to encrypt / decrypt. That is what makes at-rest storage of\n * the secrets meaningful (see IndexedDBVault's threat model).\n *\n * Concurrent callers share one in-flight promise per DB, and creation is\n * double-checked in a single IDB transaction, so two racing writers can never\n * end up encrypting under different keys.\n */\nexport const getOrCreateVaultKey = (dbName?: string): Promise<CryptoKey> => {\n const cacheKey = dbName ?? 'agent-web'\n let p = keyCache.get(cacheKey)\n if (!p) {\n p = loadOrCreateKey(dbName)\n keyCache.set(cacheKey, p)\n p.catch(() => {\n if (keyCache.get(cacheKey) === p) keyCache.delete(cacheKey)\n })\n }\n return p\n}\n\nexport interface EncryptedBlob {\n /** 96-bit random IV, fresh per write. */\n iv: Uint8Array\n ciphertext: ArrayBuffer\n}\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n/** Encrypt a JSON-serialisable value with a fresh 96-bit IV (AES-GCM). */\nexport const encryptJSON = async (key: CryptoKey, value: unknown): Promise<EncryptedBlob> => {\n const c = webcrypto()\n const iv = c.getRandomValues(new Uint8Array(12))\n const data = textEncoder.encode(JSON.stringify(value))\n const ciphertext = await c.subtle.encrypt({ name: 'AES-GCM', iv }, key, data)\n return { iv, ciphertext }\n}\n\n/** Decrypt a blob produced by encryptJSON. Throws if the key or blob don't match. */\nexport const decryptJSON = async <T = unknown>(key: CryptoKey, blob: EncryptedBlob): Promise<T> => {\n // Copy the IV into a fresh ArrayBuffer-backed view: after a round-trip through\n // IndexedDB its element buffer is typed as ArrayBufferLike, which no longer\n // satisfies BufferSource under TS's stricter typed-array generics.\n const iv = new Uint8Array(blob.iv)\n const plain = await webcrypto().subtle.decrypt({ name: 'AES-GCM', iv }, key, blob.ciphertext)\n return JSON.parse(textDecoder.decode(plain)) as T\n}\n","import { openAgentWebDB, SECRETS_STORE } from '../storage/db.js'\nimport { decryptJSON, encryptJSON, getOrCreateVaultKey, type EncryptedBlob } from './crypto.js'\n\nexport interface VaultOptions {\n /** Database name, forwarded to the shared IDB owner (default 'agent-web'). */\n dbName?: string\n}\n\n/**\n * Encrypted key/value secret store backed by IndexedDB. Values are encrypted at\n * rest with the non-extractable AES-GCM vault key (see crypto.ts).\n *\n * ── THREAT MODEL (read before shipping any app-owned key to a browser) ──\n * This vault PROTECTS secrets **at rest** — an IndexedDB / disk dump yields\n * only ciphertext — and against **casual DevTools inspection** — no plaintext\n * key is stored, and the AES key cannot be exported even by in-page script.\n *\n * It does **NOT** defend against **active XSS on your origin**: any script that\n * already runs on the page can call `getSecret()`, or use the live `CryptoKey`\n * to decrypt. Browser storage is not a secrets manager.\n *\n * Therefore this vault is for the **end user's OWN key on their OWN device**\n * (bring-your-own-key). A shared, app-owned key must NEVER reach the client —\n * put it behind a server proxy (`ProviderModelSpec.baseURL`) or the Vercel AI\n * Gateway instead.\n */\nexport class IndexedDBVault {\n private readonly dbName?: string\n\n constructor(opts: VaultOptions = {}) {\n this.dbName = opts.dbName\n }\n\n private key(): Promise<CryptoKey> {\n return getOrCreateVaultKey(this.dbName)\n }\n\n /** Encrypt and store a secret string under `id`. */\n async setSecret(id: string, value: string): Promise<void> {\n const blob = await encryptJSON(await this.key(), value)\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.put(SECRETS_STORE, blob, id)\n }\n\n /** Fetch and decrypt a secret, or undefined if absent. */\n async getSecret(id: string): Promise<string | undefined> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n const blob = (await db.get(SECRETS_STORE, id)) as EncryptedBlob | undefined\n if (!blob) return undefined\n return decryptJSON<string>(await this.key(), blob)\n }\n\n async deleteSecret(id: string): Promise<void> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.delete(SECRETS_STORE, id)\n }\n\n async listSecretIds(): Promise<string[]> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n return (await db.getAllKeys(SECRETS_STORE)).map(String)\n }\n}\n"],"mappings":";;;;;;;AAyBA,I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AAG,KAAK;AACtD,UAAM,KAAK,MAAM,eAAe,EAAE,QAAQ,KAAK,OAAO,CAAC;AACvD,UAAM,GAAG,IAAI,eAAe,MAAM,EAAE;AAAA,EACtC;AAAA;AAAA,EAGA,MAAM,UAAU,IAAyC;AACvD,UAAM,KAAK,MAAM,eAAe,EAAE,QAAQ,KAAK,OAAO,CAAC;AACvD,UAAM,OAAQ,MAAM,GAAG,IAAI,eAAe,EAAE;AAC5C,QAAI,CAAC,KAAM,QAAO;AAClB,WAAO,YAAoB,MAAM,KAAK,IAAI,GAAG,IAAI;AAAA,EACnD;AAAA,EAEA,MAAM,aAAa,IAA2B;AAC5C,UAAM,KAAK,MAAM,eAAe,EAAE,QAAQ,KAAK,OAAO,CAAC;AACvD,UAAM,GAAG,OAAO,eAAe,EAAE;AAAA,EACnC;AAAA,EAEA,MAAM,gBAAmC;AACvC,UAAM,KAAK,MAAM,eAAe,EAAE,QAAQ,KAAK,OAAO,CAAC;AACvD,YAAQ,MAAM,GAAG,WAAW,aAAa,GAAG,IAAI,MAAM;AAAA,EACxD;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/webllm.ts","../src/context-window.ts","../src/images.ts","../src/llm/generate.ts","../src/llm/util.ts","../src/memory/compress.ts"],"sourcesContent":["import { generateText, type LanguageModel } from 'ai'\nimport { withWebLLMContextWindow, type WebLLMAppConfigLike } from '../context-window.js'\n\n/** WebGPU feature-detect — WebLLM requires it. Call before offering local models. */\nexport const isWebGPUAvailable = (): boolean =>\n typeof navigator !== 'undefined' && 'gpu' in navigator\n\nexport interface WebLLMModelOptions {\n /**\n * Progress callback for weight download / engine init. `report.progress` is\n * 0..1. Forwarded to WebLLM's `initProgressCallback`.\n */\n initProgressCallback?: (report: { progress: number; text: string }) => void\n /**\n * Download the weights and initialize the engine NOW (default true).\n *\n * The underlying provider initializes lazily on the first generation — with\n * a multi-GB model that means the download would silently happen on the\n * user's first message, with `initProgressCallback` never firing at a moment\n * the host can show it. Preloading runs a 1-token warm-up so the returned\n * model is truly ready and progress is reported during creation. Re-creating\n * an already-downloaded model is fast (weights live in the browser cache).\n *\n * Set to `false` to keep the lazy behavior.\n */\n preload?: boolean\n /**\n * The context window to load the model with, in tokens. WebLLM loads its\n * prebuilt models with 4096 (to save VRAM), far below what Qwen3 or Llama\n * 3.x were trained on; a larger window costs KV-cache memory, not a new\n * download. Applied through `engineConfig.appConfig` (WebLLM's prebuilt\n * config with this model's `context_window_size` overridden) unless you pass\n * an `appConfig` of your own; see `withWebLLMContextWindow`.\n */\n contextWindowTokens?: number\n /** Any other @browser-ai/web-llm setting (temperature, worker handler, …). */\n [k: string]: unknown\n}\n\n/**\n * Force a model to download its weights and initialize its engine by running\n * a 1-token generation. Exposed for hosts that create models with\n * `preload: false` and want to warm them up later (e.g. behind their own UI).\n */\nexport const preloadWebLLMModel = async (model: LanguageModel): Promise<void> => {\n await generateText({ model, prompt: 'ok', maxOutputTokens: 1 })\n}\n\n/**\n * Best-effort release of a model's GPU memory (call when switching models —\n * an abandoned engine otherwise holds its buffers until the page reloads).\n *\n * `@browser-ai/web-llm` keeps its MLCEngine private and exposes no public\n * `unload()`, so this reaches into the instance defensively; it is a no-op on\n * an uninitialized model or if the provider's internals change shape.\n */\nexport const unloadWebLLMModel = async (model: LanguageModel): Promise<void> => {\n const engine = (model as { engine?: { unload?: () => Promise<void> } }).engine\n try {\n await engine?.unload?.()\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * Build an AI SDK `LanguageModel` backed by WebLLM (WebGPU) via the community\n * provider `@browser-ai/web-llm` (an optional peer, dynamically imported so it\n * is code-split and never loads until a local model is actually used). Accepts\n * any WebLLM prebuilt model id, e.g. \"Llama-3.2-3B-Instruct-q4f16_1-MLC\".\n *\n * By default the weights are downloaded eagerly with progress (see\n * `WebLLMModelOptions.preload`).\n */\nexport const createWebLLMModel = async (\n model: string,\n options?: WebLLMModelOptions,\n): Promise<LanguageModel> => {\n let mod: typeof import('@browser-ai/web-llm')\n try {\n mod = await import('@browser-ai/web-llm')\n } catch {\n throw new Error(\n 'Local models require \"@browser-ai/web-llm\" and its peer \"@mlc-ai/web-llm\". Install: npm install @browser-ai/web-llm @mlc-ai/web-llm',\n )\n }\n const { preload = true, contextWindowTokens, ...settings } = options ?? {}\n if (contextWindowTokens) {\n const engineConfig = (settings.engineConfig ?? {}) as { appConfig?: WebLLMAppConfigLike }\n let base = engineConfig.appConfig\n if (!base) {\n try {\n const spec = '@mlc-ai/web-llm'\n base = (\n (await import(/* webpackIgnore: true */ /* @vite-ignore */ spec)) as {\n prebuiltAppConfig: WebLLMAppConfigLike\n }\n ).prebuiltAppConfig\n } catch {\n throw new Error(\n 'contextWindowTokens needs \"@mlc-ai/web-llm\" (for its prebuilt model list), or pass engineConfig.appConfig yourself.',\n )\n }\n }\n settings.engineConfig = {\n ...engineConfig,\n appConfig: withWebLLMContextWindow(base, model, contextWindowTokens),\n }\n }\n // webLLM(modelId, settings) returns a LanguageModel. The model id is a strict\n // union in the provider's types; we accept any string and cast at the seam.\n const languageModel = mod.webLLM(\n model as Parameters<typeof mod.webLLM>[0],\n settings as Parameters<typeof mod.webLLM>[1],\n )\n if (preload) await preloadWebLLMModel(languageModel)\n return languageModel\n}\n","import { asSchema, type ToolSet } from 'ai'\nimport { modelLabel } from './images.js'\nimport {\n estimateTokens,\n type CompactionConfig,\n type ResolvedCompaction,\n} from './memory/compress.js'\n\n/**\n * The model's context window is a hard limit: a prompt that does not fit is\n * refused outright (WebLLM: \"Prompt tokens exceed context window size\"). The\n * agent sizes everything that grows — compaction thresholds, tool-result\n * clearing, the cap on one tool result, whether tools are listed or searched —\n * from the window, so it has to be the model's real one.\n *\n * Cloud windows are large and the host states them (`compaction.\n * contextWindowTokens`); a local WebLLM model's window is small (4096 tokens\n * by default — WebLLM's choice to save VRAM, not the model's limit) and is read\n * from the model itself.\n */\n\ninterface WebLLMRecordLike {\n model_id: string\n overrides?: { context_window_size?: number } & Record<string, unknown>\n}\n\n/** The shape of a WebLLM `AppConfig` this module touches. */\nexport interface WebLLMAppConfigLike {\n model_list: WebLLMRecordLike[]\n}\n\n/** WebLLM's default window for its prebuilt models. */\nexport const WEBLLM_DEFAULT_CONTEXT_WINDOW = 4096\n\n/**\n * A copy of a WebLLM app config (e.g. `prebuiltAppConfig` from\n * `@mlc-ai/web-llm`) with one model's context window set. Pass it as\n * `engineConfig.appConfig` when building the model: the weights are the same,\n * only the KV cache (VRAM) grows with the window. Models trained on long\n * contexts (Qwen3, Llama 3.x) take far more than the default 4096; models\n * trained on 4k (Llama 2) don't.\n */\nexport const withWebLLMContextWindow = <T extends WebLLMAppConfigLike>(\n appConfig: T,\n modelId: string,\n tokens: number,\n): T => ({\n ...appConfig,\n model_list: appConfig.model_list.map((r) =>\n r.model_id === modelId\n ? { ...r, overrides: { ...r.overrides, context_window_size: tokens } }\n : r,\n ),\n})\n\ninterface WebLLMModelLike {\n provider?: string\n modelId?: string\n engine?: {\n loadedModelIdToPipeline?: { get?: (id: string) => { contextWindowSize?: number } | undefined }\n }\n config?: { options?: { engineConfig?: { appConfig?: WebLLMAppConfigLike } } }\n}\n\n/**\n * The context window of a WebLLM model (`@browser-ai/web-llm`), or undefined\n * for any other model. Read from the loaded engine when it runs in this\n * thread, else from the app config it was built with, else WebLLM's defaults\n * (1024 for its \"-1k\" builds, 4096 otherwise). The provider keeps these\n * private, so this reaches in defensively.\n */\nexport const webLLMContextWindow = (model: unknown): number | undefined => {\n const m = model as WebLLMModelLike | undefined\n if (!m || typeof m !== 'object' || m.provider !== 'web-llm') return undefined\n const id = String(m.modelId ?? '')\n try {\n const live = m.engine?.loadedModelIdToPipeline?.get?.(id)?.contextWindowSize\n if (typeof live === 'number' && live > 0) return live\n } catch {\n /* the engine lives in a worker, or changed shape */\n }\n const record = m.config?.options?.engineConfig?.appConfig?.model_list?.find(\n (r) => r.model_id === id,\n )\n const configured = record?.overrides?.context_window_size\n if (typeof configured === 'number' && configured > 0) return configured\n return /-1k$/i.test(id) ? 1024 : WEBLLM_DEFAULT_CONTEXT_WINDOW\n}\n\n/**\n * The model's own context window when it can be known (local models), else\n * undefined: WebLLM's (see above), or the browser's built-in model's\n * (`@browser-ai/core` reports it once its session exists).\n */\nexport const contextWindowOf = (model: unknown): number | undefined => {\n const webllm = webLLMContextWindow(model)\n if (webllm !== undefined) return webllm\n const m = model as { provider?: string; getContextWindow?: () => number | undefined } | undefined\n if (m && typeof m === 'object' && m.provider === 'browser-ai') {\n try {\n const w = m.getContextWindow?.()\n return typeof w === 'number' && w > 0 ? w : undefined\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\n/**\n * Fit the compaction settings to the model's window: the window in use is the\n * configured one, never larger than the model's own, and every size derived\n * from it shrinks with it — also a size the host set for a larger window.\n */\nexport const fitCompactionToWindow = (\n resolved: ResolvedCompaction,\n configured: CompactionConfig | undefined,\n modelWindow: number | undefined,\n): ResolvedCompaction => {\n const window = Math.min(\n configured?.contextWindowTokens ?? modelWindow ?? resolved.contextWindowTokens,\n modelWindow ?? Infinity,\n )\n if (window === resolved.contextWindowTokens && modelWindow === undefined) return resolved\n const quarter = Math.floor(window / 4)\n const clearAfter = configured?.clearToolResultsAfterTokens\n return {\n ...resolved,\n contextWindowTokens: window,\n // A threshold the host set for a larger window comes down with the window: never past 95%\n // of what the model really has (the answer and a step's growth need the rest).\n thresholdTokens: Math.min(\n configured?.thresholdTokens ?? Math.floor(window * resolved.thresholdRatio),\n Math.floor(window * 0.95),\n ),\n // 0 = never stays never.\n clearToolResultsAfterTokens: clearAfter === 0 ? 0 : Math.min(clearAfter ?? quarter, quarter),\n // One result may take a quarter of the window (~4 chars per token).\n maxToolOutputChars:\n configured?.maxToolOutputChars === 0\n ? 0\n : Math.min(configured?.maxToolOutputChars ?? 20_000, window),\n // A small window holds fewer verbatim results.\n keepToolResults:\n configured?.keepToolResults ?? Math.max(1, Math.min(3, Math.floor(window / 8192))),\n }\n}\n\n/**\n * Estimated tokens of the tool definitions a model is sent (name, description,\n * JSON schema of the input) — for tools natively, or rendered into the prompt.\n */\nexport const toolDefinitionTokens = async (tools: ToolSet): Promise<number> => {\n const sizes = await Promise.all(\n Object.entries(tools).map(async ([name, t]) => {\n let parameters: unknown\n try {\n parameters = await asSchema(t.inputSchema as never).jsonSchema\n } catch {\n parameters = undefined\n }\n return estimateTokens(JSON.stringify({ name, description: t.description ?? '', parameters }))\n }),\n )\n return sizes.reduce((a, b) => a + b, 0)\n}\n\n/** What every call carries whatever the transcript: stage instructions, the goal, the plan, the state. */\nexport const BASE_PROMPT_TOKENS = 1500\n/** Under tool search the model is sent only the built-ins and the tools found so far. */\nexport const SEARCH_TOOLS_ALLOWANCE = 3000\n\n/**\n * The tokens of a call's prompt that do not come from the transcript or the step log - the\n * stage instructions, the tool definitions, the skills - so that compaction can judge how full the\n * window really is (history + log alone say nothing about a 15k-token tool catalogue).\n */\nexport const promptOverheadTokens = (p: {\n systemPrompt?: string\n /** `toolDefinitionTokens` of everything the agent could offer. */\n toolTokens: number\n /** Tool search: only a few definitions are sent at a time. */\n searching: boolean\n /** The rendered skills index and the active skills' instructions. */\n skillsText: string\n}): number =>\n BASE_PROMPT_TOKENS +\n estimateTokens(p.systemPrompt ?? '') +\n (p.searching ? Math.min(p.toolTokens, SEARCH_TOOLS_ALLOWANCE) : p.toolTokens) +\n estimateTokens(p.skillsText)\n\n/** 'auto' switches to tool search once the definitions would take this share of the window. */\nexport const TOOL_SEARCH_WINDOW_SHARE = 0.25\n\n/** Raised when a prompt does not fit the model's context window. */\nexport class ContextWindowExceededError extends Error {\n /** The prompt's size as the provider counted it, when it said. */\n readonly promptTokens?: number\n /** The model's window as the provider reported it, when it said. */\n readonly contextWindowTokens?: number\n constructor(model: string, promptTokens?: number, contextWindowTokens?: number) {\n const sizes =\n promptTokens && contextWindowTokens\n ? ` (${promptTokens} tokens; the window is ${contextWindowTokens})`\n : ''\n super(\n `The conversation no longer fits the context window of \"${model}\"${sizes}. Start a new chat or compact this one, connect fewer tools, or switch to a model with a larger window.`,\n )\n this.name = 'ContextWindowExceededError'\n this.promptTokens = promptTokens\n this.contextWindowTokens = contextWindowTokens\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n// What providers say when the prompt is too long: WebLLM, OpenAI\n// (context_length_exceeded), Anthropic, Gemini, llama.cpp, vLLM / OpenRouter.\nconst OVERFLOW_RE =\n /prompt tokens exceed context window|context window size|context_length_exceeded|maximum context length|prompt is too long|input token count.*exceeds|exceeds the maximum number of tokens|exceeds the available context size|context length exceeded|too many tokens in (the )?(prompt|input)/i\nconst WEBLLM_SIZES_RE = /number of prompt tokens:\\s*(\\d+);\\s*context window size:\\s*(\\d+)/i\n\n/**\n * The clear error to raise when a provider refused a prompt for its length\n * (else undefined) — instead of the provider's raw text.\n */\nexport const contextOverflowOf = (\n err: unknown,\n model: unknown,\n): ContextWindowExceededError | undefined => {\n if (err instanceof ContextWindowExceededError) return err\n const text = err instanceof Error ? `${err.name} ${err.message}` : String(err)\n if (!OVERFLOW_RE.test(text)) return undefined\n const sizes = WEBLLM_SIZES_RE.exec(text)\n return new ContextWindowExceededError(\n modelLabel(model),\n sizes ? Number(sizes[1]) : undefined,\n sizes ? Number(sizes[2]) : (webLLMContextWindow(model) ?? undefined),\n )\n}\n","import type { FilePart } from 'ai'\n\n/**\n * Attachments sent with a run: images, PDFs and other files the provider can\n * read, given as bytes / base64 / a data URL — or as an http(s) URL, which\n * providers that accept links (Gemini, Claude, OpenAI) fetch themselves and the\n * AI SDK downloads for the rest (from the browser: subject to CORS).\n */\nexport interface RunFile {\n /** Base64 (no prefix), a data URL (\"data:image/png;base64,…\"), raw bytes, or an http(s) URL. */\n data: string | Uint8Array | URL\n /** e.g. \"image/png\", \"application/pdf\" — read from a data URL when omitted. */\n mediaType?: string\n /** Shown in the transcript, in memory and in errors. */\n name?: string\n}\n\n/** An image attachment (same shape; kept as its own name for clarity). */\nexport type RunImage = RunFile\n\n/** The kinds of attachment the agent reasons about separately. */\nexport type AttachmentKind = 'image' | 'pdf' | 'file'\n\nconst DATA_URL_RE = /^data:([^;,]+)?;base64,(.*)$/s\nconst HTTP_RE = /^https?:\\/\\//i\n\n/** The media type of an attachment (declared, from a data URL, or from a URL's extension). */\nexport const mediaTypeOf = (f: RunFile): string | undefined => {\n if (f.mediaType) return f.mediaType\n if (typeof f.data === 'string') {\n const m = DATA_URL_RE.exec(f.data)\n if (m?.[1]) return m[1]\n }\n const url = f.data instanceof URL ? f.data.href : typeof f.data === 'string' ? f.data : ''\n if (HTTP_RE.test(url) || f.name) {\n const ext = (f.name ?? new URL(url, 'http://x').pathname).split('.').pop()?.toLowerCase()\n if (ext === 'pdf') return 'application/pdf'\n if (ext && ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {\n return `image/${ext === 'jpg' ? 'jpeg' : ext}`\n }\n }\n return undefined\n}\n\nexport const attachmentKind = (f: RunFile): AttachmentKind => {\n const mt = mediaTypeOf(f) ?? ''\n if (mt.startsWith('image/')) return 'image'\n if (mt === 'application/pdf') return 'pdf'\n return 'file'\n}\n\nconst KIND_LABEL: Record<AttachmentKind, string> = {\n image: 'images',\n pdf: 'PDF files',\n file: 'file attachments',\n}\n\nconst KIND_HINT: Record<AttachmentKind, string> = {\n image:\n 'Remove the image, or switch to a vision-capable model such as Gemini, Claude or GPT-4o/GPT-5.',\n pdf: 'Convert the PDF to text first (e.g. PDF → Markdown), or switch to a model that reads PDFs such as Gemini, Claude or GPT-4o/GPT-5.',\n file: 'Paste its text instead, or switch to a model that accepts this file type.',\n}\n\n/** Raised when attachments are sent to a model that cannot take them. */\nexport class AttachmentsNotSupportedError extends Error {\n readonly kind: AttachmentKind\n constructor(model: string, kind: AttachmentKind, detail?: string) {\n super(\n `The model \"${model}\" can't take ${KIND_LABEL[kind]}${detail ? ` (${detail})` : ''}. ${KIND_HINT[kind]}`,\n )\n this.name = 'AttachmentsNotSupportedError'\n this.kind = kind\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n/** The image flavour of {@link AttachmentsNotSupportedError}. */\nexport class ImagesNotSupportedError extends AttachmentsNotSupportedError {\n constructor(model: string, detail?: string) {\n super(model, 'image', detail)\n this.name = 'ImagesNotSupportedError'\n }\n}\n\n/** The error for a kind: images get the dedicated class. */\nexport const unsupportedAttachment = (\n model: string,\n kind: AttachmentKind,\n detail?: string,\n): AttachmentsNotSupportedError =>\n kind === 'image'\n ? new ImagesNotSupportedError(model, detail)\n : new AttachmentsNotSupportedError(model, kind, detail)\n\nconst dataOf = (f: RunFile): string | Uint8Array | URL => {\n if (typeof f.data === 'string') {\n const m = DATA_URL_RE.exec(f.data)\n if (m) return m[2]\n if (HTTP_RE.test(f.data)) return new URL(f.data)\n }\n return f.data\n}\n\n/**\n * An AI SDK file part (images included — the v7 SDK deprecates the separate\n * image part). An http(s) URL is passed as a URL: providers that accept links\n * fetch it themselves, and the SDK downloads it for the rest.\n */\nexport const toFilePart = (f: RunFile): FilePart => {\n const kind = attachmentKind(f)\n const mediaType = mediaTypeOf(f) ?? (kind === 'image' ? 'image' : 'application/octet-stream')\n return {\n type: 'file',\n data: dataOf(f),\n mediaType,\n ...(f.name ? { filename: f.name } : {}),\n }\n}\n\n/** Back-compat name. */\nexport const toImagePart = toFilePart\n\n/** A short, human label of a model for messages. */\nexport const modelLabel = (model: unknown): string => {\n if (typeof model === 'string') return model\n const m = model as { provider?: string; modelId?: string } | undefined\n return m?.modelId ? `${m.modelId}${m.provider ? ` (${m.provider})` : ''}` : 'this model'\n}\n\nconst REFUSAL_RE =\n /image|vision|multimodal|multi-modal|media type|mediatype|pdf|document|unsupported (file|content|part|mime)|does not support (file|content)|invalid content type|image_url|inline_?data|file_?data/i\n\n/** Does a provider error look like a refusal of attachment input? */\nexport const isAttachmentRefusal = (err: unknown): boolean =>\n REFUSAL_RE.test(err instanceof Error ? `${err.name} ${err.message}` : String(err))\n\n/** Back-compat name. */\nexport const isImageRefusal = isAttachmentRefusal\n","import {\n generateObject,\n generateText,\n streamText,\n type LanguageModel,\n type ModelMessage,\n type SystemModelMessage,\n type ToolSet,\n} from 'ai'\nimport type { ZodType } from 'zod'\nimport type { ProviderOptionsMap, ThinkingLevel } from '../thinking.js'\nimport { promptOf, timeoutSignal } from './util.js'\n\n/** Options shared by the low-level generation helpers. Provide `prompt` OR `messages`. */\nexport interface GenerateOptions {\n /** The system prompt — a string, or a SystemModelMessage (e.g. with a cache breakpoint). */\n system?: string | SystemModelMessage\n prompt?: string\n messages?: ModelMessage[]\n tools?: ToolSet\n maxOutputTokens?: number\n temperature?: number\n /** Portable thinking level (see `resolveThinking`). */\n reasoning?: ThinkingLevel\n /** Provider-keyed options (thinking budgets, cache keys, …). */\n providerOptions?: ProviderOptionsMap\n abortSignal?: AbortSignal\n /** Time-box the call; combined with `abortSignal` (0/undefined = no timeout). */\n timeoutMs?: number\n}\n\n/** The settings every helper forwards; omits undefined keys the SDK would reject. */\nconst callSettings = (opts: GenerateOptions) => ({\n ...(opts.system !== undefined ? { instructions: opts.system } : {}),\n maxOutputTokens: opts.maxOutputTokens,\n temperature: opts.temperature,\n ...(opts.reasoning ? { reasoning: opts.reasoning } : {}),\n ...(opts.providerOptions ? { providerOptions: opts.providerOptions as never } : {}),\n abortSignal: timeoutSignal(opts.abortSignal, opts.timeoutMs),\n})\n\n/**\n * One-shot text generation. Thin, provider-agnostic wrapper over the AI SDK's\n * `generateText` — the same call works against a cloud model, a local WebLLM\n * model, or Chrome/Edge built-in AI. Returns the full AI SDK result (`.text`,\n * `.usage`, `.toolCalls`, `.steps`, …).\n */\nexport const generate = (\n model: LanguageModel,\n opts: GenerateOptions = {},\n): ReturnType<typeof generateText> =>\n generateText({\n model,\n ...callSettings(opts),\n ...promptOf(opts),\n tools: opts.tools,\n })\n\n/** Streaming text generation. Returns the AI SDK `streamText` result (`.textStream`, `.fullStream`). */\nexport const stream = (\n model: LanguageModel,\n opts: GenerateOptions = {},\n): ReturnType<typeof streamText> =>\n streamText({\n model,\n ...callSettings(opts),\n ...promptOf(opts),\n tools: opts.tools,\n })\n\n/**\n * Structured output constrained to a Zod schema, via the AI SDK's\n * `generateObject`. Cloud models and WebLLM both support this; tiny local\n * models can be unreliable — the agent's prompted mode is the fallback.\n * Returns the AI SDK result (`.object`, `.usage`).\n */\nexport const generateStructured = <OBJECT>(\n model: LanguageModel,\n schema: ZodType<OBJECT>,\n opts: GenerateOptions = {},\n) =>\n generateObject({\n model,\n schema,\n ...callSettings(opts),\n ...promptOf(opts),\n })\n","import type { ModelMessage } from 'ai'\nimport type { IUsage } from '../agent/loop-types.js'\n\n/** Truncate to `max` characters, ellipsising the overflow. */\nexport const clip = (s: string, max: number): string =>\n s.length > max ? `${s.slice(0, max - 1)}…` : s\n\n/**\n * The AI SDK prompt is `{ prompt } XOR { messages }` — passing both keys (even\n * with one undefined) breaks the discriminated union. Pick exactly one.\n */\nexport const promptOf = (opts: {\n prompt?: string\n messages?: ModelMessage[]\n}): { prompt: string } | { messages: ModelMessage[] } =>\n opts.messages ? { messages: opts.messages } : { prompt: opts.prompt ?? '' }\n\n/** The AI SDK usage shape, every field optional (providers omit what they don't report). */\nexport interface SdkUsageLike {\n inputTokens?: number\n outputTokens?: number\n totalTokens?: number\n inputTokenDetails?: { cacheReadTokens?: number; cacheWriteTokens?: number }\n outputTokenDetails?: { reasoningTokens?: number }\n /** Pre-v6 flat fields, still emitted by some providers. */\n reasoningTokens?: number\n cachedInputTokens?: number\n}\n\n/** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */\n/**\n * What a call that FAILED still cost. The AI SDK puts the usage on the error it throws when a\n * structured answer cannot be parsed (`NoObjectGeneratedError.usage`); the tokens were spent\n * all the same, and a fallback call must not hide them.\n */\nexport const usageOfError = (err: unknown): IUsage => {\n const u = (err as { usage?: SdkUsageLike } | null | undefined)?.usage\n return normalizeUsage(u && typeof u === 'object' ? u : undefined)\n}\n\nexport const normalizeUsage = (u?: SdkUsageLike): IUsage => {\n const inputTokens = u?.inputTokens ?? 0\n const outputTokens = u?.outputTokens ?? 0\n return {\n inputTokens,\n outputTokens,\n totalTokens: u?.totalTokens ?? inputTokens + outputTokens,\n reasoningTokens: u?.outputTokenDetails?.reasoningTokens ?? u?.reasoningTokens ?? 0,\n cachedInputTokens: u?.inputTokenDetails?.cacheReadTokens ?? u?.cachedInputTokens ?? 0,\n cacheWriteTokens: u?.inputTokenDetails?.cacheWriteTokens ?? 0,\n }\n}\n\n/**\n * Combine the caller's AbortSignal with a timeout so a hung generation can't\n * freeze a run. Returns the original signal when no timeout is set. Uses the\n * standard `AbortSignal.timeout`/`AbortSignal.any` (Node ≥ 20, modern browsers).\n */\nexport const timeoutSignal = (signal?: AbortSignal, ms?: number): AbortSignal | undefined => {\n if (!ms || ms <= 0) return signal\n const timeout = AbortSignal.timeout(ms)\n if (!signal) return timeout\n return typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, timeout]) : signal\n}\n","import type { LanguageModel } from 'ai'\nimport { generate } from '../llm/generate.js'\nimport { normalizeUsage } from '../llm/util.js'\nimport type { IUsage } from '../agent/loop-types.js'\nimport type { StoredMessage } from './store.js'\n\n/**\n * Context compaction. A model's window is finite and every token in it is paid\n * for on every call, so long transcripts and long runs are folded into a\n * summary: the oldest material is summarised by a model, the most recent is\n * kept verbatim.\n */\nexport interface CompactionConfig {\n /** Compact automatically before planning and between steps (default true). */\n auto?: boolean\n /** The model's context window, in tokens (default 128 000). */\n contextWindowTokens?: number\n /**\n * Compact once the estimated context - the fixed prompt (system, tools, skills), the transcript\n * and the run's step log together - exceeds this many tokens. Default: `thresholdRatio` of the\n * window.\n */\n thresholdTokens?: number\n /**\n * The same threshold as a share of the window, 0 < ratio <= 1 (default 0.85). `thresholdTokens`\n * wins when both are set; it follows the window if the model turns out to have a smaller one.\n */\n thresholdRatio?: number\n /** Transcript messages kept verbatim (default 4). */\n keepRecentTurns?: number\n /** Executed steps kept verbatim in the run's trace (default 3). */\n keepRecentSteps?: number\n /** Output cap of a summary call (default 1024). */\n summaryMaxTokens?: number\n /** Cap on ONE tool result as the model sees it, in chars (default 20 000; 0 = no cap). */\n maxToolOutputChars?: number\n /**\n * Inside one step's tool loop: once its context passes this many tokens,\n * replace the oldest tool results with one-line stubs (context editing;\n * default: a quarter of the window; 0 = never).\n */\n clearToolResultsAfterTokens?: number\n /** Most recent tool results kept verbatim when clearing (default 3). */\n keepToolResults?: number\n}\n\nexport interface ResolvedCompaction {\n auto: boolean\n contextWindowTokens: number\n thresholdTokens: number\n thresholdRatio: number\n keepRecentTurns: number\n keepRecentSteps: number\n summaryMaxTokens: number\n maxToolOutputChars: number\n clearToolResultsAfterTokens: number\n keepToolResults: number\n}\n\n/**\n * Compaction starts at this share of the window unless configured. The estimate leans high (see\n * `estimateTokens`), so on a Claude model this is roughly 70-75% really used - the rest is room\n * for the answer and for what one step adds before the next check.\n */\nexport const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85\n\nconst ratioOf = (r: number | undefined): number =>\n typeof r === 'number' && r > 0 && r <= 1 ? r : DEFAULT_COMPACTION_THRESHOLD_RATIO\n\nexport const resolveCompaction = (c: CompactionConfig | undefined): ResolvedCompaction => {\n const contextWindowTokens = c?.contextWindowTokens ?? 128_000\n const thresholdRatio = ratioOf(c?.thresholdRatio)\n return {\n auto: c?.auto ?? true,\n contextWindowTokens,\n thresholdTokens: c?.thresholdTokens ?? Math.floor(contextWindowTokens * thresholdRatio),\n thresholdRatio,\n keepRecentTurns: c?.keepRecentTurns ?? 4,\n keepRecentSteps: c?.keepRecentSteps ?? 3,\n summaryMaxTokens: c?.summaryMaxTokens ?? 1024,\n maxToolOutputChars: c?.maxToolOutputChars ?? 20_000,\n clearToolResultsAfterTokens:\n c?.clearToolResultsAfterTokens ?? Math.floor(contextWindowTokens / 4),\n keepToolResults: c?.keepToolResults ?? 3,\n }\n}\n\n// Chinese / Japanese / Korean characters and the halves of a surrogate pair (emoji): about a\n// token each. Other non-ASCII text (Cyrillic, Greek, accented Latin...) about two characters.\nconst isWide = (c: number): boolean =>\n (c >= 0x3040 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af) || (c >= 0xd800 && c <= 0xdfff)\n\n/**\n * Cheap, provider-independent token estimate, by kind of character - because text is not one\n * thing: letters run ~2.5 to a token (prose is kinder; code, markdown and JSON are not), digits\n * and punctuation about one each (JSON, tables, ids), a space a quarter, a newline one, other\n * scripts (Russian...) two characters, CJK and emoji one. Calibrated against Claude's tokenizer,\n * the most token-hungry in use, over prose, markdown, code, JSON, a table, Russian and a mix: it\n * comes out 1.1-1.4x the real count and never below it (a flat \"4 characters a token\" was\n * 0.4-0.7x for everything but Russian). It errs high ON PURPOSE: it decides when to compact, and\n * compacting a little early is cheap while overflowing the window is a failed run. A tokenizer\n * that packs tighter (OpenAI, Gemini) makes it higher still - then raise `thresholdRatio`.\n */\nexport const estimateTokens = (text: string): number => {\n const s = text ?? ''\n let letters = 0\n let digits = 0\n let spaces = 0\n let newlines = 0\n let punct = 0\n let other = 0\n let wide = 0\n for (let i = 0; i < s.length; i += 1) {\n const c = s.charCodeAt(i)\n if (c < 128) {\n if ((c >= 97 && c <= 122) || (c >= 65 && c <= 90)) letters += 1\n else if (c >= 48 && c <= 57) digits += 1\n else if (c === 32 || c === 9) spaces += 1\n else if (c === 10) newlines += 1\n else punct += 1\n } else if (isWide(c)) wide += 1\n else other += 1\n }\n // In thousandths of a token, so the arithmetic is exact: 1.1 x (letters / 2.5 + digits +\n // punctuation x 1.1 + spaces / 4 + newlines + other / 2 + wide).\n return Math.ceil(\n (440 * letters +\n 1100 * digits +\n 1210 * punct +\n 275 * spaces +\n 1100 * newlines +\n 550 * other +\n 1100 * wide) /\n 1000,\n )\n}\n\nconst messageTokens = (msgs: StoredMessage[]): number =>\n msgs.reduce((n, m) => n + estimateTokens(`${m.role}: ${m.content}\\n`), 0)\n\n/**\n * The lines joined, keeping the NEWEST ones that fit `maxTokens` (estimated); with no budget the\n * historical cut: the last 48 000 characters.\n */\nconst newestWithin = (lines: string[], maxTokens: number | undefined): string => {\n if (maxTokens === undefined) return lines.join('\\n').slice(-48_000)\n const kept: string[] = []\n let used = 0\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const t = estimateTokens(lines[i]) + 1\n if (used + t > maxTokens) {\n // A single line larger than the budget: its tail, rather than nothing.\n if (kept.length === 0) kept.push(lines[i].slice(-Math.max(1, maxTokens) * 2))\n break\n }\n kept.unshift(lines[i])\n used += t\n }\n return kept.join('\\n')\n}\n\nexport interface CompressOptions {\n /** Compress once the transcript exceeds this many characters (0 = never). */\n maxChars?: number\n /** Compress once the transcript's estimated tokens exceed this (wins over maxChars). */\n thresholdTokens?: number\n /** How many most-recent messages to keep verbatim. */\n keepRecent?: number\n /** Output cap of the summary call. */\n summaryMaxTokens?: number\n /**\n * The most the summariser is shown, in estimated tokens (the newest part is kept). Default: a\n * fixed 48 000 characters. The agent passes a share of the window, so a long transcript is\n * summarised whole instead of cut to its last few pages first.\n */\n maxInputTokens?: number\n /** Compact even when below the threshold (manual \"compact now\"). */\n force?: boolean\n /** Time-box the summarisation call so it can never hang the caller. */\n timeoutMs?: number\n abortSignal?: AbortSignal\n /** Receives the summary call's token usage. */\n onUsage?: (usage: IUsage) => void\n}\n\nconst SUMMARY_SYSTEM =\n 'Summarize the following conversation into a compact set of durable facts, decisions, ' +\n 'identifiers, open tasks and user preferences. Keep names, numbers and IDs verbatim. ' +\n 'Output plain text only.'\n\n/**\n * When the transcript grows too long, summarise everything except the last\n * `keepRecent` messages into a single system message (via the model), so the\n * session stays within the model's context window. Returns the same array\n * unchanged when no compression is needed; never throws.\n */\nexport const compressHistory = async (\n messages: StoredMessage[],\n model: LanguageModel,\n opts: CompressOptions = {},\n): Promise<StoredMessage[]> => {\n const keepRecent = opts.keepRecent ?? 6\n if (messages.length <= keepRecent + 1) return messages\n if (!opts.force) {\n if (opts.thresholdTokens !== undefined) {\n if (opts.thresholdTokens <= 0 || messageTokens(messages) <= opts.thresholdTokens) {\n return messages\n }\n } else {\n const maxChars = opts.maxChars ?? 12_000\n const chars = messages.reduce((n, m) => n + m.content.length, 0)\n if (maxChars <= 0 || chars <= maxChars) return messages\n }\n }\n const head = messages.slice(0, messages.length - keepRecent)\n const tail = messages.slice(messages.length - keepRecent)\n // The newest part of the head matters most; keep the tail end of it when it\n // has to be cut to fit the summariser's own window.\n const transcript = newestWithin(\n head.map((m) => `${m.role}: ${m.content}`),\n opts.maxInputTokens,\n )\n try {\n const result = await generate(model, {\n system: SUMMARY_SYSTEM,\n prompt: transcript,\n maxOutputTokens: opts.summaryMaxTokens ?? 400,\n timeoutMs: opts.timeoutMs,\n abortSignal: opts.abortSignal,\n })\n opts.onUsage?.(normalizeUsage(result.usage))\n const clean = (result.text || '').trim()\n if (!clean) return messages\n const summaryMsg: StoredMessage = {\n role: 'system',\n content: `Summary of earlier conversation:\\n${clean}`,\n ts: head[0]?.ts,\n }\n return [summaryMsg, ...tail]\n } catch {\n return messages\n }\n}\n\n/** Alias with the sibling package's name; same behaviour as compressHistory. */\nexport const compactHistory = compressHistory\n\nconst TRACE_SYSTEM =\n 'Summarize these completed agent steps into a compact progress note: what was done, ' +\n 'what was found (keep names, numbers and IDs verbatim) and what failed. Plain text only.'\n\n/**\n * Fold the oldest entries of a run's step log into one summary entry, keeping\n * the last `keepRecent` verbatim. Returns the input unchanged when it fits the\n * threshold or on any failure; never throws.\n */\nexport const compactSteps = async (\n done: string[],\n model: LanguageModel,\n opts: CompressOptions & { thresholdTokens: number },\n): Promise<string[]> => {\n const keepRecent = opts.keepRecent ?? 3\n if (done.length <= keepRecent + 1) return done\n if (!opts.force && estimateTokens(done.join('\\n')) <= opts.thresholdTokens) return done\n const head = done.slice(0, done.length - keepRecent)\n try {\n const result = await generate(model, {\n system: TRACE_SYSTEM,\n prompt: newestWithin(\n head.map((d, i) => `${i + 1}. ${d}`),\n opts.maxInputTokens ?? 1e9,\n ),\n maxOutputTokens: opts.summaryMaxTokens ?? 600,\n timeoutMs: opts.timeoutMs,\n abortSignal: opts.abortSignal,\n })\n opts.onUsage?.(normalizeUsage(result.usage))\n const clean = (result.text || '').trim()\n if (!clean) return done\n return [`Summary of ${head.length} earlier step(s): ${clean}`, ...done.slice(head.length)]\n } catch {\n return done\n }\n}\n\nexport { messageTokens as estimateMessagesTokens }\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAwC;;;ACAjD,SAAS,gBAA8B;;;ACuBvC,IAAM,cAAc;AACpB,IAAM,UAAU;AAGT,IAAM,cAAc,CAAC,MAAmC;AAC7D,MAAI,EAAE,UAAW,QAAO,EAAE;AAC1B,MAAI,OAAO,EAAE,SAAS,UAAU;AAC9B,UAAM,IAAI,YAAY,KAAK,EAAE,IAAI;AACjC,QAAI,IAAI,CAAC,EAAG,QAAO,EAAE,CAAC;AAAA,EACxB;AACA,QAAM,MAAM,EAAE,gBAAgB,MAAM,EAAE,KAAK,OAAO,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO;AACxF,MAAI,QAAQ,KAAK,GAAG,KAAK,EAAE,MAAM;AAC/B,UAAM,OAAO,EAAE,QAAQ,IAAI,IAAI,KAAK,UAAU,EAAE,UAAU,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY;AACxF,QAAI,QAAQ,MAAO,QAAO;AAC1B,QAAI,OAAO,CAAC,OAAO,OAAO,QAAQ,OAAO,MAAM,EAAE,SAAS,GAAG,GAAG;AAC9D,aAAO,SAAS,QAAQ,QAAQ,SAAS,GAAG;AAAA,IAC9C;AAAA,EACF;AACA,SAAO;AACT;AAEO,IAAM,iBAAiB,CAAC,MAA+B;AAC5D,QAAM,KAAK,YAAY,CAAC,KAAK;AAC7B,MAAI,GAAG,WAAW,QAAQ,EAAG,QAAO;AACpC,MAAI,OAAO,kBAAmB,QAAO;AACrC,SAAO;AACT;AAEA,IAAM,aAA6C;AAAA,EACjD,OAAO;AAAA,EACP,KAAK;AAAA,EACL,MAAM;AACR;AAEA,IAAM,YAA4C;AAAA,EAChD,OACE;AAAA,EACF,KAAK;AAAA,EACL,MAAM;AACR;AAGO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EA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