@dudko.dev/agent-web-ui 0.0.1 → 0.0.2
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 +66 -1
- package/dist/{chunk-4EHUITGU.js → chunk-SVYHDLAZ.js} +7 -1
- package/dist/{chunk-4EHUITGU.js.map → chunk-SVYHDLAZ.js.map} +1 -1
- package/dist/{chunk-A55Q377T.js → chunk-VCR7LU7J.js} +7 -1
- package/dist/{chunk-A55Q377T.js.map → chunk-VCR7LU7J.js.map} +1 -1
- package/dist/{chunk-P2F2P3JC.js → chunk-WFM6B7CL.js} +7 -1
- package/dist/{chunk-P2F2P3JC.js.map → chunk-WFM6B7CL.js.map} +1 -1
- package/dist/{chunk-TPK25QGK.js → chunk-WZ7K7JIP.js} +7 -1
- package/dist/{chunk-TPK25QGK.js.map → chunk-WZ7K7JIP.js.map} +1 -1
- package/dist/chunk-ZBHESK6V.js +1440 -0
- package/dist/chunk-ZBHESK6V.js.map +1 -0
- package/dist/controller.cjs +1891 -0
- package/dist/controller.cjs.map +1 -0
- package/dist/controller.d.cts +253 -0
- package/dist/controller.d.ts +253 -0
- package/dist/controller.js +482 -0
- package/dist/controller.js.map +1 -0
- package/dist/{en-CcNUz2tN.d.cts → en-Dg2MtzcJ.d.cts} +6 -0
- package/dist/{en-CcNUz2tN.d.ts → en-Dg2MtzcJ.d.ts} +6 -0
- package/dist/index.cjs +133 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +82 -4
- package/dist/index.d.ts +82 -4
- package/dist/index.js +142 -1419
- package/dist/index.js.map +1 -1
- package/dist/{labels-UuWI7wPo.d.ts → labels-CmiTBLWD.d.cts} +68 -100
- package/dist/{labels-D5BrHct4.d.cts → labels-DH1ESUtm.d.ts} +68 -100
- package/dist/locales/be.cjs +12 -0
- package/dist/locales/be.cjs.map +1 -1
- package/dist/locales/be.d.cts +4 -2
- package/dist/locales/be.d.ts +4 -2
- package/dist/locales/be.js +7 -1
- package/dist/locales/be.js.map +1 -1
- package/dist/locales/bg.cjs +12 -0
- package/dist/locales/bg.cjs.map +1 -1
- package/dist/locales/bg.d.cts +4 -2
- package/dist/locales/bg.d.ts +4 -2
- package/dist/locales/bg.js +7 -1
- package/dist/locales/bg.js.map +1 -1
- package/dist/locales/ca.cjs +12 -0
- package/dist/locales/ca.cjs.map +1 -1
- package/dist/locales/ca.d.cts +4 -2
- package/dist/locales/ca.d.ts +4 -2
- package/dist/locales/ca.js +7 -1
- package/dist/locales/ca.js.map +1 -1
- package/dist/locales/cs.cjs +12 -0
- package/dist/locales/cs.cjs.map +1 -1
- package/dist/locales/cs.d.cts +4 -2
- package/dist/locales/cs.d.ts +4 -2
- package/dist/locales/cs.js +7 -1
- package/dist/locales/cs.js.map +1 -1
- package/dist/locales/da.cjs +12 -0
- package/dist/locales/da.cjs.map +1 -1
- package/dist/locales/da.d.cts +4 -2
- package/dist/locales/da.d.ts +4 -2
- package/dist/locales/da.js +7 -1
- package/dist/locales/da.js.map +1 -1
- package/dist/locales/de.cjs +12 -0
- package/dist/locales/de.cjs.map +1 -1
- package/dist/locales/de.d.cts +4 -2
- package/dist/locales/de.d.ts +4 -2
- package/dist/locales/de.js +7 -1
- package/dist/locales/de.js.map +1 -1
- package/dist/locales/el.cjs +12 -0
- package/dist/locales/el.cjs.map +1 -1
- package/dist/locales/el.d.cts +4 -2
- package/dist/locales/el.d.ts +4 -2
- package/dist/locales/el.js +7 -1
- package/dist/locales/el.js.map +1 -1
- package/dist/locales/en.cjs +12 -0
- package/dist/locales/en.cjs.map +1 -1
- package/dist/locales/en.d.cts +4 -2
- package/dist/locales/en.d.ts +4 -2
- package/dist/locales/en.js +7 -1
- package/dist/locales/en.js.map +1 -1
- package/dist/locales/es-419.cjs +16 -1
- package/dist/locales/es-419.cjs.map +1 -1
- package/dist/locales/es-419.d.cts +4 -2
- package/dist/locales/es-419.d.ts +4 -2
- package/dist/locales/es-419.js +6 -3
- package/dist/locales/es-419.js.map +1 -1
- package/dist/locales/es.cjs +12 -0
- package/dist/locales/es.cjs.map +1 -1
- package/dist/locales/es.d.cts +4 -2
- package/dist/locales/es.d.ts +4 -2
- package/dist/locales/es.js +2 -2
- package/dist/locales/fi.cjs +12 -0
- package/dist/locales/fi.cjs.map +1 -1
- package/dist/locales/fi.d.cts +4 -2
- package/dist/locales/fi.d.ts +4 -2
- package/dist/locales/fi.js +7 -1
- package/dist/locales/fi.js.map +1 -1
- package/dist/locales/fr-CA.cjs +12 -0
- package/dist/locales/fr-CA.cjs.map +1 -1
- package/dist/locales/fr-CA.d.cts +4 -2
- package/dist/locales/fr-CA.d.ts +4 -2
- package/dist/locales/fr-CA.js +2 -2
- package/dist/locales/fr.cjs +12 -0
- package/dist/locales/fr.cjs.map +1 -1
- package/dist/locales/fr.d.cts +4 -2
- package/dist/locales/fr.d.ts +4 -2
- package/dist/locales/fr.js +2 -2
- package/dist/locales/gn.cjs +12 -0
- package/dist/locales/gn.cjs.map +1 -1
- package/dist/locales/gn.d.cts +4 -2
- package/dist/locales/gn.d.ts +4 -2
- package/dist/locales/gn.js +7 -1
- package/dist/locales/gn.js.map +1 -1
- package/dist/locales/hr.cjs +12 -0
- package/dist/locales/hr.cjs.map +1 -1
- package/dist/locales/hr.d.cts +4 -2
- package/dist/locales/hr.d.ts +4 -2
- package/dist/locales/hr.js +7 -1
- package/dist/locales/hr.js.map +1 -1
- package/dist/locales/ht.cjs +12 -0
- package/dist/locales/ht.cjs.map +1 -1
- package/dist/locales/ht.d.cts +4 -2
- package/dist/locales/ht.d.ts +4 -2
- package/dist/locales/ht.js +7 -1
- package/dist/locales/ht.js.map +1 -1
- package/dist/locales/hu.cjs +12 -0
- package/dist/locales/hu.cjs.map +1 -1
- package/dist/locales/hu.d.cts +4 -2
- package/dist/locales/hu.d.ts +4 -2
- package/dist/locales/hu.js +7 -1
- package/dist/locales/hu.js.map +1 -1
- package/dist/locales/index.cjs +6 -0
- package/dist/locales/index.cjs.map +1 -1
- package/dist/locales/index.d.cts +6 -4
- package/dist/locales/index.d.ts +6 -4
- package/dist/locales/index.js +1 -1
- package/dist/locales/it.cjs +12 -0
- package/dist/locales/it.cjs.map +1 -1
- package/dist/locales/it.d.cts +4 -2
- package/dist/locales/it.d.ts +4 -2
- package/dist/locales/it.js +7 -1
- package/dist/locales/it.js.map +1 -1
- package/dist/locales/nb.cjs +12 -0
- package/dist/locales/nb.cjs.map +1 -1
- package/dist/locales/nb.d.cts +4 -2
- package/dist/locales/nb.d.ts +4 -2
- package/dist/locales/nb.js +7 -1
- package/dist/locales/nb.js.map +1 -1
- package/dist/locales/nl.cjs +12 -0
- package/dist/locales/nl.cjs.map +1 -1
- package/dist/locales/nl.d.cts +4 -2
- package/dist/locales/nl.d.ts +4 -2
- package/dist/locales/nl.js +7 -1
- package/dist/locales/nl.js.map +1 -1
- package/dist/locales/pl.cjs +12 -0
- package/dist/locales/pl.cjs.map +1 -1
- package/dist/locales/pl.d.cts +4 -2
- package/dist/locales/pl.d.ts +4 -2
- package/dist/locales/pl.js +7 -1
- package/dist/locales/pl.js.map +1 -1
- package/dist/locales/pt-BR.cjs +12 -0
- package/dist/locales/pt-BR.cjs.map +1 -1
- package/dist/locales/pt-BR.d.cts +4 -2
- package/dist/locales/pt-BR.d.ts +4 -2
- package/dist/locales/pt-BR.js +7 -1
- package/dist/locales/pt-BR.js.map +1 -1
- package/dist/locales/pt.cjs +12 -0
- package/dist/locales/pt.cjs.map +1 -1
- package/dist/locales/pt.d.cts +4 -2
- package/dist/locales/pt.d.ts +4 -2
- package/dist/locales/pt.js +7 -1
- package/dist/locales/pt.js.map +1 -1
- package/dist/locales/qu.cjs +12 -0
- package/dist/locales/qu.cjs.map +1 -1
- package/dist/locales/qu.d.cts +4 -2
- package/dist/locales/qu.d.ts +4 -2
- package/dist/locales/qu.js +7 -1
- package/dist/locales/qu.js.map +1 -1
- package/dist/locales/ro.cjs +12 -0
- package/dist/locales/ro.cjs.map +1 -1
- package/dist/locales/ro.d.cts +4 -2
- package/dist/locales/ro.d.ts +4 -2
- package/dist/locales/ro.js +7 -1
- package/dist/locales/ro.js.map +1 -1
- package/dist/locales/ru.cjs +12 -0
- package/dist/locales/ru.cjs.map +1 -1
- package/dist/locales/ru.d.cts +4 -2
- package/dist/locales/ru.d.ts +4 -2
- package/dist/locales/ru.js +7 -1
- package/dist/locales/ru.js.map +1 -1
- package/dist/locales/sk.cjs +12 -0
- package/dist/locales/sk.cjs.map +1 -1
- package/dist/locales/sk.d.cts +4 -2
- package/dist/locales/sk.d.ts +4 -2
- package/dist/locales/sk.js +7 -1
- package/dist/locales/sk.js.map +1 -1
- package/dist/locales/sq.cjs +12 -0
- package/dist/locales/sq.cjs.map +1 -1
- package/dist/locales/sq.d.cts +4 -2
- package/dist/locales/sq.d.ts +4 -2
- package/dist/locales/sq.js +7 -1
- package/dist/locales/sq.js.map +1 -1
- package/dist/locales/sr-Latn.cjs +12 -0
- package/dist/locales/sr-Latn.cjs.map +1 -1
- package/dist/locales/sr-Latn.d.cts +4 -2
- package/dist/locales/sr-Latn.d.ts +4 -2
- package/dist/locales/sr-Latn.js +2 -2
- package/dist/locales/sr.cjs +12 -0
- package/dist/locales/sr.cjs.map +1 -1
- package/dist/locales/sr.d.cts +4 -2
- package/dist/locales/sr.d.ts +4 -2
- package/dist/locales/sr.js +2 -2
- package/dist/locales/sv.cjs +12 -0
- package/dist/locales/sv.cjs.map +1 -1
- package/dist/locales/sv.d.cts +4 -2
- package/dist/locales/sv.d.ts +4 -2
- package/dist/locales/sv.js +7 -1
- package/dist/locales/sv.js.map +1 -1
- package/dist/locales/tr.cjs +12 -0
- package/dist/locales/tr.cjs.map +1 -1
- package/dist/locales/tr.d.cts +4 -2
- package/dist/locales/tr.d.ts +4 -2
- package/dist/locales/tr.js +7 -1
- package/dist/locales/tr.js.map +1 -1
- package/dist/locales/uk.cjs +12 -0
- package/dist/locales/uk.cjs.map +1 -1
- package/dist/locales/uk.d.cts +4 -2
- package/dist/locales/uk.d.ts +4 -2
- package/dist/locales/uk.js +7 -1
- package/dist/locales/uk.js.map +1 -1
- package/dist/mcp-app.d.cts +491 -3
- package/dist/mcp-app.d.ts +491 -3
- package/dist/questions-Dw--IEjT.d.cts +100 -0
- package/dist/questions-Dw--IEjT.d.ts +100 -0
- package/dist/{types-BmvgYUzF.d.cts → types-CQquuZpl.d.cts} +1 -1
- package/dist/{types-Cr5gmUts.d.ts → types-CXZfZVP5.d.ts} +1 -1
- package/dist/{mcp-app-entry-BA-Ca39z.d.ts → types-DnBCok3z.d.cts} +2 -488
- package/dist/{mcp-app-entry-tybABaHg.d.cts → types-DnBCok3z.d.ts} +2 -488
- package/package.json +13 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/state.ts","../src/questions.ts","../src/composer.ts","../src/labels.ts","../src/follow-scroll.ts","../src/file-kinds.ts","../src/image-resize.ts","../src/format.ts","../src/approval-queue.ts","../src/elicitation.ts","../src/prompt-arming.ts","../src/chat-history.ts","../src/util.ts","../src/voice/record.ts","../src/voice/recognizer.ts","../src/voice/speak.ts"],"sourcesContent":["import {\n isReplayedToolOutput,\n type AgentEvent,\n type IUsage,\n type Skill,\n} from '@dudko.dev/agent-web'\nimport type {\n AppView,\n WrittenFileView,\n AgentUiState,\n ApprovalView,\n ElicitationView,\n QuestionView,\n ChatAttachment,\n ChatMessage,\n DecisionView,\n LessonView,\n MediaView,\n QueuedMessageView,\n RemoteRunView,\n StepView,\n SubagentNode,\n SubagentView,\n ToolCallView,\n TranscriptView,\n} from './types.js'\nimport { withoutOwnWords } from './questions.js'\n\n/**\n * The reducer that turns the agent's `AgentEvent` stream into a renderable\n * {@link AgentUiState}. It is a pure function of (state, action) with no React,\n * no clock and no randomness (ids come from a monotonic `seq`; times come in on\n * the action as `at`), so it can be unit-tested in isolation and reused to\n * build a fully custom UI.\n */\nexport type AgentAction =\n /** Clear the whole conversation (transcript + current run), keeping status. */\n | { type: 'reset' }\n /** Set the lifecycle status (owned by the hook). */\n | { type: 'status'; status: AgentUiState['status']; error?: string }\n /**\n * Fold one streamed agent event into the view. `at` (ms epoch, from the\n * hook) times runs and tool calls; `attachments` decorate the user turn a\n * `run.start` opens.\n */\n | {\n type: 'event'\n event: AgentEvent\n maxEvents?: number\n at?: number\n attachments?: ChatAttachment[]\n /** The event is another tab's run of this conversation (`watchSession`), relayed here. */\n remote?: boolean\n /** With `session.busy`: the goal that waits (shown as queued until the run starts). */\n goal?: string\n }\n /**\n * Another tab's run of this conversation, as `watchSession` reports it (or `undefined`: none\n * in view). Ended `gone` - that tab closed before it said so - finishes the answer it left.\n */\n | { type: 'remote'; remote: RemoteRunView | undefined }\n /**\n * The agent's notebook as it is now (the hook sends it when the agent is built: lessons a\n * persistent store brought back). Later `skill.learned` / `skill.forgotten` events keep it current.\n */\n | { type: 'notebook'; lessons: LessonView[] }\n /** Replace the transcript with a saved conversation (chat history). */\n | { type: 'load'; messages: ChatMessage[]; totalUsage?: IUsage }\n /**\n * The run is over and these messages never reached the model (`RunResult.undelivered`,\n * or what was still queued when it was stopped). Clears the queue. An empty list\n * clears `undelivered` too (the follow-up was sent, or the user discarded them).\n */\n | { type: 'undelivered'; texts: string[]; keepQueued?: boolean }\n /**\n * `sendRemote`: the text went to the conversation's run in another tab, which has not answered\n * yet - shown in `queued`, marked `sentTo: 'another-tab'`, until `remote-answer` with this `id`\n * (or that run's own `message.queued` for it, which takes its place).\n */\n | { type: 'remote-send'; id: string; text: string }\n /**\n * That tab's answer to `remote-send` `id`: `taken` (its run has it), `refused` (refused, or its\n * run ended without taking it - the text comes back in `undelivered`, to send again or drop), or\n * `unknown` (the watch that sent it was closed - another conversation is in view: nothing is\n * offered, as that tab may still take it). Either way the waiting entry goes.\n */\n | { type: 'remote-answer'; id: string; text: string; answer: 'taken' | 'refused' | 'unknown' }\n /**\n * The user sent a goal and this tab's run is getting going: its turn is shown at once (a\n * user message and a pending answer), until the run's `run.start` takes its place.\n */\n | { type: 'submitted'; goal: string; attachments?: ChatAttachment[] }\n\ninterface EventContext {\n at?: number\n attachments?: ChatAttachment[]\n remote?: boolean\n /** With `session.busy`: what the user sent, waiting with the run. */\n goal?: string\n}\n\n/** ≈ tokens of a value as the model sees it (chars / 4). */\nconst approxTokens = (value: unknown): number => {\n if (value === undefined) return 0\n let text: string\n try {\n text = typeof value === 'string' ? value : (JSON.stringify(value) ?? '')\n } catch {\n text = String(value)\n }\n return Math.ceil(text.length / 4)\n}\n\nconst emptyUsage = (): IUsage => ({\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n reasoningTokens: 0,\n cachedInputTokens: 0,\n cacheWriteTokens: 0,\n})\n\n// What a usage record counts besides tokens: calls to the media models and to the decision\n// model. Absent until there is one, so a run without them keeps the six-field shape.\nconst USAGE_COUNTS = [\n 'mediaCalls',\n 'imagesGenerated',\n 'speechCharacters',\n 'transcriptionSeconds',\n 'decisionCalls',\n] as const\n\nconst addUsage = (a: IUsage, b: IUsage): IUsage => {\n const sum: IUsage = {\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),\n cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),\n cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0),\n }\n for (const key of USAGE_COUNTS) {\n const n = (a[key] ?? 0) + (b[key] ?? 0)\n if (n) sum[key] = n\n }\n return sum\n}\n\n/**\n * The notebook view of the agent's own skills (`agent.listLearnedSkills()`): what the core stored\n * about each lesson, in the shape the UI keeps current from `skill.learned` events.\n */\nexport const lessonsOf = (skills: Skill[]): LessonView[] =>\n skills\n .filter((s) => s.origin?.kind === 'learned')\n .map((s) => ({\n name: s.name,\n description: s.description,\n revision: s.origin?.revision ?? 1,\n chars: s.content.length,\n sources: [...(s.origin?.sources ?? []), ...(s.origin?.fetched ?? [])],\n }))\n\n/** A fresh, empty view. */\nexport const createInitialAgentState = (): AgentUiState => ({\n status: 'idle',\n goal: undefined,\n plan: undefined,\n planThought: '',\n steps: [],\n finalText: '',\n finalReasoning: '',\n totalUsage: emptyUsage(),\n runStartedAt: undefined,\n runMessageId: undefined,\n approvals: [],\n subagents: [],\n queued: [],\n notes: [],\n undelivered: [],\n skills: [],\n learned: [],\n learnedNow: [],\n fetches: [],\n discoveredTools: [],\n compactions: [],\n budget: undefined,\n usage: emptyUsage(),\n modelLoad: undefined,\n replan: undefined,\n error: undefined,\n stopped: false,\n messages: [],\n events: [],\n seq: 0,\n})\n\n/** Clear only the per-run view; keep the transcript, totals, status and seq counter. */\n/** The core's sentinel for a step the executor could not complete (its `BLOCKER`). */\nconst BLOCKER_MARK = '[BLOCKER]'\n\nconst resetRun = (state: AgentUiState): AgentUiState => ({\n ...createInitialAgentState(),\n status: state.status,\n messages: state.messages,\n totalUsage: state.totalUsage,\n seq: state.seq,\n learned: state.learned,\n // An MCP App's request is the user's, not the run's: it waits across runs.\n approvals: state.approvals.filter((a) => a.app && a.status === 'pending'),\n // So is what this tab sent to another tab's run, until that tab answers (a replay that opens\n // with the run's start is not an answer).\n queued: sentToOtherTab(state.queued),\n})\n\n/** The entries of what this tab sent to another tab's run and is still waiting on. */\nconst sentToOtherTab = (queued: QueuedMessageView[]): QueuedMessageView[] =>\n queued.filter((q) => q.sentTo === 'another-tab')\n\n/**\n * The entry of what this tab sent to another tab's run that a `message.queued` of that run is\n * (the oldest waiting one with the same text), or -1. By TEXT, because nothing else is shared:\n * the run there numbers its messages itself (`msg-<n>`) and the request id of `watchSession`\n * never reaches an event. Its own text, trimmed as here, or a copy the relay clipped (ending in\n * `…`, a prefix of this one). The order holds: that tab takes one tab's messages in the order\n * they were sent. A third tab sending the same words at once could be taken for this one - the\n * view only: what this tab offers back (`undelivered`) follows its own answer, never this match.\n */\nconst sentEntryOf = (queued: QueuedMessageView[], text: string): number =>\n queued.findIndex(\n (q) =>\n q.sentTo === 'another-tab' &&\n (q.text === text ||\n (text.endsWith('…') &&\n q.text.length > text.length &&\n q.text.startsWith(text.slice(0, -1)))),\n )\n\n/** Apply `fn` to the step whose id matches, leaving the rest untouched. */\nconst patchStep = (steps: StepView[], id: string, fn: (s: StepView) => StepView): StepView[] =>\n steps.map((s) => (s.id === id ? fn(s) : s))\n\n/**\n * A decided request about an MCP server's skill keeps who and what - not the server's text: the\n * preview was for the decision, and a saved conversation must not hold a server's instructions.\n */\nconst withoutSkillBody = (a: ApprovalView): ApprovalView => {\n if (!a.skill || a.skill.body === undefined) return a\n const { body: _body, ...skill } = a.skill\n return { ...a, skill }\n}\n\nconst patchApproval = (\n approvals: ApprovalView[],\n id: string,\n fn: (a: ApprovalView) => ApprovalView,\n): ApprovalView[] => approvals.map((a) => (a.id === id ? fn(a) : a))\n\nconst STATUS_OF_ACTION = {\n accept: 'accepted',\n decline: 'declined',\n cancel: 'cancelled',\n} as const\n\n/** A server's question (MCP elicitation) joins the run's view, once. */\nconst addElicitation = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'mcp.elicitation-requested' }>,\n extra: Pick<ElicitationView, 'stepId' | 'subagent' | 'remote'>,\n): AgentUiState =>\n state.elicitations?.some((e) => e.id === event.id)\n ? state\n : {\n ...state,\n elicitations: [\n ...(state.elicitations ?? []),\n {\n id: event.id,\n server: event.server,\n tool: event.tool,\n mode: event.mode,\n message: event.message,\n ...(event.requestedSchema ? { requestedSchema: event.requestedSchema } : {}),\n ...(event.url ? { url: event.url } : {}),\n ...(extra.stepId ? { stepId: extra.stepId } : {}),\n ...(extra.subagent ? { subagent: extra.subagent } : {}),\n ...(extra.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n\n/** The question was answered; one that was refused before it could be shown is recorded too. */\nconst answerElicitation = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'mcp.elicitation-answered' }>,\n stepId: string | undefined,\n): AgentUiState => {\n const answered = (e: ElicitationView): ElicitationView => ({\n ...e,\n status: STATUS_OF_ACTION[event.action],\n automatic: event.automatic,\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.fields ? { fields: event.fields } : {}),\n })\n const list = state.elicitations ?? []\n return {\n ...state,\n elicitations: list.some((e) => e.id === event.id)\n ? list.map((e) => (e.id === event.id ? answered(e) : e))\n : [\n ...list,\n answered({\n id: event.id,\n server: event.server,\n tool: event.tool,\n message: '',\n ...(stepId ? { stepId } : {}),\n status: 'pending',\n }),\n ],\n }\n}\n\n/** A question the model put to the person (`ask_user`) joins the run's view, once. */\nconst addQuestion = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'user.question-asked' }>,\n extra: Pick<QuestionView, 'stepId' | 'subagent' | 'remote'>,\n): AgentUiState =>\n state.questions?.some((q) => q.id === event.id)\n ? state\n : {\n ...state,\n questions: [\n ...(state.questions ?? []),\n {\n id: event.id,\n question: event.question,\n options: event.options.map((o) => ({ ...o })),\n multiple: event.multiple,\n allowOther: event.allowOther,\n ...(extra.stepId ? { stepId: extra.stepId } : {}),\n ...(extra.subagent ? { subagent: extra.subagent } : {}),\n ...(extra.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n\n/**\n * How the question ended. Only what the event says: the labels of a choice, never anything typed\n * (the core's event never carries it). An answer to a question this view never saw is not kept:\n * there is nothing to show of it.\n */\nconst answerQuestion = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'user.question-answered' }>,\n): AgentUiState =>\n state.questions?.some((q) => q.id === event.id)\n ? {\n ...state,\n questions: state.questions.map((q) =>\n q.id === event.id\n ? {\n ...q,\n status: event.action,\n automatic: event.automatic,\n ...(event.action === 'choice' && event.choice ? { choice: [...event.choice] } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n }\n : q,\n ),\n }\n : state\n\nconst patchSubagent = (\n subagents: SubagentView[],\n id: string,\n fn: (s: SubagentView) => SubagentView,\n): SubagentView[] => subagents.map((s) => (s.id === id ? fn(s) : s))\n\n/** The step currently executing (the last one still running). */\nconst runningStepId = (steps: StepView[]): string | undefined =>\n [...steps].reverse().find((s) => s.status === 'running')?.id\n\n/** Fold one of a subagent's own events into its compact view. */\nconst applySubagentEvent = (view: SubagentView, event: AgentEvent): SubagentView => {\n switch (event.type) {\n case 'step.start':\n return {\n ...view,\n steps: view.steps + 1,\n activity: `step ${event.index}/${event.total}: ${event.step.description}`,\n // Known only when the child runs with model tiers.\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n }\n case 'step.escalated':\n return { ...view, tier: event.to, ...(event.model ? { model: event.model } : {}) }\n case 'step.tool-call':\n return { ...view, toolCalls: view.toolCalls + 1, activity: `→ ${event.name}` }\n case 'final.text-delta':\n return { ...view, text: view.text + event.delta, activity: 'writing the answer' }\n case 'final':\n return { ...view, text: event.text }\n case 'usage':\n return { ...view, usage: addUsage(view.usage, event.usage) }\n default:\n return view\n }\n}\n\n/** A subagent an event came through on its way up (a `subagent.event` envelope). */\ninterface Ancestor {\n id: string\n}\n\ntype SubagentStart = Extract<AgentEvent, { type: 'subagent.start' }>\n\n/**\n * The node `id`, created when it is not there yet. An event can arrive for a subagent whose\n * `subagent.start` was never seen (a capped log replayed, a host that joined late): it gets a\n * node from what the envelope says - its name, and where in the tree it is.\n */\nconst ensureSubagent = (\n state: AgentUiState,\n id: string,\n name: string,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n if (state.subagents.some((s) => s.id === id)) return state\n const parentId = ancestors[ancestors.length - 1]?.id\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id,\n name,\n task: '',\n ...(parentId ? { parentId } : {}),\n depth: ancestors.length + 1,\n status: 'running',\n ...(stepId ? { stepId } : {}),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** What a `subagent.start` says about its node (everything but the counters). */\nconst startSubagent = (\n state: AgentUiState,\n event: SubagentStart,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n // The envelopes around an event are its ancestry; a start that came bare says it itself\n // (`parentId` is then a subagent only below depth 1 - at depth 1 it is the run's id).\n const depth = Math.max(event.depth ?? 1, ancestors.length + 1)\n const parentId = ancestors[ancestors.length - 1]?.id ?? (depth > 1 ? event.parentId : undefined)\n const told = {\n name: event.name,\n task: event.task,\n depth,\n ...(parentId ? { parentId } : {}),\n ...(event.profile ? { profile: event.profile } : {}),\n ...(event.dynamic ? { dynamic: true as const } : {}),\n ...(event.role ? { role: event.role } : {}),\n ...(event.tools ? { tools: event.tools } : {}),\n }\n // Already there (its events arrived first): the start fills in what they could not say.\n if (state.subagents.some((s) => s.id === event.id)) {\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({ ...s, ...told })),\n }\n }\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n // A nested one belongs to the step that delegated its top-most ancestor.\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id: event.id,\n ...told,\n status: 'running',\n stepId,\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** How long a subagent ran, when both ends were stamped. */\nconst subagentDuration = (s: SubagentView, at?: number): Partial<SubagentView> =>\n at !== undefined && s.startedAt !== undefined ? { durationMs: Math.max(0, at - s.startedAt) } : {}\n\nconst addMedia = (state: AgentUiState, view: MediaView): AgentUiState => ({\n ...state,\n media: [...(state.media ?? []), view],\n ...(view.stepId\n ? {\n steps: patchStep(state.steps, view.stepId, (s) => ({\n ...s,\n media: [...(s.media ?? []), view],\n })),\n }\n : {}),\n})\n\nconst mediaOf = (\n event: Extract<AgentEvent, { type: 'media.generated' }>,\n withStep: boolean,\n): MediaView => ({\n kind: event.kind,\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n model: event.model,\n ...(event.references\n ? {\n references: {\n used: event.references.used === true,\n count: event.references.count,\n paths: [...event.references.paths],\n },\n }\n : {}),\n ...(withStep && event.step ? { stepId: event.step.id } : {}),\n})\n\ntype McpAppEvent = Extract<AgentEvent, { type: 'mcp.app' }>\n\n/**\n * An MCP App joins the run's view, once, and the tool call it came with is tagged. `by` is the\n * subagent the call came through (its step ids are its own: no step then).\n */\nconst addApp = (state: AgentUiState, event: McpAppEvent, by?: AppView['by']): AgentUiState => {\n if (state.apps?.some((a) => a.id === event.id)) return state\n const view: AppView = {\n id: event.id,\n server: event.server,\n tool: event.tool,\n toolName: event.toolName,\n resourceUri: event.resourceUri,\n input: event.input,\n ...(event.result ? { result: event.result } : {}),\n ...(!by && event.step ? { stepId: event.step.id } : {}),\n ...(by ? { by } : {}),\n }\n const steps =\n !by && event.step\n ? patchStep(state.steps, event.step.id, (s) => {\n // The event comes while its call is still running: the newest untagged call of it.\n let i = s.toolCalls.length - 1\n while (i >= 0 && !(s.toolCalls[i].name === event.tool && !s.toolCalls[i].app)) i -= 1\n if (i < 0) return s\n const toolCalls = s.toolCalls.slice()\n toolCalls[i] = { ...toolCalls[i], app: event.id }\n return { ...s, toolCalls }\n })\n : state.steps\n return { ...state, steps, apps: [...(state.apps ?? []), view] }\n}\n\ntype FileWritten = Extract<AgentEvent, { type: 'file.written' }>\n\n/**\n * A file the run wrote: one entry per path (a second write updates it in place), newest size\n * and type. `by` is the subagent it came through; its step ids are its own, so no step then.\n */\nconst fileWritten = (\n state: AgentUiState,\n event: FileWritten,\n by?: WrittenFileView['by'],\n): AgentUiState => {\n const files = state.writtenFiles ?? []\n const i = files.findIndex((f) => f.path === event.path)\n const view: WrittenFileView = {\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n writes: (i >= 0 ? files[i].writes : 0) + 1,\n ...(!by && event.step ? { stepId: event.step.id } : {}),\n ...(by ? { by } : {}),\n }\n return {\n ...state,\n writtenFiles: i >= 0 ? files.map((f, k) => (k === i ? view : f)) : [...files, view],\n }\n}\n\n/** A file deleted later in the run is not one of its files any more. */\nconst fileDeleted = (state: AgentUiState, path: string): AgentUiState =>\n state.writtenFiles?.some((f) => f.path === path)\n ? { ...state, writtenFiles: state.writtenFiles.filter((f) => f.path !== path) }\n : state\n\nconst transcriptOf = (\n event: Extract<AgentEvent, { type: 'media.transcribed' }>,\n): TranscriptView => ({\n source: event.source,\n name: event.name,\n text: event.text,\n ...(event.language ? { language: event.language } : {}),\n ...(event.durationInSeconds !== undefined ? { durationInSeconds: event.durationInSeconds } : {}),\n model: event.model,\n})\n\n/**\n * Fold a `subagent.*` event into the tree. `ancestors` are the subagents it came up through\n * (outermost first): a subagent's own subagents arrive nested,\n * `subagent.event{ A, subagent.event{ G, event } }`, and each level lands on its own node.\n */\nconst applySubagent = (\n state: AgentUiState,\n event: Extract<\n AgentEvent,\n { type: 'subagent.start' | 'subagent.event' | 'subagent.complete' | 'subagent.error' }\n >,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n switch (event.type) {\n case 'subagent.start':\n return startSubagent(state, event, ancestors, ctx)\n\n case 'subagent.event': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n const inner = event.event\n switch (inner.type) {\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(known, inner, [...ancestors, { id: event.id }], ctx)\n\n // A helper the model started asks through the run's own consent gate (the event says\n // which helper): its request is the user's to answer, like the run's. A subagent with\n // a gate of its own (no `subagent` on the event) is its host's business.\n case 'tool.approval-requested': {\n if (!inner.subagent || known.approvals.some((a) => a.id === inner.id)) return known\n const node = known.subagents.find((s) => s.id === inner.subagent!.id)\n return {\n ...known,\n approvals: [\n ...known.approvals,\n {\n id: inner.id,\n name: inner.name,\n input: inner.input,\n readOnly: inner.readOnly,\n // The helper's own step ids mean nothing here: the step that delegated it does.\n stepId: node?.stepId,\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n ...(inner.skill ? { skill: inner.skill } : {}),\n ...(inner.rule ? { rule: inner.rule } : {}),\n ...(ctx.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n }\n case 'tool.approval-resolved':\n return known.approvals.some((a) => a.id === inner.id)\n ? {\n ...known,\n approvals: patchApproval(known.approvals, inner.id, (a) =>\n withoutSkillBody({\n ...a,\n status: inner.approved ? 'approved' : 'denied',\n reason: inner.reason,\n automatic: inner.automatic,\n }),\n ),\n }\n : known\n\n // A server asks the user during a subagent's tool call (the connection lets helpers\n // ask): the question is the user's to answer, like the run's own.\n case 'mcp.elicitation-requested': {\n const node = inner.subagent\n ? known.subagents.find((s) => s.id === inner.subagent!.id)\n : undefined\n return addElicitation(known, inner, {\n ...(ctx.remote ? { remote: true as const } : {}),\n // The subagent's own step ids mean nothing here: the step that delegated it does.\n stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,\n ...(inner.subagent\n ? {\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n }\n : {}),\n })\n }\n case 'mcp.elicitation-answered':\n return answerElicitation(\n known,\n inner,\n known.subagents.find((s) => s.id === event.id)?.stepId,\n )\n\n // A helper (or a subagent the host defined) asks the person through the run's handler:\n // the question is the person's to answer, like the run's own, marked with who asks.\n case 'user.question-asked': {\n const asker = inner.subagent ?? { id: event.id, depth: ancestors.length + 1 }\n const node = known.subagents.find((s) => s.id === asker.id)\n return addQuestion(known, inner, {\n ...(ctx.remote ? { remote: true as const } : {}),\n // The helper's own step ids mean nothing here: the step that delegated it does.\n stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,\n subagent: {\n id: asker.id,\n depth: asker.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n })\n }\n case 'user.question-answered':\n return answerQuestion(known, inner)\n\n // What a subagent generated is in the same workspace: it shows in the turn (its step\n // ids are its own, so it is tied to no step here).\n case 'media.generated':\n return addMedia(known, mediaOf(inner, false))\n case 'media.transcribed':\n return { ...known, transcripts: [...(known.transcripts ?? []), transcriptOf(inner)] }\n\n // A subagent works in the same workspace: what it wrote belongs to the turn, and says\n // who wrote it.\n case 'file.written': {\n const node = known.subagents.find((s) => s.id === event.id)\n return fileWritten(known, inner, {\n id: event.id,\n name: node?.name ?? event.name,\n ...(node?.role ? { role: node.role } : {}),\n })\n }\n case 'file.deleted':\n return fileDeleted(known, inner.path)\n // An app a subagent's call came with is shown in the turn too, and says whose call it was.\n case 'mcp.app': {\n // Another tab's app is that tab's: a frame here would run it a second time.\n if (ctx.remote) return known\n const node = known.subagents.find((s) => s.id === event.id)\n return addApp(known, inner, {\n id: event.id,\n name: node?.name ?? event.name,\n ...(node?.role ? { role: node.role } : {}),\n })\n }\n\n default:\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) =>\n applySubagentEvent(s, inner),\n ),\n }\n }\n }\n\n case 'subagent.complete': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: 'done',\n activity: 'done',\n text: event.text,\n usage: event.usage,\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n\n case 'subagent.error': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: event.stopped ? 'stopped' : 'error',\n activity: event.stopped ? 'stopped' : 'failed',\n error: event.error,\n // A helper says what it had spent when it ended; a static subagent does not.\n ...(event.usage ? { usage: event.usage } : {}),\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n }\n}\n\n/**\n * The flat `subagents` list as a tree: each node with the subagents it started, in the order\n * they started. A node whose parent is not in the list (its start was never seen) is a root.\n */\nexport const subagentTree = (subagents: SubagentView[]): SubagentNode[] => {\n const nodes = new Map<string, SubagentNode>()\n for (const s of subagents) nodes.set(s.id, { ...s, children: [] })\n // A parent chain that comes back to the node is not a tree: such a node is a root.\n const loops = (node: SubagentNode): boolean => {\n let up = node.parentId\n for (let i = 0; up !== undefined && i <= nodes.size; i++) {\n if (up === node.id) return true\n up = nodes.get(up)?.parentId\n }\n return false\n }\n const roots: SubagentNode[] = []\n for (const node of nodes.values()) {\n const parent =\n node.parentId !== undefined && !loops(node) ? nodes.get(node.parentId) : undefined\n if (parent) parent.children.push(node)\n else roots.push(node)\n }\n return roots\n}\n\n/** Finalize the trailing pending assistant message with the given content. */\nconst finalizeAssistant = (\n messages: ChatMessage[],\n content: string,\n extra: Partial<ChatMessage> = {},\n): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content: content || m.content, pending: false, ...extra }\n return next\n }\n }\n return messages\n}\n\n/** Duration of the current run at `at`, when both ends are known. */\nconst runDuration = (state: AgentUiState, at?: number): Partial<ChatMessage> =>\n at !== undefined && state.runStartedAt !== undefined\n ? { durationMs: Math.max(0, at - state.runStartedAt) }\n : {}\n\n/** Update the trailing pending assistant message's streaming content. */\nconst streamAssistant = (messages: ChatMessage[], content: string): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content }\n return next\n }\n }\n return messages\n}\n\n/** The queue entry of a goal that waits for the session (`session.busy`). */\nconst WAITING_ID = 'waiting-for-session'\n\n/** The state without a wait for the session (the run got it, or will not wait any more). */\nconst withoutBusy = (state: AgentUiState): AgentUiState => {\n if (!state.sessionBusy) return state\n const { sessionBusy: _over, ...rest } = state\n void _over\n return { ...rest, queued: rest.queued.filter((q) => q.id !== WAITING_ID) }\n}\n\n/** The state without the turn shown at submit (`submitted`): the run's own turn replaces it. */\nconst withoutSubmitted = (state: AgentUiState): AgentUiState => {\n if (!state.submitted) return state\n const { submitted, ...rest } = state\n const ids = new Set([submitted.userId, submitted.assistantId])\n return { ...rest, messages: rest.messages.filter((m) => !ids.has(m.id)) }\n}\n\n/** Keep the turn shown at submit, as the run's (it ended before its `run.start`, with an error). */\nconst keepSubmitted = (state: AgentUiState): AgentUiState => {\n if (!state.submitted) return state\n const { submitted: _kept, ...rest } = state\n void _kept\n return rest\n}\n\nconst applyEvent = (state: AgentUiState, event: AgentEvent, ctx: EventContext): AgentUiState => {\n switch (event.type) {\n case 'run.start': {\n // Start a new run: clear the previous run's view but keep the transcript,\n // then push the user turn and a pending assistant turn to stream into (in place of the\n // turn shown when it was sent).\n const base = resetRun(ctx.remote ? state : withoutSubmitted(state))\n const userId = `msg-${base.seq}`\n const assistantId = `msg-${base.seq + 1}`\n // When the turn began: what places it among another tab's turns when both save the chat.\n const began = ctx.at !== undefined ? { startedAt: ctx.at } : {}\n return {\n ...base,\n // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).\n ...(ctx.remote && state.remote ? { remote: state.remote } : {}),\n // ...and this tab's sent turn, still waiting for its own run.start (or a session.busy).\n ...(ctx.remote && state.submitted ? { submitted: state.submitted } : {}),\n goal: event.goal,\n runStartedAt: ctx.at,\n runMessageId: assistantId,\n messages: [\n ...base.messages,\n {\n id: userId,\n role: 'user',\n content: event.goal,\n pending: false,\n ...(ctx.remote ? { remote: true as const } : {}),\n ...began,\n ...(ctx.attachments?.length ? { attachments: ctx.attachments } : {}),\n },\n {\n id: assistantId,\n role: 'assistant',\n content: '',\n pending: true,\n ...(ctx.remote ? { remote: true as const } : {}),\n ...began,\n },\n ],\n seq: base.seq + 2,\n }\n }\n\n case 'model.load':\n return { ...state, modelLoad: { progress: event.progress, text: event.text } }\n\n case 'plan.thought-delta':\n return { ...state, planThought: state.planThought + event.delta }\n\n case 'plan.created':\n return {\n ...state,\n plan: event.plan,\n planThought: state.planThought || event.plan.thought,\n }\n\n case 'plan.revised':\n return {\n ...state,\n plan: event.plan,\n // `replan.decision` came first: keep its \"because the user spoke\" flag.\n replan: {\n mode: 'revise',\n reason: event.reason,\n ...(state.replan?.byUser ? { byUser: true } : {}),\n },\n }\n\n case 'plan.step-added':\n // Execution is tracked from step.* events; the plan itself already\n // arrived via plan.created. Nothing to fold here.\n return state\n\n case 'step.start': {\n const view: StepView = {\n id: event.step.id,\n index: event.index,\n total: event.total,\n step: event.step,\n text: '',\n reasoning: '',\n toolCalls: [],\n status: 'running',\n blocked: false,\n // Only with `config.executorTiers`: without it the view is what it always was.\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tierReason !== undefined ? { tierReason: event.tierReason } : {}),\n }\n // `total` is the plan's length as this step starts - a replan may have grown or cut it\n // since the earlier steps started: they show the same, so the rows read 1/2, 2/2, not\n // 1/1, 2/2.\n const steps = state.steps.map((s) =>\n s.total === event.total ? s : { ...s, total: event.total },\n )\n return { ...state, steps: [...steps, view] }\n }\n\n case 'step.escalated':\n // The attempt on `from` is over and the step CONTINUES on `to`. What the failed attempt\n // wrote is not the next attempt's text: it moves onto the escalation. Its tool calls\n // happened (the core keeps them in the step's result and shows them to the stronger\n // model), so they stay, marked with the attempt they belong to.\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n const attempt = (s.escalations?.length ?? 0) + 1\n return {\n ...s,\n tier: event.to,\n ...(event.model ? { model: event.model } : {}),\n text: '',\n reasoning: '',\n toolCalls: s.toolCalls.map((c) => (c.attempt === undefined ? { ...c, attempt } : c)),\n escalations: [\n ...(s.escalations ?? []),\n {\n from: event.from,\n to: event.to,\n reason: event.reason,\n ...(event.model ? { model: event.model } : {}),\n ...(s.text.trim() ? { text: s.text } : {}),\n },\n ],\n }\n }),\n }\n\n case 'step.reasoning-delta':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n reasoning: s.reasoning + event.delta,\n })),\n }\n\n case 'step.text-delta':\n return {\n ...state,\n // \"[BLOCKER]\" is the executor's signal to the core that a step cannot be completed (the\n // core strips it from the step's summary): never a word for the user. Stripped from the\n // text as it accumulates, so a marker split across two deltas goes too.\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n text: (s.text + event.delta).split(BLOCKER_MARK).join(''),\n })),\n }\n\n case 'step.tool-call': {\n // An app can be told before its call is (the tool runs while the stream is read): the\n // call then takes the app of this step and tool that no call has yet.\n const tagged = new Set(\n state.steps.flatMap((s) => s.toolCalls.map((c) => c.app).filter(Boolean)),\n )\n const early = state.apps?.find(\n (a) => a.stepId === event.step.id && a.tool === event.name && !tagged.has(a.id),\n )\n const call: ToolCallView = {\n name: event.name,\n input: event.input,\n status: 'calling',\n inputTokens: approxTokens(event.input),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n ...(early ? { app: early.id } : {}),\n }\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n toolCalls: [...s.toolCalls, call],\n })),\n }\n }\n\n case 'step.tool-result':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n // Match the last still-calling entry for this tool name.\n let done = false\n const toolCalls = s.toolCalls\n .slice()\n .reverse()\n .map((c) => {\n if (!done && c.status === 'calling' && c.name === event.name) {\n done = true\n return {\n ...c,\n output: event.output,\n ok: event.ok,\n status: 'done' as const,\n outputTokens: approxTokens(event.output),\n ...(isReplayedToolOutput(event.output) ? { replayed: true } : {}),\n ...(ctx.at !== undefined && c.startedAt !== undefined\n ? { durationMs: Math.max(0, ctx.at - c.startedAt) }\n : {}),\n }\n }\n return c\n })\n .reverse()\n return { ...s, toolCalls }\n }),\n }\n\n case 'step.complete':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n status: 'done',\n summary: event.result.summary,\n // With tiers: where the step finished and how it got there. The result's list is the\n // authority; an escalation seen live keeps what only the event told (model, text).\n ...(event.result.tier !== undefined ? { tier: event.result.tier } : {}),\n ...(event.result.model !== undefined ? { model: event.result.model } : {}),\n ...(event.result.escalations?.length\n ? {\n escalations: event.result.escalations.map((e, i) => {\n const live = s.escalations?.[i]\n return live && live.from === e.from && live.to === e.to\n ? { ...live, reason: e.reason }\n : { from: e.from, to: e.to, reason: e.reason }\n }),\n }\n : {}),\n blocked: event.result.blocked,\n // The result carries the authoritative, ordered tool-call list; keep\n // the timing the streamed calls measured (matched in order per name).\n toolCalls: (() => {\n const seen = new Map<string, number>()\n return event.result.toolCalls.map((c) => {\n const nth = seen.get(c.name) ?? 0\n seen.set(c.name, nth + 1)\n const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth]\n return {\n name: c.name,\n input: c.input,\n output: c.output,\n ok: c.ok,\n status: 'done' as const,\n inputTokens: approxTokens(c.input),\n outputTokens: approxTokens(c.output),\n ...(streamed?.startedAt !== undefined ? { startedAt: streamed.startedAt } : {}),\n ...(streamed?.durationMs !== undefined ? { durationMs: streamed.durationMs } : {}),\n // With tiers the list holds every attempt's calls, in the order they were made.\n ...(streamed?.attempt !== undefined ? { attempt: streamed.attempt } : {}),\n ...(isReplayedToolOutput(c.output) ? { replayed: true } : {}),\n // The MCP App the call came with (only the stream told it).\n ...(streamed?.app !== undefined ? { app: streamed.app } : {}),\n }\n })\n })(),\n })),\n }\n\n case 'replan.decision': {\n if (!event.failed) {\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n },\n }\n }\n // The replanner could not decide: `continue` is the fallback and the run goes on. The\n // failure itself came as the `error` event (phase 'replan') just before; it is pinned to\n // the step the replanner ran after, so the warning stays in that turn's activity.\n const error = state.replan?.failed ? state.replan.error : undefined\n const last = state.steps[state.steps.length - 1]\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n failed: true,\n ...(error ? { error } : {}),\n },\n steps: last\n ? patchStep(state.steps, last.id, (s) => ({\n ...s,\n replanFailed: error ?? event.reason,\n }))\n : state.steps,\n }\n }\n\n case 'decision': {\n // The decision model is asked after a step (continue / finish): the note belongs to it.\n const view: DecisionView = {\n point: event.point,\n accepted: event.accepted,\n ...(event.choice !== undefined ? { choice: event.choice } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n threshold: event.threshold,\n ...(event.reason ? { reason: event.reason } : {}),\n durationMs: event.durationMs,\n ...(event.model ? { model: event.model } : {}),\n }\n const last = state.steps[state.steps.length - 1]\n return last\n ? {\n ...state,\n steps: patchStep(state.steps, last.id, (s) => ({\n ...s,\n decisions: [...(s.decisions ?? []), view],\n })),\n }\n : { ...state, decisions: [...(state.decisions ?? []), view] }\n }\n\n case 'media.generated':\n return addMedia(state, mediaOf(event, true))\n\n case 'media.transcribed':\n return { ...state, transcripts: [...(state.transcripts ?? []), transcriptOf(event)] }\n\n case 'file.written':\n return fileWritten(state, event)\n\n case 'file.deleted':\n return fileDeleted(state, event.path)\n\n case 'mcp.app':\n // Another tab's app is that tab's: a frame here would load it and run its calls again.\n return ctx.remote ? state : addApp(state, event)\n\n case 'message.queued': {\n if (state.queued.some((q) => q.id === event.id)) return state\n const entry: QueuedMessageView = {\n id: event.id,\n text: event.text,\n ...(event.origin ? { origin: event.origin } : {}),\n }\n // Another tab's run took what THIS tab sent it: its entry takes the place of the one that\n // waited for that tab - shown once, not twice.\n const mine =\n ctx.remote && event.origin === 'another-tab' ? sentEntryOf(state.queued, event.text) : -1\n if (mine < 0) return { ...state, queued: [...state.queued, entry] }\n return { ...state, queued: state.queued.map((q, i) => (i === mine ? entry : q)) }\n }\n\n case 'message.delivered': {\n // Anchored where it landed: inside the executing step (between tool calls),\n // after the step that just ended (a step boundary), or at the end (the answer).\n const anchor =\n event.at === 'round'\n ? runningStepId(state.steps)\n : event.at === 'step'\n ? state.steps[state.steps.length - 1]?.id\n : undefined\n return {\n ...state,\n queued: state.queued.filter((q) => q.id !== event.id),\n notes: [\n ...state.notes,\n {\n id: event.id,\n text: event.text,\n at: event.at,\n ...(anchor ? { stepId: anchor } : {}),\n ...(event.origin ? { origin: event.origin } : {}),\n },\n ],\n }\n }\n\n case 'final.text-delta': {\n const finalText = state.finalText + event.delta\n return { ...state, finalText, messages: streamAssistant(state.messages, finalText) }\n }\n\n case 'final':\n return {\n ...state,\n finalText: event.text,\n messages: finalizeAssistant(state.messages, event.text, runDuration(state, ctx.at)),\n }\n\n case 'final.reasoning-delta':\n return { ...state, finalReasoning: state.finalReasoning + event.delta }\n\n case 'usage':\n // An app's sampling is no run's: it counts in the conversation's total only, never in a\n // run's usage (nor, through it, on an answer).\n if (event.phase === 'app') {\n return { ...state, totalUsage: addUsage(state.totalUsage, event.usage) }\n }\n return {\n ...state,\n usage: addUsage(state.usage, event.usage),\n totalUsage: addUsage(state.totalUsage, event.usage),\n }\n\n case 'mcp.elicitation-requested':\n return addElicitation(state, event, {\n // Asked in the tab that runs the tool call: shown here, answered there.\n ...(ctx.remote ? { remote: true as const } : {}),\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n })\n\n case 'mcp.elicitation-answered':\n return answerElicitation(state, event, runningStepId(state.steps))\n\n case 'user.question-asked':\n return addQuestion(state, event, {\n // Asked in the tab that runs the agent: shown here, answered there only.\n ...(ctx.remote ? { remote: true as const } : {}),\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n })\n\n case 'user.question-answered':\n return answerQuestion(state, event)\n\n case 'tool.approval-requested':\n return {\n ...state,\n approvals: [\n ...state.approvals,\n {\n id: event.id,\n name: event.name,\n input: event.input,\n readOnly: event.readOnly,\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n ...(event.app ? { app: event.app } : {}),\n ...(event.skill ? { skill: event.skill } : {}),\n ...(event.rule ? { rule: event.rule } : {}),\n // Asked in the tab that runs the tool: shown here, answered there.\n ...(ctx.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n\n case 'tool.approval-resolved': {\n const known = state.approvals.some((a) => a.id === event.id)\n const decided = (a: ApprovalView): ApprovalView =>\n withoutSkillBody({\n ...a,\n status: event.approved ? 'approved' : 'denied',\n reason: event.reason,\n automatic: event.automatic,\n })\n return {\n ...state,\n approvals: known\n ? patchApproval(state.approvals, event.id, decided)\n : // A policy denial arrives without a request: record it too.\n [\n ...state.approvals,\n decided({\n id: event.id,\n name: event.name,\n input: undefined,\n readOnly: false,\n stepId: runningStepId(state.steps),\n status: 'pending',\n }),\n ],\n }\n }\n\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(state, event, [], ctx)\n\n case 'skill.activated':\n return state.skills.includes(event.name)\n ? state\n : { ...state, skills: [...state.skills, event.name] }\n\n case 'skill.learned': {\n const before = state.learned.find((l) => l.name === event.name)\n const lesson: LessonView = {\n name: event.name,\n description: event.description,\n // A rewrite of a lesson we know goes up one; a lesson we never saw (an event for a store\n // loaded before this view existed) starts at 2 when the core says it is an update.\n revision: event.update ? (before?.revision ?? 1) + 1 : 1,\n chars: event.chars,\n sources: event.sources,\n }\n return {\n ...state,\n learned: before\n ? state.learned.map((l) => (l.name === event.name ? lesson : l))\n : [...state.learned, lesson],\n learnedNow: state.learnedNow.includes(event.name)\n ? state.learnedNow\n : [...state.learnedNow, event.name],\n }\n }\n\n case 'skill.forgotten':\n return { ...state, learned: state.learned.filter((l) => l.name !== event.name) }\n\n case 'egress.request':\n return {\n ...state,\n fetches: [\n ...state.fetches,\n {\n url: event.url,\n allowed: event.allowed,\n ...(event.status !== undefined ? { status: event.status } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n },\n ],\n }\n\n case 'tools.discovered':\n return {\n ...state,\n discoveredTools: [...new Set([...state.discoveredTools, ...event.names])],\n }\n\n case 'context.compacted':\n return {\n ...state,\n compactions: [\n ...state.compactions,\n { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens },\n ],\n }\n\n case 'budget.exceeded':\n return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } }\n\n case 'session.busy':\n // What was shown as sent waits now: a queued item, not a turn of the transcript.\n state = withoutSubmitted(state)\n return {\n ...state,\n sessionBusy: { heldBy: event.heldBy, ...(ctx.goal ? { goal: ctx.goal } : {}) },\n // What the user sent waits with the run: shown as queued, not lost.\n ...(ctx.goal\n ? {\n queued: [\n ...state.queued.filter((q) => q.id !== WAITING_ID),\n { id: WAITING_ID, text: ctx.goal, session: event.heldBy },\n ],\n }\n : {}),\n }\n\n case 'session.acquired':\n return withoutBusy(state)\n\n case 'stopped':\n // A run of this tab stopped while it only waited for the session: nothing of it began, and\n // the run in view (another tab's, followed here) is not the one that stopped.\n if (!ctx.remote && state.sessionBusy) return withoutBusy(state)\n // Stopped before it began: the turn shown at submit goes (the text goes back to the user).\n if (!ctx.remote && state.submitted) return withoutSubmitted(state)\n return {\n ...withoutBusy(state),\n stopped: true,\n // Nothing of the run is waiting any more once it has stopped (an app's request is not\n // the run's).\n approvals: state.approvals.map((a) =>\n a.status === 'pending' && !a.app\n ? withoutSkillBody({ ...a, status: 'denied' as const, reason: 'stopped' })\n : a,\n ),\n ...(state.elicitations\n ? {\n elicitations: state.elicitations.map((e) =>\n e.status === 'pending'\n ? { ...e, status: 'cancelled' as const, automatic: true, reason: 'stopped' }\n : e,\n ),\n }\n : {}),\n // Nobody is asked any more once the run has stopped.\n ...(state.questions\n ? {\n questions: state.questions.map((q) =>\n q.status === 'pending'\n ? { ...q, status: 'stopped' as const, automatic: true, reason: 'stopped' }\n : q,\n ),\n }\n : {}),\n // What it had written, or nothing - the chat says \"stopped\" through its labels.\n messages: finalizeAssistant(state.messages, state.finalText, {\n ...runDuration(state, ctx.at),\n stopped: true,\n }),\n }\n\n case 'error':\n // A per-step ('execute'/'plan'/...) error does not end the run — only a\n // top-level 'run' error does, and it arrives with no trailing `final`.\n // A replanner that failed is not an error of the run at all: the run continues with its\n // plan. It is held for the `replan.decision { failed }` that follows, never in `error`.\n if (event.phase === 'replan') {\n return {\n ...state,\n replan: { mode: 'continue', reason: '', failed: true, error: event.error },\n }\n }\n return event.phase === 'run'\n ? {\n ...withoutBusy(keepSubmitted(state)),\n error: event.error,\n errorCode: event.code,\n messages: finalizeAssistant(\n state.messages,\n state.finalText || `Error: ${event.error}`,\n { ...runDuration(state, ctx.at), error: true },\n ),\n }\n : { ...state, error: event.error }\n\n case 'retry':\n return state\n\n default:\n return state\n }\n}\n\n/**\n * Mirror the current run's activity onto its assistant message, so every turn\n * of the transcript keeps its own tool calls, thoughts, subagents and usage\n * after the next run starts. Only copies what changed (cheap on every event).\n */\nconst syncRunMessage = (state: AgentUiState): AgentUiState => {\n const id = state.runMessageId\n if (!id) return state\n const i = state.messages.findIndex((m) => m.id === id)\n if (i < 0) return state\n const m = state.messages[i]\n // An app's requests are not the run's decisions: they are never kept on its message.\n const decided = state.approvals.filter((a) => a.status !== 'pending' && !a.app)\n const patch: Partial<ChatMessage> = {}\n if (m.steps !== state.steps) patch.steps = state.steps\n if (m.subagents !== state.subagents) patch.subagents = state.subagents\n if (state.notes.length > 0 && m.notes !== state.notes) patch.notes = state.notes\n if (m.usage !== state.usage) patch.usage = state.usage\n if ((m.reasoning ?? '') !== state.finalReasoning) patch.reasoning = state.finalReasoning\n if (m.skills !== state.skills) patch.skills = state.skills\n if (state.learnedNow.length > 0 && m.learned !== state.learnedNow)\n patch.learned = state.learnedNow\n if (state.fetches.length > 0 && m.fetches !== state.fetches) patch.fetches = state.fetches\n if (state.media && m.media !== state.media) patch.media = state.media\n if (state.transcripts && m.transcripts !== state.transcripts)\n patch.transcripts = state.transcripts\n if (state.writtenFiles && m.writtenFiles !== state.writtenFiles)\n patch.writtenFiles = state.writtenFiles\n if (state.apps && m.apps !== state.apps) patch.apps = state.apps\n if (\n (m.approvals?.length ?? 0) !== decided.length ||\n decided.some((a, k) => m.approvals?.[k] !== a)\n ) {\n patch.approvals = decided\n }\n if (Object.keys(patch).length === 0) return state\n const messages = state.messages.slice()\n messages[i] = { ...m, ...patch }\n return { ...state, messages }\n}\n\n/**\n * The consent requests THIS tab can answer: pending, and not asked in another tab (a run of the\n * conversation going on there - those are shown, and answered only there). What `useAgent`\n * returns as `pendingApprovals`.\n */\nexport const pendingApprovalsOf = (state: Pick<AgentUiState, 'approvals'>): ApprovalView[] =>\n state.approvals.filter((a) => a.status === 'pending' && !a.remote)\n\n/**\n * The status to show: `running` while another tab runs this conversation (`remote`) and this\n * tab is otherwise ready or idle - never over `initializing` or `error`, which the host must see.\n */\nexport const agentStatusOf = (\n state: Pick<AgentUiState, 'status' | 'remote'>,\n): AgentUiState['status'] =>\n state.remote?.running && (state.status === 'ready' || state.status === 'idle')\n ? 'running'\n : state.status\n\nexport const agentStateReducer = (state: AgentUiState, action: AgentAction): AgentUiState => {\n switch (action.type) {\n case 'reset':\n // A full \"new conversation\" clear — unlike run.start, this also drops the\n // transcript. Keep status (the agent is still built) and the seq counter\n // (so ids stay unique across resets).\n return {\n ...createInitialAgentState(),\n status: state.status,\n seq: state.seq,\n learned: state.learned,\n }\n case 'notebook':\n return { ...state, learned: action.lessons }\n case 'submitted': {\n if (state.submitted) return state\n const userId = `msg-${state.seq}`\n const assistantId = `msg-${state.seq + 1}`\n return {\n ...state,\n submitted: { userId, assistantId },\n messages: [\n ...state.messages,\n {\n id: userId,\n role: 'user',\n content: action.goal,\n pending: false,\n ...(action.attachments?.length ? { attachments: action.attachments } : {}),\n },\n { id: assistantId, role: 'assistant', content: '', pending: true },\n ],\n seq: state.seq + 2,\n }\n }\n case 'status':\n return {\n ...state,\n status: action.status,\n error: action.status === 'error' ? action.error : undefined,\n errorCode: undefined,\n }\n case 'remote': {\n const remote = action.remote\n if (!remote) {\n const { remote: _gone, ...rest } = state\n void _gone\n return rest\n }\n // That tab went away mid-run: the answer is what had arrived, marked as cut short.\n if (remote.ended === 'gone' && state.remote?.running) {\n return syncRunMessage({\n ...state,\n remote,\n messages: finalizeAssistant(state.messages, state.finalText, { error: true }),\n })\n }\n return { ...state, remote }\n }\n case 'event': {\n // The person's own words (an ask_user answer) reached the model; they are not kept here -\n // not in the steps, the saved transcript or the event log.\n const event = withoutOwnWords(action.event)\n const next = syncRunMessage(\n applyEvent(state, event, {\n at: action.at,\n attachments: action.attachments,\n ...(action.remote ? { remote: true } : {}),\n ...(action.goal ? { goal: action.goal } : {}),\n }),\n )\n const cap = action.maxEvents ?? 200\n const events = cap > 0 ? [...state.events, event].slice(-cap) : [...state.events, event]\n return { ...next, events }\n }\n case 'undelivered':\n // `keepQueued`: a message another tab refused - the run's queue there is not this one's.\n // What this tab sent to another tab's run waits for that tab, not for this run.\n return {\n ...state,\n queued: action.keepQueued ? state.queued : sentToOtherTab(state.queued),\n undelivered: action.texts,\n }\n case 'remote-send':\n return state.queued.some((q) => q.id === action.id)\n ? state\n : {\n ...state,\n queued: [\n ...state.queued,\n { id: action.id, text: action.text, sentTo: 'another-tab' as const },\n ],\n }\n case 'remote-answer': {\n const queued = state.queued.filter((q) => q.id !== action.id)\n // Refused, or that run ended without it: offered back. Taken: that run shows it (its own\n // `message.queued`, then where it arrived). Unknown: not this view's to offer.\n return action.answer === 'refused'\n ? { ...state, queued, undelivered: [...state.undelivered, action.text] }\n : { ...state, queued }\n }\n case 'load': {\n // Ids of the loaded messages must not collide with ones minted later.\n const maxSeq = action.messages.reduce((n, m) => {\n const k = Number(/^msg-(\\d+)$/.exec(m.id)?.[1] ?? -1)\n return Math.max(n, k + 1)\n }, state.seq)\n return {\n ...createInitialAgentState(),\n status: state.status,\n messages: action.messages.map((m) => (m.pending ? { ...m, pending: false } : m)),\n totalUsage: action.totalUsage ?? emptyUsage(),\n seq: maxSeq,\n learned: state.learned,\n }\n }\n default:\n return state\n }\n}\n","import type {\n AgentEvent,\n AskUserAnswer,\n AskUserConfig,\n AskUserContext,\n AskUserHandler,\n AskUserRequest,\n} from '@dudko.dev/agent-web'\n\n/**\n * The model asks the person ONE closed question (the core's `ask_user`, `config.askUser`): the\n * part of it that is not React - the queue the hook hands the core as `askUser.onQuestion`, the\n * answer a prompt builds, and what of a question's tool result may be kept.\n *\n * Pure: no React, no clock of its own (the queue takes `now`), no import of the core at run time\n * (types only), so the main entry still loads next to an older core.\n *\n * Nothing here keeps, logs or returns what the person typed (`{ other }`) except to the one caller\n * that hands it to the core: the queue passes an answer straight to the core's resolver, and\n * {@link withoutOwnWords} takes the person's words out of the events before a view keeps them.\n */\n\n/** The core's tool name (`ASK_USER_TOOL`). */\nexport const ASK_USER_TOOL_NAME = 'ask_user'\n\n/** The core's default for `askUser.timeoutMs` (`ASK_USER_TIMEOUT_MS`). */\nexport const QUESTION_TIMEOUT_MS = 300_000\n\n/** The longest wait a timer holds (2^31 - 1 ms); the core takes a longer `timeoutMs` as none. */\nconst TIMER_MAX_MS = 2_147_483_647\n\n// ── a question waiting for the person ────────────────────────────────────\n\n/**\n * A question waiting for the person: the core's request (the question and every option are the\n * MODEL's text, cleaned - show them as plain text), and when the core stops waiting for it.\n */\nexport interface PendingQuestion extends AskUserRequest {\n /** Epoch ms after which the core answers it by itself (\"did not answer in time\"); absent: no limit. */\n expiresAt?: number\n}\n\n/**\n * How long the core waits for an answer with this `askUser`; `undefined` = no limit of its own\n * (`0`, `Infinity`, more than a timer holds - the core's own rules).\n */\nexport const questionTimeoutOf = (\n askUser: boolean | AskUserConfig | undefined,\n): number | undefined => {\n if (!askUser) return undefined\n const raw = askUser === true ? undefined : askUser.timeoutMs\n if (raw === undefined || raw === null) return QUESTION_TIMEOUT_MS\n if (typeof raw !== 'number' || !(raw > 0) || raw > TIMER_MAX_MS) return undefined\n return Math.max(1, Math.floor(raw))\n}\n\n/**\n * `config.askUser` as `useAgent` builds the agent with it: on without a handler of its own\n * (`true`, `{ timeoutMs, maxPerRun }`) it gets `handler`; a host's own `onQuestion` wins, and off\n * (absent, `false`) stays off - nothing is added, so the core mounts no tool.\n */\nexport const askUserWith = (\n askUser: boolean | AskUserConfig | undefined,\n handler: AskUserHandler,\n): boolean | AskUserConfig | undefined => {\n if (!askUser) return askUser\n if (askUser === true) return { onQuestion: handler }\n return askUser.onQuestion ? askUser : { ...askUser, onQuestion: handler }\n}\n\nexport interface QuestionQueueOptions {\n /**\n * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read when\n * a question arrives (the settings of the agent that asks).\n */\n timeoutMs?: number | (() => number | undefined)\n /** Called whenever the list of waiting questions changed. */\n onChange?: (pending: PendingQuestion[]) => void\n /** The clock (tests). */\n now?: () => number\n}\n\nexport interface QuestionQueue {\n /** The core's `askUser.onQuestion`: resolves when the person answers, or as `{ declined: true }`. */\n handler: (request: AskUserRequest, ctx?: AskUserContext) => Promise<AskUserAnswer>\n /** The questions waiting, oldest first. */\n pending: () => PendingQuestion[]\n /** Answer one. False when no such question is waiting (answered, expired, cancelled). */\n answer: (id: string, answer: AskUserAnswer) => boolean\n /**\n * Take the waiting questions down - all of them, or those `match` picks - as declined (the run\n * ended, it was stopped). The core has usually stopped waiting already; this only makes sure no\n * resolver is left.\n */\n cancel: (match?: (question: PendingQuestion) => boolean) => void\n /** Cancel everything and stop reporting: the owner is gone. A later question is declined at once. */\n dispose: () => void\n}\n\nconst DECLINED: AskUserAnswer = { declined: true }\n\n/**\n * The questions the model is waiting on: `request.id → resolver`. A question leaves the queue\n * exactly once - answered by the person, dropped because the core no longer wants the answer\n * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (the run ended, an\n * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.\n */\nexport const createQuestionQueue = (options: QuestionQueueOptions = {}): QuestionQueue => {\n const now = options.now ?? Date.now\n const waiting = new Map<\n string,\n { question: PendingQuestion; settle: (answer: AskUserAnswer) => void }\n >()\n let disposed = false\n\n const list = (): PendingQuestion[] => [...waiting.values()].map((w) => w.question)\n const changed = (): void => {\n if (!disposed) options.onChange?.(list())\n }\n\n const handler: QuestionQueue['handler'] = (request, ctx) =>\n new Promise<AskUserAnswer>((resolve) => {\n const signal = ctx?.signal\n // Nobody to ask, nobody wants the answer any more, or the core asks the same id twice.\n if (disposed || signal?.aborted || waiting.has(request.id)) {\n resolve(DECLINED)\n return\n }\n // The core no longer wants the answer: its time ran out, or the run stopped.\n const onAbort = (): void => {\n if (waiting.get(request.id)?.settle !== settle) return\n settle(DECLINED)\n changed()\n }\n // Called only for the question in the map (every caller looks it up first, and it leaves\n // the map here): exactly once - a second answer finds nothing to resolve.\n const settle = (answer: AskUserAnswer): void => {\n waiting.delete(request.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(answer)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n const timeoutMs =\n typeof options.timeoutMs === 'function' ? options.timeoutMs() : options.timeoutMs\n waiting.set(request.id, {\n question: {\n ...request,\n options: request.options.map((o) => ({ ...o })),\n ...(timeoutMs !== undefined ? { expiresAt: now() + timeoutMs } : {}),\n },\n settle,\n })\n changed()\n })\n\n return {\n handler,\n pending: list,\n answer: (id, answer) => {\n const entry = waiting.get(id)\n if (!entry) return false\n entry.settle(answer)\n changed()\n return true\n },\n cancel: (match) => {\n let any = false\n for (const entry of [...waiting.values()]) {\n if (match && !match(entry.question)) continue\n entry.settle(DECLINED)\n any = true\n }\n if (any) changed()\n },\n dispose: () => {\n disposed = true\n for (const entry of [...waiting.values()]) entry.settle(DECLINED)\n },\n }\n}\n\n/**\n * Why a question ended without the person deciding: the core's `AskUserReason`\n * (`handler-error`, `invalid-answer`, `cannot-park`), or its action (`timeout`, `stopped`).\n */\nexport type QuestionOutcomeReason =\n 'timeout' | 'stopped' | 'handler-error' | 'invalid-answer' | 'cannot-park'\n\n// ── the answer a prompt builds ───────────────────────────────────────────\n\n/**\n * The person's picks as the core's answer: the labels that were offered, in the order they were\n * offered, each once - and one only unless the question allows several. `undefined` when nothing\n * that was offered is picked (Send stays off).\n */\nexport const questionChoiceOf = (\n question: Pick<AskUserRequest, 'options' | 'multiple'>,\n picked: readonly string[],\n): AskUserAnswer | undefined => {\n const chosen = question.options.map((o) => o.label).filter((label) => picked.includes(label))\n if (chosen.length === 0) return undefined\n return { choice: question.multiple ? chosen : chosen.slice(0, 1) }\n}\n\n/**\n * The person's own words as the core's answer, when the question allows them and there is\n * anything but spaces; `undefined` otherwise (Send stays off). The text goes to the caller only.\n */\nexport const questionOtherOf = (\n question: Pick<AskUserRequest, 'allowOther'>,\n text: string,\n): AskUserAnswer | undefined =>\n question.allowOther && typeof text === 'string' && text.trim()\n ? { other: text.trim() }\n : undefined\n\n// ── what of a question's tool result a view may keep ─────────────────────\n\n/**\n * The beginnings of the `ask_user` results that hold no word of the person's: a choice (the\n * labels, which are the model's own text), a decline, no answer in time, not asked, the cap. An\n * answer in the person's own words (\"...answered in their own words: ...\") is none of them - and\n * neither is anything a later core may say: a result that is not one of these is not kept.\n */\nconst LABELS_ONLY = [\n 'The user chose: ',\n 'The user chose not to answer.',\n 'The user did not answer in time.',\n 'The question could not be put to the user',\n 'You have already asked the user ',\n]\n\n/** Whether an `ask_user` result may be kept by a view: it holds no word the person typed. */\nexport const askUserOutputKept = (output: unknown, ok: boolean): boolean =>\n // A failed call is about the model's own arguments (a bad question): nobody was asked.\n !ok || (typeof output === 'string' && LABELS_ONLY.some((start) => output.startsWith(start)))\n\ntype ToolCallLike = { name: string; output?: unknown; ok: boolean }\n\nconst withoutOutput = <T extends ToolCallLike>(call: T): T => {\n if (call.name !== ASK_USER_TOOL_NAME || askUserOutputKept(call.output, call.ok)) return call\n const { output: _dropped, ...rest } = call\n void _dropped\n return rest as T\n}\n\n/**\n * The event with the person's own words taken out: the result of an `ask_user` call that is not\n * known to hold labels only (an answer in their own words) loses its `output` - in\n * `step.tool-result`, in `step.complete`'s tool calls, and in a subagent's events at any depth.\n * Everything else comes back as it was (the same object). The model was given the words; the\n * view, the saved chat and the event log are not.\n */\nexport const withoutOwnWords = (event: AgentEvent): AgentEvent => {\n switch (event.type) {\n case 'step.tool-result': {\n const cleaned = withoutOutput(event)\n return cleaned === event ? event : ({ ...cleaned, output: undefined } as AgentEvent)\n }\n case 'step.complete': {\n const calls = event.result.toolCalls\n const cleaned = calls.map(withoutOutput)\n return cleaned.every((c, i) => c === calls[i])\n ? event\n : { ...event, result: { ...event.result, toolCalls: cleaned } }\n }\n case 'subagent.event': {\n const inner = withoutOwnWords(event.event)\n return inner === event.event ? event : { ...event, event: inner }\n }\n default:\n return event\n }\n}\n","import type { AgentLabels } from './labels.js'\nimport type { AgentUiState } from './types.js'\n\n/**\n * Pure helpers behind `<AgentComposer>`: slash commands, attachments, notices\n * and the elapsed-time label. No React, no DOM — unit-tested on their own.\n */\n\n/** A command offered when the input starts with \"/\". */\nexport interface SlashCommand {\n /** Typed after the slash, e.g. \"compact\" for \"/compact\". */\n name: string\n description: string\n /**\n * 'action' runs at once on Enter (e.g. /compact); 'prefix' stays in the\n * input and rewrites the goal on submit (e.g. /chess-coach <goal>).\n */\n kind?: 'action' | 'prefix'\n /** For 'action' commands: what to do (receives the text after the name). */\n run?: (args: string) => void | Promise<void>\n /** For 'prefix' commands: the goal to send, built from the text after the name. */\n transform?: (args: string) => string\n /** Grouping label in the palette (\"Commands\", \"Skills\", …). */\n group?: string\n}\n\n/** \"/name rest of text\" → { name, args }; undefined unless the text starts with \"/\". */\nexport const parseSlash = (text: string): { name: string; args: string } | undefined => {\n const m = /^\\/([\\w-]*)(?:\\s+([\\s\\S]*))?$/.exec(text.trimStart())\n return m ? { name: m[1].toLowerCase(), args: (m[2] ?? '').trim() } : undefined\n}\n\n/** What pressing Enter does while the agent is working (see {@link steerIntent}). */\nexport type SteerIntent =\n /** The agent is idle: submit as usual. */\n | 'idle'\n /** Say it to the running agent. */\n | 'steer'\n /** There are attachments, which cannot be added to a run that is going. */\n | 'attachments'\n /** Nothing to do (empty, a slash command, or steering is switched off). */\n | 'ignore'\n\n/**\n * Decide what Enter means while the agent works: text goes to the running agent,\n * files cannot (they are sent with the next message), a \"/command\" is not a message,\n * and a host that switched steering off gets the old behaviour (nothing happens).\n */\nexport const steerIntent = (input: {\n /** The trimmed text. */\n raw: string\n busy: boolean\n steering: boolean\n hasAttachments: boolean\n}): SteerIntent => {\n if (!input.busy) return 'idle'\n if (!input.steering) return 'ignore'\n if (!input.raw && !input.hasAttachments) return 'ignore'\n if (parseSlash(input.raw)) return 'ignore'\n return input.hasAttachments ? 'attachments' : 'steer'\n}\n\n/** Commands matching what was typed after \"/\" — name prefix first, then substring. */\nexport const filterCommands = (commands: SlashCommand[], query: string): SlashCommand[] => {\n const q = query.toLowerCase()\n if (!q) return commands\n const starts = commands.filter((c) => c.name.toLowerCase().startsWith(q))\n const contains = commands.filter(\n (c) =>\n !starts.includes(c) &&\n (c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q)),\n )\n return [...starts, ...contains]\n}\n\n/**\n * Something attached to the next message:\n * - `text` — its content is inlined into the goal (works with every model);\n * - `image` / `pdf` / `file` — sent to the model as a file part (needs a model\n * that takes that kind — see the core's `agent.capabilities`).\n */\nexport interface ComposerAttachment {\n id: string\n name: string\n kind: 'text' | 'image' | 'pdf' | 'file'\n mediaType: string\n /** Text content (kind 'text'). */\n text?: string\n /** Data URL (kinds image / pdf / file). */\n dataUrl?: string\n bytes: number\n /** Where it was saved in the virtual file system, if it was. */\n path?: string\n /** \"converted from report.pdf\" and the like. */\n note?: string\n /** A recording's length in milliseconds (a voice message). */\n durationMs?: number\n /**\n * A text the host made (`convertFile`): it carries its own note and goes to the model as it is,\n * never cut to an excerpt by `longText` (the host decides how much of a document goes).\n */\n converted?: boolean\n}\n\n/** The kind of an attachment from its media type and name. */\nexport const attachmentKindOf = (mediaType: string, name: string): ComposerAttachment['kind'] => {\n if (mediaType.startsWith('image/')) return 'image'\n if (mediaType === 'application/pdf' || /\\.pdf$/i.test(name)) return 'pdf'\n if (\n mediaType.startsWith('text/') ||\n /json|xml|yaml|javascript|typescript|csv|markdown|x-sh|sql|toml/.test(mediaType) ||\n /\\.(txt|md|markdown|json|csv|tsv|ya?ml|xml|html?|css|m?[jt]sx?|py|sh|log|sql|toml|ini|env)$/i.test(\n name,\n )\n ) {\n return 'text'\n }\n return 'file'\n}\n\n/** What `withAttachments` does with a long text attachment (`<AgentComposer longText>`). */\nexport interface AttachmentTextOptions {\n /**\n * OFF unless given. A text attachment longer than this many characters that was saved in the\n * workspace (`path`) goes as its BEGINNING with a note naming the file that holds it whole -\n * never whole. Only for an agent that can read the file: the core's `createFileTools` over the\n * same workspace (its `fs_read`, or the name `readTool` gives). One the host converted\n * (`converted`), or one without a `path`, goes whole.\n */\n excerptChars?: number\n /** The tool the note tells the model to read on with (default `fs_read`: `createFileTools`' prefix + `read`). */\n readTool?: string\n}\n\n/** The beginning of a long text, cut at a line's end when one is in its second half. */\nexport interface TextExcerpt {\n text: string\n /** The line the excerpt ends in (1-based). */\n lastLine: number\n /** Whether that line is whole in the excerpt (false: it is cut inside it). */\n lineWhole: boolean\n /** Lines of the whole text, counted as the core's `fs_read` counts them (a last line break\n * starts no line). */\n totalLines: number\n}\n\n/** A text's lines as the core's `fs_read` counts them: a text that ends with a line break has no\n * empty last line. */\nexport const lineCountOf = (text: string): number => {\n const lines = text.split('\\n')\n return lines.length > 1 && lines[lines.length - 1] === '' ? lines.length - 1 : lines.length\n}\n\n/**\n * At most `maxChars` characters from the start of `text`: at the last line break when it is in\n * the second half of them (a model reads on by line), never in the middle of a surrogate pair.\n */\nexport const textExcerpt = (text: string, maxChars: number): TextExcerpt => {\n const totalLines = lineCountOf(text)\n if (text.length <= maxChars) return { text, lastLine: totalLines, lineWhole: true, totalLines }\n let end = Math.max(0, Math.floor(maxChars))\n const code = text.charCodeAt(end - 1)\n if (code >= 0xd800 && code <= 0xdbff) end -= 1\n const head = text.slice(0, end)\n const lineEnd = head.lastIndexOf('\\n')\n const atLine = lineEnd >= end / 2\n const cut = atLine ? head.slice(0, lineEnd) : head\n const lastLine = cut.split('\\n').length\n return { text: cut, lastLine, lineWhole: atLine, totalLines }\n}\n\n/**\n * The note in front of an excerpt (for the MODEL, in English like the rest of the goal): how much\n * of the text this is, and how to read on. The file's path is NOT in it - the block's heading\n * names it once (a host that renames a placed file rewrites each mention it counts).\n */\nexport const excerptNote = (\n excerpt: TextExcerpt,\n totalChars: number,\n readTool = 'fs_read',\n): string => {\n const from = excerpt.lineWhole ? excerpt.lastLine + 1 : excerpt.lastLine\n return `[This is only the beginning of a long text: the first ${excerpt.text.length} of ${totalChars} characters (lines 1-${excerpt.lastLine} of ${excerpt.totalLines}${excerpt.lineWhole ? '' : `, line ${excerpt.lastLine} cut`}). The whole text is in the file named above - read on with ${readTool} from line ${from} (startLine / endLine), or search it, only when the answer needs it.]`\n}\n\n/**\n * The goal the agent receives: the typed text followed by each attached TEXT\n * file in a fenced block. Binary attachments travel as file parts instead; the\n * ones saved in the workspace (`path`) are named with it, so a tool can take\n * the file itself (`generate_image`'s reference pictures). With `excerptChars`,\n * a long text saved in the workspace goes as its beginning and the file's path\n * (`AttachmentTextOptions`).\n */\nexport const withAttachments = (\n text: string,\n files: ComposerAttachment[],\n options: AttachmentTextOptions = {},\n): string => {\n const texts = files.filter((f) => f.kind === 'text' && f.text !== undefined)\n // A picture or a file the model gets as itself: where it is in the workspace, so that a tool\n // can take it by its path (generate_image's reference pictures, a PDF to convert).\n const saved = files.filter((f) => f.kind !== 'text' && f.path)\n if (texts.length === 0 && saved.length === 0) return text\n const limit = options.excerptChars\n const blocks = texts.map((f) => {\n const whole = f.text as string\n const cuts = limit !== undefined && f.path !== undefined && !f.converted && whole.length > limit\n const excerpt = cuts ? textExcerpt(whole, limit) : undefined\n const body = excerpt ? excerpt.text : whole\n const fence = body.includes('```') ? '~~~' : '```'\n if (excerpt)\n return `### ${f.name} (its beginning; the whole text: ${f.path})\\n${excerptNote(excerpt, whole.length, options.readTool)}\\n${fence}\\n${body}\\n${fence}`\n const where = f.path ? ` (also saved as ${f.path})` : ''\n return `### ${f.name}${where}\\n${fence}\\n${body}\\n${fence}`\n })\n const kind = (f: ComposerAttachment) =>\n f.kind === 'image' ? 'picture' : f.kind === 'pdf' ? 'PDF' : 'file'\n const lines = saved.map(\n (f) => `- ${kind(f)} \"${f.name.replace(/[\"\\s]+/g, ' ').trim()}\" (also saved as ${f.path})`,\n )\n return [\n text,\n ...(blocks.length ? [`Attached file(s):\\n${blocks.join('\\n\\n')}`] : []),\n ...(lines.length ? [`Also attached:\\n${lines.join('\\n')}`] : []),\n ].join('\\n\\n')\n}\n\n/**\n * The size bounds of an attachment (`<AgentComposer attachments={…}>`; these are the defaults).\n * - `maxBytes`: what is SENT. A file that goes as it is, by its size; one the composer transforms\n * first, by the result - an image it downscales (a 13 MB photo goes as a few hundred KB), a\n * file the host's `convertFile` turns into text (a 30 MB PDF goes as its Markdown).\n * - `maxSourceBytes`: the ORIGINAL of one it transforms, judged before it is read or decoded.\n * - `imageMaxSourcePixels`: the original of an image it downscales, by the pixels its header\n * declares (`imageSizeOf`) - a decoded picture takes ~4 bytes a pixel. A format whose header is\n * not read is held to the bytes only.\n * - `maxImages` / `maxTotalBytes`: ONE message - its pictures, and what all its attachments carry\n * together (`messageOverLimit`), so a batch never meets the provider's request-size error.\n */\nexport interface AttachmentBounds {\n maxBytes: number\n maxSourceBytes: number\n imageMaxSourcePixels: number\n maxImages: number\n maxTotalBytes: number\n}\n\nexport const ATTACHMENT_BOUNDS: AttachmentBounds = {\n maxBytes: 20 * 1024 * 1024,\n // The largest JPEGs a phone writes (a 200 MP shot: ~20-40 MB) pass, and a long PDF with its\n // pictures; past this it is read into memory for nothing the model would get.\n maxSourceBytes: 50 * 1024 * 1024,\n // The largest phone sensor (200 MP: 16320 × 12240) passes, ~800 MB decoded; past this is a\n // scan, a render or a decompression bomb (a PNG of a few KB can declare 30000 × 30000 px).\n imageMaxSourcePixels: 200_000_000,\n // Under what the providers take in one request (Anthropic: 100 pictures, 32 MB; OpenAI: 50 MB).\n maxImages: 20,\n maxTotalBytes: 20 * 1024 * 1024,\n}\n\n/**\n * How an attachment goes to the model: `'convert'` - as the text the host's `convertFile` makes\n * of it (`converts`: the composer will call it for this file); `'downscale'` - an image of a type\n * the composer draws smaller (not GIF - animated - or SVG - drawn at any size), while\n * `imageMaxDimension` is not false; `'none'` - as it is.\n */\nexport type AttachmentTransform = 'none' | 'downscale' | 'convert'\n\nexport const attachmentTransformOf = (input: {\n kind: ComposerAttachment['kind']\n mediaType: string\n imageMaxDimension: number | false\n converts: boolean\n}): AttachmentTransform =>\n input.converts\n ? 'convert'\n : input.kind === 'image' &&\n input.imageMaxDimension !== false &&\n input.mediaType !== 'image/gif' &&\n input.mediaType !== 'image/svg+xml'\n ? 'downscale'\n : 'none'\n\n/** The bound an attachment is over, and its value (bytes or pixels). */\nexport type AttachmentOverLimit = { bound: 'bytes' | 'pixels'; limit: number }\n\n/**\n * Which bound an attachment is over, or undefined. `stage` is when it is judged: `'original'` -\n * the file as picked (and, for an image to downscale, its pixels when known); `'sent'` - what\n * goes to the model (the downscaled image, the converted text, or the file as it is). The\n * original of one the composer transforms is held to `maxSourceBytes` - never below `maxBytes`,\n * so nothing that passed before is refused for its size - and an image's to\n * `imageMaxSourcePixels`; what is sent, to `maxBytes`. One it does not transform: `maxBytes` on\n * the original, as it is.\n */\nexport const attachmentOverLimit = (\n file: { bytes: number; pixels?: number },\n stage: 'original' | 'sent',\n transform: AttachmentTransform,\n bounds: AttachmentBounds,\n): AttachmentOverLimit | undefined => {\n if (stage === 'original' && transform !== 'none') {\n const sourceBytes = Math.max(bounds.maxSourceBytes, bounds.maxBytes)\n if (file.bytes > sourceBytes) return { bound: 'bytes', limit: sourceBytes }\n if (\n transform === 'downscale' &&\n file.pixels !== undefined &&\n file.pixels > bounds.imageMaxSourcePixels\n )\n return { bound: 'pixels', limit: bounds.imageMaxSourcePixels }\n return undefined\n }\n return file.bytes > bounds.maxBytes ? { bound: 'bytes', limit: bounds.maxBytes } : undefined\n}\n\n/**\n * Which limit of ONE message adding `next` to the attachments already in it would break:\n * `'images'` - it is a picture and `maxImages` are there; `'bytes'` - what they would carry\n * together is over `maxTotalBytes`. Each counts as it goes (`bytes`): a picture as downscaled, a\n * converted file as its text, a text file as itself. undefined: it fits.\n */\nexport const messageOverLimit = (\n inMessage: readonly Pick<ComposerAttachment, 'kind' | 'bytes'>[],\n next: Pick<ComposerAttachment, 'kind' | 'bytes'>,\n bounds: Pick<AttachmentBounds, 'maxImages' | 'maxTotalBytes'>,\n): 'images' | 'bytes' | undefined => {\n if (\n next.kind === 'image' &&\n inMessage.filter((a) => a.kind === 'image').length >= bounds.maxImages\n )\n return 'images'\n const total = inMessage.reduce((n, a) => n + a.bytes, 0)\n return total + next.bytes > bounds.maxTotalBytes ? 'bytes' : undefined\n}\n\n/** The transcript label for a message with attachments. */\nexport const attachmentLabel = (text: string, files: ComposerAttachment[]): string =>\n files.length ? `${text}\\n📎 ${files.map((f) => f.name).join(', ')}` : text\n\n/**\n * Can the current model take this attachment? Returns the reason it can't\n * (an actionable sentence), or undefined. `caps` is the core agent's\n * `capabilities` (true / false / undefined per kind; undefined = will try).\n */\nexport const attachmentRefusal = (\n kind: ComposerAttachment['kind'],\n caps: { images?: boolean; pdf?: boolean; files?: boolean } | undefined,\n canConvertPdf = false,\n): string | undefined => {\n if (kind === 'text' || !caps) return undefined\n if (kind === 'image' && caps.images === false) {\n return \"This model can't see images — switch to a vision-capable model (Gemini, Claude, GPT-4o/5) to attach one.\"\n }\n if (kind === 'pdf' && caps.pdf === false && !canConvertPdf) {\n return \"This model can't read PDF files — convert it to text first, or switch to Gemini, Claude or GPT-4o/5.\"\n }\n if (kind === 'file' && caps.files === false) {\n return \"This model can't take file attachments — paste the text instead.\"\n }\n return undefined\n}\n\n/** One run of a chip menu's rows that share a `section` (none: rows drawn without a heading). */\nexport interface MenuSection<T> {\n section?: string\n options: T[]\n}\n\n/**\n * A chip menu's rows as the menu draws them: each run of rows that share a `section` under one\n * heading, in the order given (the host orders them - the keyboard goes the same way). A section\n * that comes back later is a new run: rows are never moved. Pure.\n */\nexport const menuSections = <T extends { section?: string }>(\n options: readonly T[],\n): MenuSection<T>[] => {\n const out: MenuSection<T>[] = []\n for (const option of options) {\n const section = option.section || undefined\n const last = out[out.length - 1]\n if (last && last.section === section) last.options.push(option)\n else out.push({ ...(section ? { section } : {}), options: [option] })\n }\n return out\n}\n\n/**\n * The row a key moves to in a menu of `count` rows from row `index` (-1: none focused): ArrowDown /\n * ArrowUp to the next / previous (around the ends), Home / End to the first / last. Undefined for\n * any other key, or an empty menu. Pure.\n */\nexport const menuKeyTarget = (key: string, index: number, count: number): number | undefined => {\n if (count <= 0) return undefined\n switch (key) {\n case 'ArrowDown':\n return index < 0 ? 0 : (index + 1) % count\n case 'ArrowUp':\n return index < 0 ? count - 1 : (index - 1 + count) % count\n case 'Home':\n return 0\n case 'End':\n return count - 1\n default:\n return undefined\n }\n}\n\n/** 950 → \"0s\", 61_000 → \"1m 1s\", 3_725_000 → \"1h 2m\". */\nexport const formatElapsed = (ms: number): string => {\n const s = Math.max(0, Math.floor(ms / 1000))\n if (s < 60) return `${s}s`\n const m = Math.floor(s / 60)\n if (m < 60) return `${m}m ${s % 60}s`\n return `${Math.floor(m / 60)}h ${m % 60}m`\n}\n\n/** A banner above the input. */\nexport interface ComposerNotice {\n /** Stable per occurrence, so a dismissal sticks until something new happens. */\n id: string\n tone: 'info' | 'warn' | 'error'\n text: string\n}\n\nconst kTokens = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : `${n}`\n\n/** The banner texts (override for another language). */\nexport interface NoticeTexts {\n /** A limit stopped the run; `kind` is 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls'. */\n limit: (kind: string, used: number, cap: number) => string\n /** The context was compacted. */\n compacted: (scope: string, before: number, after: number) => string\n}\n\nexport const defaultNoticeTexts: NoticeTexts = {\n limit: (kind, used, cap) => {\n const calls = kind === 'tool-calls'\n const what = calls ? 'Tool-call' : `${kind[0].toUpperCase()}${kind.slice(1)}-token`\n const amount = calls ? `${used}/${cap} calls` : `${kTokens(used)}/${kTokens(cap)} tokens`\n return `${what} limit reached · ${amount} — the agent stopped early and answered with what it had`\n },\n compacted: (scope, before, after) =>\n `Context compacted (${scope}) · ${kTokens(before)} → ${kTokens(after)} tokens`,\n}\n\n/**\n * The notices worth a banner for the current run: a limit that stopped it, the\n * latest compaction, a failure to start. Pure — derived from the UI state.\n */\nexport const noticesOf = (\n state: AgentUiState,\n texts: Partial<NoticeTexts> = {},\n): ComposerNotice[] => {\n const t = { ...defaultNoticeTexts, ...texts }\n const out: ComposerNotice[] = []\n if (state.status === 'error' && state.error) {\n out.push({ id: `error:${state.error}`, tone: 'error', text: state.error })\n }\n if (state.budget) {\n const b = state.budget\n out.push({\n id: `budget:${state.goal ?? ''}:${b.kind}:${b.cap}`,\n tone: 'warn',\n text: t.limit(b.kind, b.tokens, b.cap),\n })\n }\n const last = state.compactions.at(-1)\n if (last) {\n out.push({\n id: `compact:${state.compactions.length}:${last.beforeTokens}:${last.afterTokens}`,\n tone: 'info',\n text: t.compacted(last.scope, last.beforeTokens, last.afterTokens),\n })\n }\n return out\n}\n\n/** A recording's length as a clock: `0:07`, `12:30`, `1:02:05`. */\nexport const formatClock = (ms: number): string => {\n const s = Math.max(0, Math.floor(ms / 1000))\n const two = (n: number) => String(n).padStart(2, '0')\n const h = Math.floor(s / 3600)\n const m = Math.floor((s % 3600) / 60)\n return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${m}:${two(s % 60)}`\n}\n\n/**\n * What to say of a microphone or dictation failure: the recognizer's own words when it gave some\n * (a host's transcription error, already in its language), else the label of the code - a refused\n * permission says how to allow it again.\n */\nexport const micProblemText = (\n code: string | undefined,\n message: string | undefined,\n labels: Pick<\n AgentLabels,\n 'micDenied' | 'micMissing' | 'micBusy' | 'micUnsupported' | 'dictationFailed' | 'microphone'\n >,\n): string => {\n if (code === 'not-allowed' || code === 'service-not-allowed') return labels.micDenied\n if (code === 'audio-capture') return labels.micMissing\n if (code === 'busy') return labels.micBusy\n if (code === 'unsupported') return labels.micUnsupported\n if (message) return message\n return code && code !== 'transcription' && code !== 'failed'\n ? `${labels.dictationFailed} (${code})`\n : labels.dictationFailed\n}\n\n/** A voice message's file name, from when it was recorded: `voice-2026-11-29-1052.webm`. */\nexport const voiceMessageName = (at: Date, extension: string): string => {\n const two = (n: number) => String(n).padStart(2, '0')\n return `voice-${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())}-${two(\n at.getHours(),\n )}${two(at.getMinutes())}${two(at.getSeconds())}.${extension}`\n}\n\n// ── the message box's limit (`<AgentComposer longText>`) ─────────────────────\n\n/** The counter shows from this share of the limit on (\"3,650 / 4,000\"). */\nexport const INPUT_COUNTER_FROM = 0.9\n\n/** Whether the counter is shown for `count` characters of `max`. */\nexport const inputCounterShown = (count: number, max: number): boolean =>\n count >= Math.ceil(max * INPUT_COUNTER_FROM)\n\n/**\n * A text's length as the box will hold it: a textarea keeps every line break as one `\\n` (a\n * pasted CRLF or CR becomes LF), and its value is counted in UTF-16 code units - what the\n * counter shows and the limit is judged by (an emoji is 2, a letter 1, in every browser).\n */\nexport const boxLength = (text: string): number => text.replace(/\\r\\n?/g, '\\n').length\n\n/**\n * Whether inserting `inserted` into `current` over its selection `[start, end)` keeps the box\n * within `max` characters (`boxLength`).\n */\nexport const insertionFits = (\n current: string,\n start: number,\n end: number,\n inserted: string,\n max: number,\n): boolean => current.length - Math.max(0, end - start) + boxLength(inserted) <= max\n\n/**\n * Whether `text` is ONE character as a person types it: one grapheme (a letter, an emoji with its\n * modifiers, a line break) - what a key press inserts. At the limit that is typing, and it stops;\n * anything longer is never cut.\n */\nexport const isOneCharacter = (text: string): boolean => {\n if (text.length === 0) return false\n if (text.length === 1) return true\n const Segmenter = (Intl as { Segmenter?: typeof Intl.Segmenter }).Segmenter\n if (Segmenter) {\n const it = new Segmenter(undefined, { granularity: 'grapheme' })\n .segment(text)\n [Symbol.iterator]()\n it.next()\n return it.next().done === true\n }\n return [...text].length === 1\n}\n\n/**\n * Where text goes in a box with a limit:\n * - `'insert'` - into the box: it fits (or there is no limit);\n * - `'stop'` - nowhere, silently: ONE character typed into a full box (`fromBox`: it came through\n * the box's own editing - a key, a paste of one letter) - typing stops at the limit;\n * - `'attach'` - the WHOLE of it as a text attachment (never cut);\n * - `'refuse'` - nowhere, said in words: attachments are off.\n * Dictation and a draft are not `fromBox`: a single dictated word is attached, never dropped.\n */\nexport const longTextRoute = (input: {\n current: string\n start: number\n end: number\n inserted: string\n max: number | undefined\n attachments: boolean\n fromBox?: boolean\n}): 'insert' | 'stop' | 'attach' | 'refuse' => {\n if (input.max === undefined) return 'insert'\n if (insertionFits(input.current, input.start, input.end, input.inserted, input.max))\n return 'insert'\n if (input.fromBox && isOneCharacter(input.inserted)) return 'stop'\n return input.attachments ? 'attach' : 'refuse'\n}\n\nconst isHigh = (code: number) => code >= 0xd800 && code <= 0xdbff\nconst isLow = (code: number) => code >= 0xdc00 && code <= 0xdfff\n\n/**\n * What an edit the composer could not stop beforehand inserted (an IME's commit, an insertion\n * whose `beforeinput` cannot be cancelled): the part of `next` that is not in `prev`, found by\n * their common start and end - around the caret, never splitting a surrogate pair. Undefined\n * when the box is within `max`, or did not grow (a deletion is never taken back).\n */\nexport const overflowOf = (\n prev: string,\n next: string,\n max: number,\n): { inserted: string } | undefined => {\n if (next.length <= max || next.length <= prev.length) return undefined\n let head = 0\n const most = Math.min(prev.length, next.length)\n while (head < most && prev.charCodeAt(head) === next.charCodeAt(head)) head += 1\n if (head > 0 && isHigh(next.charCodeAt(head - 1)) && isLow(next.charCodeAt(head))) head -= 1\n let tail = 0\n while (\n tail < most - head &&\n prev.charCodeAt(prev.length - 1 - tail) === next.charCodeAt(next.length - 1 - tail)\n )\n tail += 1\n const to = next.length - tail\n if (tail > 0 && isLow(next.charCodeAt(to)) && isHigh(next.charCodeAt(to - 1))) tail -= 1\n return { inserted: next.slice(head, next.length - tail) }\n}\n\n/**\n * The name of a text attachment the composer made from a paste or a dictation, by when it was\n * made in local time: `pasted-2026-11-30-140509.txt` (`-2`, `-3`… when the message already holds\n * that name: two pastes in one second must not land in one file). `.txt`: it is plain text as it\n * was given - not Markdown (a paste of code or a log is no document) - and every reader of the\n * workspace (`fs_read`, a search index, a preview) takes it as text.\n */\nexport const longTextName = (\n at: Date,\n kind: 'pasted' | 'dictation' = 'pasted',\n taken: readonly string[] = [],\n): string => {\n const two = (n: number) => String(n).padStart(2, '0')\n const stem = `${kind}-${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())}-${two(\n at.getHours(),\n )}${two(at.getMinutes())}${two(at.getSeconds())}`\n let name = `${stem}.txt`\n for (let n = 2; taken.includes(name); n += 1) name = `${stem}-${n}.txt`\n return name\n}\n\n// ── saving a message's attachments (`<AgentComposer files>`) ────────────────\n\n/** What `saveAttachments` needs of a workspace (the core's `VirtualFileSystem` has it). */\nexport interface AttachmentFiles {\n read(path: string): Promise<unknown>\n write(path: string, content: string, opts?: { mimeType?: string }): Promise<unknown>\n writeDataUrl(path: string, dataUrl: string): Promise<unknown>\n delete(path: string): Promise<unknown>\n /**\n * A workspace that NAMES a message's attachments itself gives this, and then it decides where\n * each one goes: it is asked for `/attachments/<name>` and answers where the file is - never\n * over another file (beside it, `-2`…; or the very same file already there, `created: false`,\n * which is then never deleted again). The composer names THAT path to the model. Without it the\n * composer picks a name no file has (`freeAttachmentPath`) and writes there.\n */\n saveAttachment?(\n path: string,\n content: string,\n opts: { mimeType: string; encoding: 'utf8' | 'base64' },\n ): Promise<{ path: string; created: boolean }>\n}\n\n/** A data URL's parts as the core's `writeDataUrl` reads them (base64 or URL-encoded text). */\nexport const dataUrlParts = (\n dataUrl: string,\n): { content: string; encoding: 'utf8' | 'base64'; mimeType: string } => {\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 ? { content: m[3], encoding: 'base64', mimeType }\n : { content: decodeURIComponent(m[3]), encoding: 'utf8', mimeType }\n}\n\n/** One path segment out of an attachment's name (`a b.txt` → `a_b.txt`). */\nexport const attachmentFileName = (name: string): string =>\n name.replace(/[^\\w.-]+/g, '_').slice(0, 80) || 'file'\n\n/**\n * Where an attachment goes in the workspace: `/attachments/<name>`, or - when a file is there\n * already, or this message took the path - `<stem>-2<ext>`, `-3`…: never over another file.\n */\nexport const freeAttachmentPath = async (\n name: string,\n taken: (path: string) => Promise<boolean>,\n): Promise<string> => {\n const file = attachmentFileName(name)\n const dot = file.lastIndexOf('.')\n const stem = dot > 0 ? file.slice(0, dot) : file\n const ext = dot > 0 ? file.slice(dot) : ''\n let path = `/attachments/${file}`\n for (let n = 2; await taken(path); n += 1) path = `/attachments/${stem}-${n}${ext}`\n return path\n}\n\n/** What `saveAttachments` did: every file written, or the ones it could not write (none kept). */\nexport type SavedAttachments = { saved: true } | { saved: false; failed: string[] }\n\n/**\n * Write a message's attachments into the workspace before it is sent, each as a NEW file, and set\n * their `path`. Who names the file: the workspace, when it has `saveAttachment` (a host's policy -\n * the app keeps one file of the same bytes once); else this, by `freeAttachmentPath`. Never both:\n * a host that places a file the library already numbered writes it twice, under two names. All or\n * nothing: when one write fails (no room, over the workspace's file size, any error) the files\n * this message created are deleted again, no `path` is set, and the names of the ones that failed\n * come back - the message must not go (its text would otherwise reach the model whole, or not at\n * all).\n */\nexport const saveAttachments = async (\n files: AttachmentFiles,\n items: ComposerAttachment[],\n): Promise<SavedAttachments> => {\n const created: string[] = []\n const paths = new Map<ComposerAttachment, string>()\n const mine = new Set<string>()\n const taken = async (path: string) => mine.has(path) || (await files.read(path)) !== undefined\n for (const a of items) {\n if (!a.dataUrl && a.text === undefined) continue\n try {\n if (files.saveAttachment) {\n const { content, encoding, mimeType } = a.dataUrl\n ? dataUrlParts(a.dataUrl)\n : { content: a.text as string, encoding: 'utf8' as const, mimeType: a.mediaType }\n const placed = await files.saveAttachment(\n `/attachments/${attachmentFileName(a.name)}`,\n content,\n { mimeType, encoding },\n )\n if (placed.created) created.push(placed.path)\n paths.set(a, placed.path)\n continue\n }\n const path = await freeAttachmentPath(a.name, taken)\n mine.add(path)\n if (a.dataUrl) await files.writeDataUrl(path, a.dataUrl)\n else await files.write(path, a.text as string, { mimeType: a.mediaType })\n created.push(path)\n paths.set(a, path)\n } catch {\n for (const path of created) {\n try {\n await files.delete(path)\n } catch {\n /* best effort: the failure is what is said */\n }\n }\n return { saved: false, failed: [a.name] }\n }\n }\n for (const [a, path] of paths) a.path = path\n return { saved: true }\n}\n","import type {\n DecisionFallbackReason,\n EscalationReason,\n ModelTier,\n TierReason,\n ToolApprovalMode,\n} from '@dudko.dev/agent-web'\nimport { defaultNoticeTexts, type NoticeTexts } from './composer.js'\nimport type { ElicitationIssueKind, ElicitationOutcomeReason } from './elicitation.js'\nimport type { FileKind } from './file-kinds.js'\nimport type { McpAppSandboxReason } from './mcp-app.js'\nimport type { QuestionOutcomeReason } from './questions.js'\nimport type { AgentStatus } from './types.js'\n\n/**\n * Every string the pre-styled components render — override any of them for\n * another language or wording, per component (`labels` prop) or for a whole\n * tree (`<AgentLabelsProvider>`). Counted phrases are functions, so languages\n * with several plural forms can say them properly.\n */\nexport interface AgentLabels {\n // ── chat panel ─────────────────────────────────────────────────────────────\n emptyState: string\n status: Record<AgentStatus, string>\n history: string\n newChat: string\n files: string\n totalUsage: string\n showHistory: string\n showFiles: string\n close: string\n\n // ── transcript ─────────────────────────────────────────────────────────────\n steps: (n: number) => string\n toolCalls: (n: number) => string\n subagents: (n: number) => string\n skillsUsed: (names: string) => string\n /** \"learned: a, b\" - lessons the agent wrote down in this run. */\n learnedNow: (names: string) => string\n /** \"2 web requests\" - what the model fetched in this run. */\n fetches: (n: number) => string\n /** Why a web request was refused. */\n fetchRefused: (reason: string) => string\n answerThoughts: string\n /** In place of the answer of a run that was stopped before it wrote any (`ChatMessage.stopped`). */\n answerStopped: string\n stepThoughts: string\n usageTitle: string\n attachments: string\n planned: string\n replanned: (mode: string, reason: string) => string\n\n // ── notebook (the agent's own lessons) ─────────────────────────────────────\n notebookTitle: string\n notebookEmpty: string\n notebookForget: string\n notebookRevision: (n: number) => string\n /** Before the sources a lesson came from. */\n notebookFrom: string\n\n // ── memory cards (a fact the host's app saved, changed or forgot: `MemoryCard`) ──\n /** Before a fact that was just saved. */\n memorySaved: string\n /** Before a fact that was just changed. */\n memoryUpdated: string\n /** Before a fact that was just forgotten. */\n memoryForgotten: string\n /** The card's button that takes it back. */\n memoryUndo: string\n /** In place of the button once it was taken back. */\n memoryUndone: string\n\n // ── composer ───────────────────────────────────────────────────────────────\n placeholder: string\n listening: string\n message: string\n dropHint: string\n attach: string\n attachTitle: string\n commands: string\n commandsTitle: string\n send: string\n stop: string\n dismiss: string\n remove: (name: string) => string\n dictate: string\n dictateTitle: string\n stopDictation: string\n /**\n * The mic button's name while it listens: that it listens, and that a tap finishes (the title\n * stays `stopDictation`).\n */\n micListening: string\n microphone: string\n /** While a recording recognizer waits for its model (`useSpeechToText().finishing`). */\n transcribing: string\n /** The microphone was refused (`not-allowed`): how to allow it again. */\n micDenied: string\n /** No microphone on the device (`audio-capture`). */\n micMissing: string\n /** The microphone is held by another app (`busy`). */\n micBusy: string\n /** No recording here at all (`unsupported`: an insecure page, no `MediaRecorder`). */\n micUnsupported: string\n /** A dictation that failed without words of its own. */\n dictationFailed: string\n /** The composer's voice-message button (`voiceMessage` of the composer). */\n recordVoiceMessage: string\n /**\n * A recording, in words: the title of a chat a voice message starts (until its transcript is\n * there), the name a screen reader gives a message that is only a recording.\n */\n voiceMessage: string\n /** The length shown beside a voice message's player (`formatClock`: \"0:07\"). */\n audioDuration: (clock: string) => string\n /** The strip while a voice message is recorded: \"Recording 0:07\". */\n recording: (elapsed: string) => string\n /** Its button that keeps the recording as an attachment. */\n recordingDone: string\n /** Its button that throws the recording away. */\n recordingCancel: string\n /** A voice message that reached the longest recording and was stopped by itself. */\n recordingLimit: string\n model: string\n thinking: string\n toolConsent: string\n modes: Record<ToolApprovalMode, { label: string; hint: string }>\n timerRunning: string\n timerLast: string\n agents: (n: number) => string\n agentsTitle: string\n /** Banners: a limit stopped the run / the context was compacted. */\n notices: NoticeTexts\n /** No longer shown: a message of attachments only is shown as its attachments, with no text. */\n attachmentsOnly: string\n seeAttachments: string\n tooLarge: (name: string, mb: number) => string\n /** A picture with more pixels than `attachments.imageMaxSourcePixels` (in millions). */\n tooManyPixels: (name: string, megapixels: number) => string\n binaryText: (name: string) => string\n /** An attachment's note: an image sent smaller (`size` is `bytes` of the original). */\n downscaledFrom: (size: string) => string\n /** An attachment's note: a file sent as the text `convertFile` made of it. */\n convertedFrom: (name: string) => string\n /** Files left out: the message has `attachments.maxImages` pictures (`names`: up to three). */\n tooManyImages: (names: string, max: number) => string\n /** Files left out: the message would carry more than `attachments.maxTotalBytes` (in MB). */\n messageTooLarge: (names: string, mb: number) => string\n /** A paste too long for the message box, as an attachment's note (`longText`): its length. */\n pastedText: (chars: number) => string\n /** The same for a dictation too long for the box. */\n dictatedText: (chars: number) => string\n /** The box's counter near its limit (`longText`): \"3,650 / 4,000\". */\n inputCount: (count: number, max: number) => string\n /** The counter's label (its tooltip and accessible name). */\n inputLimit: (max: number) => string\n /** Said (politely, to a screen reader too) when the box is full. */\n inputLimitReached: (max: number) => string\n /** The same with attachments off: no file is promised. */\n inputLimitFull: (max: number) => string\n /** Said to a screen reader when a paste (or any insertion) became a file: its length. */\n pastedAsFile: (chars: number) => string\n /** The same for a dictation that became a file. */\n dictatedAsFile: (chars: number) => string\n /** A long paste with attachments off: it is not inserted, and not cut either. */\n longTextRefused: (max: number) => string\n /**\n * An attachment could not be written into the workspace (no room, too large, an error): the\n * message was NOT sent and everything stays in the composer.\n */\n attachmentSaveFailed: (names: string) => string\n commandGroups: { commands: string; consent: string; skills: string }\n commandDescriptions: {\n compact: string\n new: string\n stop: string\n autopilot: string\n ask: string\n askAll: string\n readOnly: string\n think: (levels: string) => string\n }\n /** `off` = the provider's default; `none` = thinking switched off. */\n thinkingLevels: { off: string; none: string; low: string; medium: string; high: string }\n\n // ── files panel ────────────────────────────────────────────────────────────\n filesEmpty: string\n upload: string\n download: string\n delete: string\n preview: string\n bytes: (n: number) => string\n\n // ── chat history ───────────────────────────────────────────────────────────\n historyEmpty: string\n deleteChat: string\n messagesCount: (n: number) => string\n\n // ── consent prompt ─────────────────────────────────────────────────────────\n approvalLead: string\n approve: string\n alwaysAllow: string\n deny: string\n declinedReason: string\n readOnlyTool: string\n consentWaiting: string\n consentAllowed: string\n consentDenied: (reason?: string) => string\n\n // ── steering a run that is going ───────────────────────────────────────────\n /** Composer placeholder while the agent works (what you type is sent to it). */\n placeholderBusy: string\n /** The send button while the agent works. */\n steer: string\n /** Shown when files are attached while the agent works (they can't be added then). */\n noAttachmentsWhileBusy: string\n /** A message waiting to reach the agent. */\n queuedWaiting: string\n /**\n * What the user sent, waiting with a run of this tab's that waits for the conversation's other\n * run (`sessionBusy`) - in another tab, or in this one - to finish. Shown only while that lasts.\n */\n queuedForSession: (heldBy: 'another-tab' | 'this-tab') => string\n /**\n * What this tab said to the conversation's run in another tab (`sendRemote`), while that tab has\n * not answered (it may be in the background, frozen by the browser): it is not refused.\n */\n queuedForOtherTab: string\n /** Where a note landed: between tool calls / after a step / before the answer. */\n noteAt: Record<'round' | 'step' | 'final', string>\n /** Messages the run ended without delivering, offered for sending. */\n undelivered: (n: number) => string\n sendUndelivered: string\n discardUndelivered: string\n stopSubagent: string\n subagentStopped: string\n\n // ── another tab of the same site ───────────────────────────────────────────\n /** The conversation is running in another tab: it is shown here live, and Stop / typing go there. */\n remoteRunning: string\n /** That run waits for a person's answer - which is given in that tab. */\n remoteWaitingConsent: string\n /** That tab closed (or crashed) before the run finished. */\n remoteGone: string\n /** This tab's run waits for the other run of the conversation (in another tab, or in this one). */\n sessionBusy: (heldBy: 'another-tab' | 'this-tab') => string\n /** The mark on a message written to this run from another tab (queued, and where it arrived). */\n fromAnotherTab: string\n\n // ── steps / tool calls ─────────────────────────────────────────────────────\n failed: string\n toolCostTitle: string\n\n // ── model tiers and escalation ─────────────────────────────────────────────\n /** The tier badge on a step. */\n tierNames: Record<ModelTier, string>\n /** The badge's tooltip: why the step started on its tier. */\n tierReasons: Record<TierReason, string>\n /** Why a step was retried on a stronger model. */\n escalationReasons: Record<EscalationReason, string>\n /** \"Escalated: light → strong (reported a blocker)\" - the names and the reason are already labels. */\n escalated: (from: string, to: string, reason: string) => string\n /** Opens what the failed attempt had written. */\n escalatedAttemptText: string\n /** \"1 escalation\" in the activity summary. */\n escalations: (n: number) => string\n /** On a tool call made by an attempt that was escalated. */\n attemptTag: (n: number) => string\n /** On a write the core did not run a second time (it succeeded in an earlier attempt). */\n replayed: string\n replayedTitle: string\n /** The replanner call failed; the run went on with the plan it had. */\n replanFailed: string\n\n // ── the subagent tree ──────────────────────────────────────────────────────\n /** The tag on a helper the model started itself (`spawn_subagent`). */\n subagentHelper: string\n /** A node's status, in words. */\n subagentStatus: Record<'running' | 'done' | 'error' | 'stopped', string>\n /** \"12k tokens\" - what was spent under a node; the number is already formatted. */\n subagentTokens: (tokens: string) => string\n /** \"tools: fs_read, web_fetch\" - what a helper was given. */\n subagentTools: (names: string) => string\n /** A helper that was given no tools at all (it only reasons). */\n subagentNoTools: string\n /** The consent prompt of a helper's call: `role` is what the model wrote for it, if anything. */\n approvalLeadHelper: (role: string | undefined, depth: number) => string\n\n // ── generated media and transcripts ────────────────────────────────────────\n /** Alt text of a generated image; `path` is where it is in the workspace. */\n mediaImage: (path: string) => string\n /** A picture in the transcript: the thumbnail's accessible name (it opens the viewer). */\n imageOpen: (name: string) => string\n /** The image viewer: the other pictures of the message, the zoom switch, \"2 of 5\". */\n imagePrevious: string\n imageNext: string\n imageZoom: string\n imageCount: (index: number, total: number) => string\n /** The accessible name of a generated audio player. */\n mediaAudio: (path: string) => string\n /** A generated file that cannot be shown here (no workspace, the file is gone, an unknown type). */\n mediaFile: (path: string) => string\n /** Under a generated picture made with reference pictures: their names (\"me.jpg, dog.png\"). */\n mediaReferences: (names: string) => string\n /** ...and when the image model took none: the picture was made from the text alone. */\n mediaReferencesUnused: (names: string) => string\n /** The summary of a transcript block. */\n transcriptOf: (name: string) => string\n /** Says whose words a transcript is: the content of the user's file, not the agent's. */\n transcriptNote: string\n /** The accessible name of an attached audio file's player (a voice message). */\n audioAttachment: (name: string) => string\n\n // ── read aloud (`readAloud`) ───────────────────────────────────────────────\n readAloud: string\n readAloudPause: string\n readAloudResume: string\n readAloudStop: string\n /** While the audio is made (a provider's voice). */\n readAloudLoading: string\n /** Said in place of a code block - the code is not read out. Empty: the block is skipped. */\n readAloudCode: string\n /** A reading that failed without words of its own. */\n readAloudFailed: string\n\n // ── files written in a turn ────────────────────────────────────────────────\n /** Above the chips: \"3 files written in this turn\". */\n filesWritten: (n: number) => string\n /**\n * Above the chips of the workspace files an answer NAMES (`showNamedFiles`) - it did not write\n * them: \"2 files in this answer\".\n */\n filesNamed: (n: number) => string\n /** In the activity summary: \"3 files\". */\n filesCount: (n: number) => string\n /** The link that opens the Files panel. */\n showInFiles: string\n /** What a file is, on its chip. */\n fileKinds: Record<FileKind, string>\n /** The open button of a chip (accessible name); `name` is the file's name. */\n fileOpen: (name: string) => string\n /** The same button while the preview is open. */\n fileClose: (name: string) => string\n /**\n * A link in an answer to a workspace file (`WorkspaceFileLink`): the button's accessible name,\n * from the link's words and the file's name.\n */\n fileLinkOpen: (text: string, name: string) => string\n /** The download button of a chip (accessible name). */\n fileDownload: (name: string) => string\n /** On a chip: the subagent that wrote the file. */\n fileBy: (name: string) => string\n /** On a chip whose file is not in the workspace any more. */\n fileGone: string\n /** In the preview of a file that cannot be shown as text or as an image. */\n fileNoPreview: string\n /** Under a preview that shows only the first `chars` characters. */\n fileCut: (chars: number) => string\n /** Unfold / fold a long text preview. */\n fileShowRest: string\n fileShowLess: string\n /** The two views of a text file the host can render (Markdown). */\n fileRendered: string\n fileSource: string\n closePreview: string\n /** Under a source view: \"64 lines\". */\n fileLines: (n: number) => string\n\n // ── HTML preview (the sandboxed frame) ─────────────────────────────────────\n /** The host's label on the frame of an HTML file. */\n htmlFrameTitle: string\n /** The two badges under it, while the page is shown. */\n htmlSandboxed: string\n htmlNoNetwork: string\n /** In their place, while the source is shown. */\n htmlSourceNote: string\n /** In the frame's footer. */\n htmlScripts: (on: boolean) => string\n /** The files the page links to that the preview does not load. */\n htmlLinkedFiles: (names: string) => string\n /** A page too large to frame. */\n htmlTooLarge: string\n /** The button that makes the frame taller / back. */\n htmlTaller: string\n htmlShorter: string\n /** The accessible name of the frame itself. */\n htmlFrameName: (path: string) => string\n\n // ── usage: calls that are not tokens ───────────────────────────────────────\n /**\n * `n` is the CALLS to the media models, failed ones included (`usage.mediaCalls`: what the\n * run's cap counts). `made` is what came of them (`imagesGenerated`, `speechCharacters`,\n * `transcriptionSeconds`): a label that says \"pictures made\" counts `made.imagesGenerated`,\n * never `n` - a call that failed made nothing. An empty string shows nothing.\n */\n usageMedia: (\n n: number,\n made: { imagesGenerated: number; speechCharacters: number; transcriptionSeconds: number },\n ) => string\n usageDecisions: (n: number) => string\n\n // ── decision model ─────────────────────────────────────────────────────────\n /** \"decision model: continue (0.93)\" - its answer was used; the probability is formatted. */\n decisionAccepted: (choice: string, confidence: string) => string\n /** \"decision model fell back: low confidence (0.41 < 0.8)\" - the ordinary model call ran. */\n decisionFellBack: (reason: string, detail: string) => string\n decisionReasons: Record<DecisionFallbackReason, string>\n\n // ── web search results ─────────────────────────────────────────────────────\n /** Before the query of a `web_search` call. */\n searchQuery: string\n searchNoResults: string\n /** Results left out by the egress policy. */\n searchFiltered: (n: number) => string\n /** The list was cut to the cap. */\n searchTruncated: string\n\n // ── a question from an MCP server (elicitation) ────────────────────────────\n /** The accessible name of the prompt. */\n elicitationTitle: string\n /** The host's own line: which server asks. */\n elicitationLead: (server: string) => string\n /** The same when the call that asks is a helper's; `role` is what the model wrote for it. */\n elicitationLeadHelper: (server: string, role: string | undefined) => string\n /** Before the tool's name: \"during\". */\n elicitationDuring: string\n /** \"1 of 3\" - several questions are waiting. */\n elicitationCount: (index: number, total: number) => string\n /** The caption over the server's own words. */\n elicitationFrom: (server: string) => string\n /** The meaning of the mark on a required field. */\n elicitationRequired: string\n /** The empty choice of a select. */\n elicitationChoose: string\n elicitationSubmit: string\n elicitationDecline: string\n elicitationCancel: string\n /** Why a field's value does not fit; `field` is its label, `limit` the rule's number. */\n elicitationErrors: Record<ElicitationIssueKind, (field: string, limit?: number) => string>\n /** Over the buttons, after a submit that was refused. */\n elicitationFix: (n: number) => string\n /** The host's line of a link request; the host name follows. */\n elicitationUrlLead: (server: string) => string\n /** The caption over the whole address. */\n elicitationUrlFull: string\n elicitationOpen: string\n /** After the link was opened. */\n elicitationOpened: string\n /** \"I have finished there\" - the accept of a link request. */\n elicitationUrlDone: string\n /** A link that will not be opened from here. */\n elicitationUrlRefused: string\n /** \"Expires in 4:05\". */\n elicitationExpiresIn: (time: string) => string\n /** The same note when the time left is not known. */\n elicitationExpires: string\n /** A question nobody answered: the server, and why (one of `elicitationReasons`). */\n elicitationAutomatic: (server: string, reason: string) => string\n /** Why a question was answered without anybody deciding, by the core's reason (+ `stopped`). */\n elicitationReasons: Record<ElicitationOutcomeReason, string>\n elicitationDismiss: string\n\n // ── a question from the agent (ask_user) ───────────────────────────────────\n /** The host's own line over the model's question. */\n questionLead: string\n /** The same when a helper asks; `role` is what the model wrote for it. */\n questionLeadHelper: (role: string | undefined, depth: number) => string\n /** \"1 of 2\" - several questions are waiting. */\n questionCount: (index: number, total: number) => string\n /** Under a question that takes several options. */\n questionSeveral: string\n /** Sends the options picked, or the person's own words. */\n questionSend: string\n /** Opens the field for an answer in the person's own words. */\n questionOther: string\n /** That field's label. */\n questionOtherLabel: string\n /** No answer: the agent goes on with its best judgment. */\n questionSkip: string\n /** \"...in 4:05\": when the agent stops waiting. */\n questionExpiresIn: (time: string) => string\n /** A question asked by the run in another tab: shown here, answered there. */\n questionRemote: string\n /** The agent went on without an answer; `reason` is one of `questionReasons`. */\n questionAutomatic: (reason: string) => string\n /** Why, by the core's reason (+ `timeout`, `stopped`). */\n questionReasons: Record<QuestionOutcomeReason, string>\n questionDismiss: string\n\n // ── MCP Apps (an app a server's tool came with) ────────────────────────────\n /** The host's label on an app's frame: \"App from server “travel”\". */\n appFrom: (server: string) => string\n /** The badge beside it. */\n appSandboxed: string\n /** The badge when the app runs on an origin of its own (the sandbox page answered). */\n appSandboxedOrigin: string\n /** The note (menu, badge title) for that: the sandbox origin. */\n appSandboxOrigin: (origin: string) => string\n /** A sandbox URL is set, and the app runs in the opaque frame all the same: why. */\n appSandboxFallback: (reason: string) => string\n /** The reasons, by `McpAppSandboxReason`. */\n appSandboxReasons: Record<McpAppSandboxReason, string>\n /** The app loaded its sandbox page again (navigated it) and was stopped. */\n appSandboxBroken: string\n /** The badge while a request of the app waits for the user. */\n appWaiting: string\n /** The \"waiting for you\" badge is a button: its title (it takes the focus to the prompt). */\n appWaitingFocus: string\n /** The region of an app's prompts drawn in its panel / sheet / full screen chrome. */\n appPromptsLabel: (server: string) => string\n /** The tag on the tool call an app came with, and the activity summary's count. */\n appTag: string\n appsCount: (n: number) => string\n appLoading: string\n /** The app could not be read or is refused (`reason` is the core's message). */\n appFailed: (reason: string) => string\n /** No connection to its server (not connected any more, or apps are off). */\n appUnavailable: (server: string) => string\n /** The folded line: \"App from server “travel” · hidden [Show]\". */\n appHidden: string\n appShow: string\n /** The app's menu and what is in it. */\n appMenu: string\n appReload: string\n appOpenPanel: string\n /** Under an inline app taller than the chat shows inline (`appHeightCap`): it scrolls inside. */\n appTaller: string\n appHide: string\n /** The note at the bottom of the menu. */\n appServedBy: (server: string, uri: string) => string\n /** The line left in the transcript while the app is in the panel, and its button. */\n appInPanel: string\n appBringBack: string\n appClosePanel: string\n /** The panel's footer. */\n appPanelNote: (server: string) => string\n /** The accessible name of the app's frame. */\n appFrameName: (server: string) => string\n /** Under the frame: the tools the app called, and the ones that were refused. */\n appRan: (names: string) => string\n appRefused: string\n /** A tool call the app asks for (`<ToolApprovalPrompt>`): the lead and the note. */\n approvalLeadApp: (server: string) => string\n approvalFromApp: (server: string, readOnly: boolean) => string\n /** A link the app asks to open (`<AppRequestPrompt>`). */\n appLinkLead: (server: string) => string\n appLinkNote: string\n appLinkOpen: string\n appCancel: string\n /** A message the app asks to put in the chat. */\n appMessageLead: (server: string) => string\n appMessageNote: string\n appMessageAccept: string\n appMessageDiscard: string\n /** The app shown full screen (`<McpAppFrame allowFullscreen>`): the badge, the way back. */\n appFullscreenBadge: string\n appFullscreenExit: string\n /** The note under an inline app taller than the chat: show it full screen (when it may be). */\n appFullscreenEnter: string\n /** The key that exits too, shown on the button. */\n appFullscreenKey: string\n /** A file the app asks to save (`<AppRequestPrompt>`). */\n appDownloadLead: (server: string) => string\n /** Name · type · size. */\n appDownloadType: (mimeType: string | undefined) => string\n appDownloadSize: (bytes: number) => string\n /** Where the bytes came from: the request itself, or read from the app's server. */\n appDownloadSource: (source: 'embedded' | 'link', server: string) => string\n appDownloadNote: string\n appDownloadSave: string\n /** The app asks the agent's model for an answer (`sampling/createMessage`). */\n appSamplingLead: (server: string) => string\n appSamplingSystem: string\n appSamplingRole: (role: 'user' | 'assistant') => string\n appSamplingImages: (count: number) => string\n appSamplingTokens: (tokens: number, asked: number) => string\n appSamplingNote: string\n appSamplingAllow: string\n appSamplingAlways: string\n appSamplingDeny: string\n /**\n * An MCP server's skill about to enter the model's context (`<ToolApprovalPrompt>`, a request\n * with `approval.skill`): the lead, its size and files, how it was found, the body preview.\n */\n skillConsentLead: (server: string, skill: string) => string\n /** The size of its SKILL.md, and how many more files it bundles. */\n skillConsentSize: (bytes: number, files: number) => string\n /** It was named by its address (`skills/get`), not in the server's list. */\n skillConsentByUri: string\n /** It sits inside another skill of the same server. */\n skillConsentNested: (enclosing: string) => string\n /**\n * A generated skill (`skill.dynamic`): the server publishes no checksums - the person approves\n * the copy the agent just read, and only that copy is used.\n */\n skillConsentDynamic: string\n /** (with `skillConsentDynamic`) The server cannot list the skill's files: SKILL.md alone. */\n skillConsentNoFileListing: string\n /** The summary of the collapsible preview of its instructions. */\n skillConsentPreview: string\n /** Under the preview: its other files, and how many more there are than are shown. */\n skillConsentFiles: (paths: string, more: number) => string\n /** What a yes means: `'once-per-skill'` - this text for the session; `'ask'` - this task. */\n skillConsentNote: (server: string, consent: 'ask' | 'once-per-skill') => string\n skillConsentAllow: string\n skillConsentAlways: string\n skillConsentDeny: string\n /** The reason a \"Deny\" gives the agent. */\n skillConsentDeclined: string\n}\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`\n\n/** \"12,345 characters\" (grouped: a long paste's length is read at a glance). */\nconst characters = (n: number) =>\n `${n.toLocaleString('en-US')} ${n === 1 ? 'character' : 'characters'}`\n\nconst kb = (n: number): string =>\n n < 1024\n ? `${n} B`\n : n < 1024 * 1024\n ? `${(n / 1024).toFixed(1)} KB`\n : `${(n / 1024 / 1024).toFixed(1)} MB`\n\nexport const defaultLabels: AgentLabels = {\n emptyState: 'Ask the agent to do something.',\n status: {\n idle: 'Idle',\n initializing: 'Loading model…',\n ready: 'Ready',\n running: 'Working…',\n error: 'Failed to start',\n },\n history: 'Chats',\n newChat: 'New chat',\n files: 'Files',\n totalUsage: 'Tokens this conversation used, by kind',\n showHistory: 'Show chats',\n showFiles: 'Show files',\n close: 'Close',\n\n steps: (n) => plural(n, 'step', 'steps'),\n toolCalls: (n) => plural(n, 'tool call', 'tool calls'),\n subagents: (n) => plural(n, 'subagent', 'subagents'),\n skillsUsed: (names) => `skills: ${names}`,\n learnedNow: (names) => `learned: ${names}`,\n fetches: (n) => plural(n, 'web request', 'web requests'),\n fetchRefused: (reason) => `refused: ${reason}`,\n answerThoughts: 'Thinking about the answer',\n answerStopped: 'Stopped.',\n stepThoughts: 'Thoughts',\n usageTitle: 'Tokens this answer spent, by kind',\n attachments: 'Attachments',\n planned: 'Plan',\n replanned: (mode, reason) => `Replanned (${mode}): ${reason}`,\n\n notebookTitle: 'Notebook',\n notebookEmpty: 'The agent has not written any lessons down yet.',\n notebookForget: 'Forget',\n notebookRevision: (n) => `revision ${n}`,\n notebookFrom: 'from',\n\n memorySaved: 'Remembered',\n memoryUpdated: 'Memory updated',\n memoryForgotten: 'Forgotten',\n memoryUndo: 'Undo',\n memoryUndone: 'Undone',\n\n placeholder: 'Ask the agent to do something… ( / for commands, Ctrl+V to paste an image )',\n listening: 'Listening…',\n message: 'Message',\n dropHint: 'Drop files or images to attach them',\n attach: 'Attach files',\n attachTitle: 'Attach files or images (or paste with Ctrl+V, or drop them here)',\n commands: 'Commands',\n commandsTitle: 'Commands and skills ( / )',\n send: 'Send',\n stop: 'Stop',\n dismiss: 'Dismiss',\n remove: (name) => `Remove ${name}`,\n dictate: 'Dictate (speech to text)',\n dictateTitle: 'Dictate — speech to text in the browser',\n stopDictation: 'Stop dictation',\n micListening: 'Listening — tap to finish',\n microphone: 'Microphone',\n transcribing: 'Transcribing…',\n micDenied:\n \"The microphone is blocked for this site. Allow it in the browser's site settings (the icon beside the address), then try again.\",\n micMissing: 'No microphone was found on this device.',\n micBusy: 'The microphone is in use by another app.',\n micUnsupported: 'This browser cannot record audio on this page.',\n dictationFailed: 'Dictation did not work.',\n recordVoiceMessage: 'Record a voice message',\n voiceMessage: 'Voice message',\n audioDuration: (clock) => clock,\n recording: (elapsed) => `Recording ${elapsed}`,\n recordingDone: 'Attach the recording',\n recordingCancel: 'Discard the recording',\n recordingLimit: 'The recording reached its longest and was stopped; it is attached.',\n model: 'Model',\n thinking: 'Thinking',\n toolConsent: 'Tool consent',\n modes: {\n autopilot: {\n label: 'Auto',\n hint: 'Never ask: every tool runs - the assistant’s and an app’s. Per-tool rules still apply',\n },\n 'ask-writes': {\n label: 'Ask',\n hint: 'Run read-only tools freely; ask before anything that may change state',\n },\n 'ask-all': { label: 'Ask all', hint: 'Ask before every tool call' },\n 'read-only': {\n label: 'Read-only',\n hint: 'Only read-only tools; refuse changes without asking',\n },\n },\n timerRunning: 'This run so far',\n timerLast: 'The last run took',\n agents: (n) => plural(n, 'agent', 'agents'),\n agentsTitle: 'Subagents running in this run',\n notices: defaultNoticeTexts,\n attachmentsOnly: '(attachments)',\n seeAttachments: 'See the attachments.',\n tooLarge: (name, mb) => `${name} is larger than ${mb} MB.`,\n tooManyPixels: (name, megapixels) =>\n `${name} has more than ${megapixels} megapixels — too large a picture to attach.`,\n binaryText: (name) => `${name} looks binary — it can't be attached as text.`,\n downscaledFrom: (size) => `downscaled from ${size}`,\n convertedFrom: (name) => `converted from ${name}`,\n tooManyImages: (names, max) => `${names}: not added — at most ${max} pictures go in one message.`,\n messageTooLarge: (names, mb) => `${names}: not added — the message would be over ${mb} MB.`,\n pastedText: (chars) => `Pasted text · ${characters(chars)}`,\n dictatedText: (chars) => `Dictated text · ${characters(chars)}`,\n inputCount: (count, max) => `${count.toLocaleString('en-US')} / ${max.toLocaleString('en-US')}`,\n inputLimit: (max) => `The message holds up to ${max.toLocaleString('en-US')} characters`,\n inputLimitReached: (max) =>\n `The message is full: ${max.toLocaleString('en-US')} characters. A longer paste is attached as a file.`,\n inputLimitFull: (max) => `The message is full: ${max.toLocaleString('en-US')} characters.`,\n pastedAsFile: (chars) => `Pasted text attached as a file: ${characters(chars)}`,\n dictatedAsFile: (chars) => `Dictated text attached as a file: ${characters(chars)}`,\n longTextRefused: (max) =>\n `The text is longer than a message holds (${max.toLocaleString('en-US')} characters) — it was not inserted.`,\n attachmentSaveFailed: (names) =>\n `${names}: could not be saved in the files, so the message was not sent. Free some space or remove it, then send again.`,\n commandGroups: { commands: 'Commands', consent: 'Consent', skills: 'Skills' },\n commandDescriptions: {\n compact: 'Summarise the conversation to free context',\n new: 'Start a new conversation',\n stop: 'Stop the current run',\n autopilot: 'Run every tool without asking',\n ask: 'Ask before tools that may change state',\n askAll: 'Ask before every tool call',\n readOnly: 'Only read; refuse changes',\n think: (levels) => `Set thinking: ${levels}`,\n },\n thinkingLevels: {\n off: 'Default',\n none: 'No thinking',\n low: 'Low',\n medium: 'Medium',\n high: 'High',\n },\n\n filesEmpty: 'No files yet. Attachments and files the agent writes appear here.',\n upload: 'Upload',\n download: 'Download',\n delete: 'Delete',\n preview: 'Preview',\n bytes: kb,\n\n historyEmpty: 'No saved chats yet.',\n deleteChat: 'Delete chat',\n messagesCount: (n) => plural(n, 'message', 'messages'),\n\n approvalLead: 'The agent wants to run',\n approve: 'Allow once',\n alwaysAllow: 'Always allow',\n deny: 'Deny',\n declinedReason: 'the user declined',\n readOnlyTool: 'read-only',\n consentWaiting: 'waiting for your consent',\n consentAllowed: 'allowed',\n consentDenied: (reason) => `denied${reason ? ` — ${reason}` : ''}`,\n\n placeholderBusy: 'Tell the agent something while it works…',\n steer: 'Send to the agent',\n noAttachmentsWhileBusy:\n 'Files can’t be added while the agent is working — send them with your next message.',\n queuedWaiting: 'waiting for the agent’s next step',\n queuedForSession: (heldBy) =>\n heldBy === 'this-tab'\n ? 'waiting for the other run to finish'\n : 'waiting for the other tab to finish',\n queuedForOtherTab: 'waiting for the other tab to pick it up',\n noteAt: {\n round: 'you said, between tool calls',\n step: 'you said, after this step',\n final: 'you said, before the answer',\n },\n undelivered: (n) => `Not delivered (${plural(n, 'message', 'messages')})`,\n sendUndelivered: 'Send now',\n discardUndelivered: 'Discard',\n stopSubagent: 'Stop this subagent',\n subagentStopped: 'stopped',\n\n remoteRunning: 'Running in another tab: follow it here, write to it or stop it.',\n remoteWaitingConsent: 'It waits for an answer in the other tab.',\n remoteGone: 'The tab running this conversation closed before it finished.',\n sessionBusy: (heldBy) =>\n heldBy === 'this-tab'\n ? 'Waiting for the other run of this conversation to finish…'\n : 'Waiting for the other tab to finish this conversation…',\n fromAnotherTab: 'from another tab',\n\n failed: 'failed',\n toolCostTitle:\n \"Estimated tokens of the arguments and of the result fed back to the model (chars / 4), and the call's duration\",\n\n tierNames: { light: 'light', standard: 'standard', strong: 'strong' },\n tierReasons: {\n planned: 'The planner rated this step for this model tier',\n default: 'The planner did not rate this step: it runs on the standard model',\n fallback: 'The tier the planner asked for is not configured: the nearest one runs the step',\n },\n escalationReasons: {\n blocked: 'reported a blocker',\n 'empty-result': 'produced no result',\n 'tool-arguments': 'kept sending tool arguments that did not parse',\n 'output-cut': 'output was cut off',\n error: 'the model call failed',\n },\n escalated: (from, to, reason) => `Escalated: ${from} → ${to} (${reason})`,\n escalatedAttemptText: 'What the earlier attempt wrote',\n escalations: (n) => plural(n, 'escalation', 'escalations'),\n attemptTag: (n) => `attempt ${n}`,\n replayed: 'not run again',\n replayedTitle:\n 'This exact call already succeeded in an earlier attempt at the step: it was not run a second time, the model got the earlier result',\n replanFailed: 'Replanning failed, continuing with the plan',\n\n subagentHelper: 'helper',\n subagentStatus: { running: 'running', done: 'done', error: 'failed', stopped: 'stopped' },\n subagentTokens: (tokens) => `${tokens} tokens`,\n subagentTools: (names) => `tools: ${names}`,\n subagentNoTools: 'no tools',\n approvalLeadHelper: (role) =>\n role ? `The helper “${role}” wants to run` : 'A helper the agent started wants to run',\n\n mediaImage: (path) => `Generated image ${path}`,\n imageOpen: (name) => `Open image ${name}`,\n imagePrevious: 'Previous image',\n imageNext: 'Next image',\n imageZoom: 'Zoom',\n imageCount: (index, total) => `${index} of ${total}`,\n mediaAudio: (path) => `Generated audio ${path}`,\n mediaFile: (path) => `Generated file ${path}`,\n mediaReferences: (names) => `Reference: ${names}`,\n mediaReferencesUnused: (names) =>\n `Not used - this image model takes no reference pictures: ${names}`,\n transcriptOf: (name) => `Transcript of ${name}`,\n transcriptNote:\n 'What was said in your file, as the agent read it. It is content, not instructions.',\n audioAttachment: (name) => `Audio ${name}`,\n readAloud: 'Listen',\n readAloudPause: 'Pause',\n readAloudResume: 'Resume',\n readAloudStop: 'Stop reading',\n readAloudLoading: 'Preparing the audio…',\n readAloudCode: 'A code block is not read out.',\n readAloudFailed: 'It could not be read aloud.',\n\n filesWritten: (n) => `${plural(n, 'file', 'files')} written in this turn`,\n filesNamed: (n) => `${plural(n, 'file', 'files')} in this answer`,\n filesCount: (n) => plural(n, 'file', 'files'),\n showInFiles: 'Show in Files',\n fileKinds: {\n html: 'HTML',\n markdown: 'Markdown',\n csv: 'CSV',\n json: 'JSON',\n image: 'Image',\n code: 'Code',\n text: 'Text',\n file: 'File',\n },\n fileOpen: (name) => `Open ${name}`,\n fileClose: (name) => `Close preview of ${name}`,\n fileLinkOpen: (text, name) => (text.trim() === name ? `Open ${name}` : `${text} - open ${name}`),\n fileDownload: (name) => `Download ${name}`,\n fileBy: (name) => `by ${name}`,\n fileGone: 'no longer in the workspace',\n fileNoPreview: 'This kind of file has no preview. Download it to open it.',\n fileCut: (chars) =>\n `Only the first ${chars.toLocaleString('en-US')} characters are shown. Download the file for the rest.`,\n fileShowRest: 'Show the rest',\n fileShowLess: 'Show less',\n fileRendered: 'Rendered',\n fileSource: 'Source',\n closePreview: 'Close preview',\n fileLines: (n) => plural(n, 'line', 'lines'),\n\n htmlFrameTitle: 'HTML written by the agent',\n htmlSandboxed: 'sandboxed',\n htmlNoNetwork: 'no network',\n htmlSourceNote: 'shown as text, nothing runs',\n htmlScripts: (on) => (on ? 'scripts on' : 'scripts off'),\n htmlLinkedFiles: (names) => `linked files are not loaded: ${names}`,\n htmlTooLarge: 'This page is too large to preview. It is shown as source.',\n htmlTaller: 'Make the preview taller',\n htmlShorter: 'Make the preview shorter',\n htmlFrameName: (path) => `Preview of ${path}`,\n\n usageMedia: (n) => plural(n, 'media call', 'media calls'),\n usageDecisions: (n) => plural(n, 'decision call', 'decision calls'),\n\n decisionAccepted: (choice, confidence) => `decision model: ${choice} (${confidence})`,\n decisionFellBack: (reason, detail) =>\n `decision model fell back: ${reason}${detail ? ` (${detail})` : ''}`,\n decisionReasons: {\n 'low-confidence': 'low confidence',\n 'invalid-choice': 'an answer that is not an option',\n 'invalid-confidence': 'a confidence that is not a probability',\n error: 'the call failed',\n timeout: 'timed out',\n 'needs-model': 'the choice needs the model',\n },\n\n searchQuery: 'Searched the web for',\n searchNoResults: 'no results',\n searchFiltered: (n) => `${n} left out by the web access policy`,\n searchTruncated: 'list cut short',\n\n elicitationTitle: 'A question from an MCP server',\n elicitationLead: (server) => `The MCP server “${server}” asks for your input`,\n elicitationLeadHelper: (server, role) =>\n role\n ? `The MCP server “${server}” asks for your input (a call by the helper “${role}”)`\n : `The MCP server “${server}” asks for your input (a call by a helper)`,\n elicitationDuring: 'during',\n elicitationCount: (index, total) => `${index} of ${total}`,\n elicitationFrom: (server) => `From the server “${server}”`,\n elicitationRequired: 'required',\n elicitationChoose: 'Choose…',\n elicitationSubmit: 'Submit',\n elicitationDecline: 'Decline',\n elicitationCancel: 'Cancel',\n elicitationErrors: {\n required: (field) => `${field} is required.`,\n tooShort: (field, limit) => `${field} must be at least ${limit} characters.`,\n tooLong: (field, limit) => `${field} must be at most ${limit} characters.`,\n email: (field) => `${field} must be an email address.`,\n uri: (field) => `${field} must be a full address, such as https://example.com.`,\n date: (field) => `${field} must be a date.`,\n dateTime: (field) => `${field} must be a date and a time.`,\n notNumber: (field) => `${field} must be a number.`,\n notInteger: (field) => `${field} must be a whole number.`,\n belowMinimum: (field, limit) => `${field} must be ${limit} or more.`,\n aboveMaximum: (field, limit) => `${field} must be ${limit} or less.`,\n notAnOption: (field) => `${field} must be one of the options.`,\n tooFew: (field, limit) => `${field}: choose at least ${limit}.`,\n tooMany: (field, limit) => `${field}: choose at most ${limit}.`,\n },\n elicitationFix: (n) => `${plural(n, 'field needs', 'fields need')} a correction.`,\n elicitationUrlLead: (server) => `The MCP server “${server}” asks you to open a page on`,\n elicitationUrlFull: 'Full address',\n elicitationOpen: 'Open in a new tab',\n elicitationOpened: 'Opened in a new tab. Finish there, then confirm here.',\n elicitationUrlDone: 'I have finished there',\n elicitationUrlRefused:\n 'This link is not a secure (https) address, so it is not opened from here.',\n elicitationExpiresIn: (time) => `Cancelled automatically in ${time}`,\n elicitationExpires: 'Cancelled automatically if it is left unanswered',\n elicitationAutomatic: (server, reason) =>\n `A question from the MCP server “${server}” was answered automatically, and its tool call did not finish: ${reason}.`,\n elicitationReasons: {\n timeout: 'nobody answered in time',\n 'step-timeout': 'the step ran out of time while the question was waiting',\n aborted: 'the run was stopped',\n stopped: 'the run was stopped',\n 'cap-per-call': 'the tool call had already asked too many questions',\n 'cap-per-run': 'too many questions had already been asked in this run',\n 'unsupported-schema': 'the form it sent cannot be shown',\n 'unsupported-mode': 'it asked in a way this app does not offer',\n 'insecure-url': 'the link it sent was refused',\n 'invalid-request': 'its request was malformed',\n subagent: 'a helper is not allowed to ask you',\n 'handler-error': 'the question could not be shown',\n 'invalid-answer': 'the answer did not fit the form and was not sent',\n 'after-failure': 'an earlier question of the same call had already failed',\n 'no-tool-call': 'no tool call was in progress',\n },\n elicitationDismiss: 'Dismiss',\n\n questionLead: 'The agent asks you',\n questionLeadHelper: (role) =>\n role ? `The helper “${role}” asks you` : 'A helper the agent started asks you',\n questionCount: (index, total) => `${index} of ${total}`,\n questionSeveral: 'Pick one or more, then Send.',\n questionSend: 'Send',\n questionOther: 'Other…',\n questionOtherLabel: 'Your answer',\n questionSkip: 'Skip',\n questionExpiresIn: (time) => `If you do not answer, the agent decides by itself in ${time}`,\n questionRemote: 'Answered in the other tab, where the agent is running.',\n questionAutomatic: (reason) => `The agent went on without your answer: ${reason}.`,\n questionReasons: {\n timeout: 'nobody answered in time',\n stopped: 'the run was stopped',\n 'handler-error': 'the question could not be shown',\n 'invalid-answer': 'the answer did not fit the question',\n 'cannot-park': 'the question could not wait here',\n },\n questionDismiss: 'Dismiss',\n\n appFrom: (server) => `App from server “${server}”`,\n appSandboxed: 'sandboxed',\n appSandboxedOrigin: 'sandboxed on its own origin',\n appSandboxOrigin: (origin) =>\n `Runs on its own origin, ${origin}: its storage is its own, never this page's.`,\n appSandboxFallback: (reason) =>\n `Not on an origin of its own (${reason}): it runs in an opaque sandbox, with no storage of its own.`,\n appSandboxReasons: {\n invalid: 'the sandbox URL is not valid',\n insecure: 'the sandbox URL is not https',\n 'same-origin': \"the sandbox URL is on this page's origin\",\n 'no-page-origin': 'this page has no origin of its own',\n 'server-name': \"the server's name is not a DNS label\",\n 'too-many-origins': 'it declares too many origins',\n 'no-answer': 'the sandbox page did not answer',\n },\n appSandboxBroken: 'The app reloaded its frame, so it was stopped. Reload it to start again.',\n appWaiting: 'waiting for you',\n appWaitingFocus: 'Go to what the app is waiting for',\n appPromptsLabel: (server) => `What the app from “${server}” is waiting for`,\n appTag: 'app',\n appsCount: (n) => plural(n, 'app', 'apps'),\n appLoading: 'Loading the app…',\n appFailed: (reason) => `The app could not be shown: ${reason}`,\n appUnavailable: (server) =>\n `The server “${server}” is not connected, so its app cannot be shown.`,\n appHidden: 'hidden',\n appShow: 'Show',\n appMenu: 'App menu',\n appReload: 'Reload app',\n appOpenPanel: 'Open in panel',\n appTaller: 'Taller than the chat - this app scrolls inside its frame.',\n appHide: 'Hide app',\n appServedBy: (server, uri) =>\n `Served by ${server} as ${uri}. It cannot read this chat, your keys or your files.`,\n appInPanel: 'open in the panel',\n appBringBack: 'Bring back',\n appClosePanel: 'Close the panel',\n appPanelNote: (server) =>\n `Content from the server “${server}”. It cannot read this chat, your keys or your files.`,\n appFrameName: (server) => `App from server ${server}`,\n appRan: (names) => `The app ran ${names}`,\n appRefused: 'refused',\n approvalLeadApp: (server) => `The app “${server}” wants to run`,\n approvalFromApp: (server, readOnly) =>\n `Asked by the app, not by the agent. This tool ${readOnly ? 'only reads' : 'changes'} data on the server “${server}”.`,\n appLinkLead: (server) => `The app “${server}” wants to open a link. Open it?`,\n appLinkNote: 'Opens in a new tab, outside this chat. Check the site name before you continue.',\n appLinkOpen: 'Open',\n appCancel: 'Cancel',\n appMessageLead: (server) => `The app “${server}” wants to put a message in your message box`,\n appMessageNote:\n 'Nothing is sent until you send it yourself, and you can change it first. It is the app’s text, not yours.',\n appMessageAccept: 'Put in the message box',\n appMessageDiscard: 'Discard',\n appFullscreenBadge: 'full screen',\n appFullscreenExit: 'Exit full screen',\n appFullscreenEnter: 'Full screen',\n appFullscreenKey: 'Esc',\n appDownloadLead: (server) => `The app “${server}” wants to save a file to your device`,\n appDownloadType: (mimeType) => mimeType ?? 'type not given',\n appDownloadSize: kb,\n appDownloadSource: (source, server) =>\n source === 'link'\n ? `Read from the server “${server}” for the app.`\n : 'Made by the app inside its frame.',\n appDownloadNote:\n 'This page saves it, not the app. Programs, scripts and web pages are never saved; check the name before you save.',\n appDownloadSave: 'Save file',\n appSamplingLead: (server) => `The app “${server}” asks the agent’s model for an answer`,\n appSamplingSystem: 'Its instructions',\n appSamplingRole: (role) => (role === 'user' ? 'Asks' : 'Earlier answer'),\n appSamplingImages: (count) => plural(count, 'image', 'images'),\n appSamplingTokens: (tokens, asked) =>\n tokens < asked\n ? `Up to ${tokens} tokens (the app asked for ${asked}).`\n : `Up to ${tokens} tokens.`,\n appSamplingNote:\n 'Only this text is sent - not your chat. The answer goes to the app only, and its tokens count in your total.',\n appSamplingAllow: 'Allow once',\n appSamplingAlways: 'Always for this app',\n appSamplingDeny: 'Deny',\n skillConsentLead: (server, skill) => `The server “${server}” offers the skill “${skill}”`,\n skillConsentSize: (bytes, files) =>\n `SKILL.md ${kb(bytes)}${files ? ` · ${plural(files, 'more file', 'more files')}` : ''}`,\n skillConsentByUri: 'Not in the server’s list: the agent asked for it by its address.',\n skillConsentNested: (enclosing) =>\n `It sits inside the skill “${enclosing}”: allowing that one did not allow this one.`,\n skillConsentDynamic:\n 'This server publishes no checksums for this skill: you approve the copy the agent just read, and only that copy is used.',\n skillConsentNoFileListing:\n 'The server cannot list this skill’s files: that copy is its SKILL.md alone.',\n skillConsentPreview: 'Show what the agent would read',\n skillConsentFiles: (paths, more) =>\n `Its files, read as text and never run: ${paths}${more ? ` and ${more} more` : ''}`,\n skillConsentNote: (server, consent) =>\n `Instructions written by the server “${server}”, not by you. They reach the agent only if you allow it${\n consent === 'ask'\n ? ', and you are asked again in every task that loads them.'\n : ' - you are asked again if the server changes them.'\n } They cannot change the agent’s rules or approvals.`,\n skillConsentAllow: 'Allow once',\n skillConsentAlways: 'Always for this server',\n skillConsentDeny: 'Deny',\n skillConsentDeclined: 'the user declined the skill',\n}\n\n/** Overrides: any label, with the nested groups merged key by key. */\nexport type AgentLabelsOverride = Partial<\n Omit<\n AgentLabels,\n | 'status'\n | 'modes'\n | 'commandGroups'\n | 'commandDescriptions'\n | 'thinkingLevels'\n | 'notices'\n | 'tierNames'\n | 'tierReasons'\n | 'escalationReasons'\n | 'subagentStatus'\n | 'decisionReasons'\n | 'elicitationErrors'\n | 'elicitationReasons'\n | 'questionReasons'\n | 'fileKinds'\n | 'appSandboxReasons'\n >\n> & {\n status?: Partial<AgentLabels['status']>\n modes?: Partial<AgentLabels['modes']>\n commandGroups?: Partial<AgentLabels['commandGroups']>\n commandDescriptions?: Partial<AgentLabels['commandDescriptions']>\n thinkingLevels?: Partial<AgentLabels['thinkingLevels']>\n notices?: Partial<AgentLabels['notices']>\n tierNames?: Partial<AgentLabels['tierNames']>\n tierReasons?: Partial<AgentLabels['tierReasons']>\n escalationReasons?: Partial<AgentLabels['escalationReasons']>\n subagentStatus?: Partial<AgentLabels['subagentStatus']>\n decisionReasons?: Partial<AgentLabels['decisionReasons']>\n elicitationErrors?: Partial<AgentLabels['elicitationErrors']>\n elicitationReasons?: Partial<AgentLabels['elicitationReasons']>\n questionReasons?: Partial<AgentLabels['questionReasons']>\n fileKinds?: Partial<AgentLabels['fileKinds']>\n appSandboxReasons?: Partial<AgentLabels['appSandboxReasons']>\n}\n\nconst NESTED = [\n 'status',\n 'modes',\n 'commandGroups',\n 'commandDescriptions',\n 'thinkingLevels',\n 'noteAt',\n 'tierNames',\n 'tierReasons',\n 'escalationReasons',\n 'subagentStatus',\n 'decisionReasons',\n 'elicitationErrors',\n 'elicitationReasons',\n 'questionReasons',\n 'fileKinds',\n 'appSandboxReasons',\n] as const\n\n/** `base` with `over` applied (nested groups merged, not replaced). */\nexport const mergeLabels = (base: AgentLabels, over?: AgentLabelsOverride): AgentLabels => {\n if (!over) return base\n const out = { ...base, ...over } as AgentLabels\n for (const key of NESTED) {\n if (over[key]) (out as unknown as Record<string, unknown>)[key] = { ...base[key], ...over[key] }\n }\n return out\n}\n","/**\n * The transcript's scroll position while content arrives - the rule, as a pure function (no DOM),\n * and the numbers it stands on. `useFollowScroll` (hooks/use-follow-scroll.ts) applies it.\n *\n * Two states. FOLLOWING: the view is at the end and stays there, whatever grows or shrinks.\n * READING: the person moved up, and the view is theirs - nothing that arrives moves what they\n * read; going back down to the end follows again.\n */\n\n/** A scroller's measures (CSS pixels). */\nexport interface ScrollMeasure {\n scrollTop: number\n scrollHeight: number\n clientHeight: number\n}\n\n/** How far from the end still counts as \"back at the end\" when moving down. */\nexport const FOLLOW_REJOIN_PX = 80\n/**\n * How far above the end a move up must leave the view to count as the person's. Under it, a\n * move up is the browser's own: the bounce at the end of a touch scroll (the position comes\n * back from beyond the end), or a sub-pixel rounding. Small on purpose: a slow drag moves a\n * few pixels between two pieces of an answer, and must not be pulled back.\n */\nexport const FOLLOW_LEAVE_PX = 2\n\nexport const endGap = (m: ScrollMeasure): number => m.scrollHeight - m.scrollTop - m.clientHeight\n\n/** The furthest position the view had a reason to be at: its own, or the end (a bounce is beyond it). */\nconst reach = (m: ScrollMeasure): number =>\n Math.min(m.scrollTop, Math.max(0, m.scrollHeight - m.clientHeight))\n\n/**\n * Whether the view follows after a scroll event: `before` is what the scroller measured when it\n * was last looked at, `now` what it measures in the event.\n *\n * - The content or the box changed size since: the move is the layout's (the browser keeps the\n * position inside a shorter transcript, a keyboard opens), not the person's - nothing changes.\n * - A move up that leaves the end: the person reads - stop following.\n * - A move down that ends near the end: follow again.\n */\nexport const followsAfterScroll = (\n following: boolean,\n before: ScrollMeasure,\n now: ScrollMeasure,\n): boolean => {\n if (before.scrollHeight !== now.scrollHeight || before.clientHeight !== now.clientHeight)\n return following\n if (now.scrollTop < reach(before) - FOLLOW_LEAVE_PX) return false\n if (now.scrollTop > before.scrollTop) return endGap(now) < FOLLOW_REJOIN_PX ? true : following\n return following\n}\n\n/**\n * Whether the view still follows when the transcript changed size: a piece of the answer often\n * lands between a move of the person's and its scroll event, and must not undo the move. With\n * the box as it was and the transcript no shorter, nothing but the person moves the view up\n * (the hook turns the browser's own scroll anchoring off: `useFollowScroll`).\n */\nexport const followsAfterResize = (\n following: boolean,\n before: ScrollMeasure,\n now: ScrollMeasure,\n): boolean =>\n following &&\n !(\n now.clientHeight === before.clientHeight &&\n now.scrollHeight >= before.scrollHeight &&\n now.scrollTop < reach(before) - FOLLOW_LEAVE_PX\n )\n","import { MEDIA_IMAGE_TYPES, isTextMime } from '@dudko.dev/agent-web'\n\n/**\n * What a workspace file is to the UI. `image` is only what the core's media tools accept\n * (PNG / JPEG / GIF / WebP - never SVG, which is shown as its source); `file` is anything that\n * cannot be shown as text: a chip with a download and no preview.\n */\nexport type FileKind = 'html' | 'markdown' | 'csv' | 'json' | 'image' | 'code' | 'text' | 'file'\n\nconst CODE =\n /\\.(?:js|mjs|cjs|jsx|ts|tsx|css|scss|py|rb|go|rs|java|kt|c|h|cpp|cs|php|sh|sql|xml|svg|yaml|yml|toml)$/i\n\nconst mimeOf = (mediaType: string): string => mediaType.toLowerCase().split(';')[0].trim()\n\n/** The kind of a file, by its MIME type first and its extension second. */\nexport const fileKindOf = (path: string, mediaType: string): FileKind => {\n const mime = mimeOf(mediaType)\n if (Object.hasOwn(MEDIA_IMAGE_TYPES, mime)) return 'image'\n if (mime === 'text/html' || mime === 'application/xhtml+xml' || /\\.x?html?$/i.test(path))\n return 'html'\n if (mime === 'text/markdown' || /\\.(?:md|markdown)$/i.test(path)) return 'markdown'\n if (mime === 'text/csv' || /\\.(?:csv|tsv)$/i.test(path)) return 'csv'\n if (mime === 'application/json' || /\\.json$/i.test(path)) return 'json'\n if (CODE.test(path)) return 'code'\n if (mime === 'text/plain' || /\\.(?:txt|log)$/i.test(path) || isTextMime(mime)) return 'text'\n return 'file'\n}\n\n/** The last segment of a path: what a chip is called and what a download is saved as. */\nexport const fileNameOf = (path: string): string => path.split('/').filter(Boolean).pop() || 'file'\n","/**\n * Downscale an image in the browser before it goes to a model. Providers bill\n * images by their pixel size and resize anything over ~1.15 MP / 1568 px on\n * the long edge themselves — sending more only costs upload time and, for\n * some providers, tokens. GIF and SVG are left as they are.\n */\nexport interface DownscaleOptions {\n /** Longest edge in pixels (default 1568). */\n maxDimension?: number\n /** Total pixels (default 1 150 000). */\n maxPixels?: number\n /** JPEG/WebP quality 0..1 (default 0.9). */\n quality?: number\n}\n\ntype AnyCanvas = OffscreenCanvas | HTMLCanvasElement\n\nconst canvasOf = (w: number, h: number): AnyCanvas | undefined => {\n if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(w, h)\n if (typeof document !== 'undefined') {\n const c = document.createElement('canvas')\n c.width = w\n c.height = h\n return c\n }\n return undefined\n}\n\nconst toBlob = (canvas: AnyCanvas, type: string, quality: number): Promise<Blob | null> =>\n 'convertToBlob' in canvas\n ? canvas.convertToBlob({ type, quality })\n : new Promise((resolve) => canvas.toBlob(resolve, type, quality))\n\n/** A picture's size in pixels, as its file declares it. */\nexport interface ImageSize {\n width: number\n height: number\n}\n\nconst WINDOW = 64 * 1024\n// JPEG markers that start a frame and carry its size (SOF0-15 but DHT, JPG and DAC).\nconst SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf])\n\n/**\n * A picture's size in pixels read from its file's header - a few small reads, nothing decoded -\n * for PNG, JPEG and WebP (by their bytes, whatever the file's type says). undefined for any\n * other format, a header that does not add up, or a file that cannot be read: the caller then\n * goes by the bytes alone. Never throws.\n */\nexport const imageSizeOf = async (file: Blob): Promise<ImageSize | undefined> => {\n let at = 0\n let buf = new Uint8Array(0)\n /** `length` bytes from `start` (a 64 KB window is read at a time), or undefined past the end. */\n const read = async (start: number, length: number): Promise<Uint8Array | undefined> => {\n if (start < 0 || start + length > file.size) return undefined\n if (start < at || start + length > at + buf.length) {\n at = start\n buf = new Uint8Array(\n await file\n .slice(start, Math.min(file.size, start + Math.max(WINDOW, length)))\n .arrayBuffer(),\n )\n }\n return buf.subarray(start - at, start - at + length)\n }\n const sized = (width: number, height: number): ImageSize | undefined =>\n width > 0 && height > 0 ? { width, height } : undefined\n try {\n const head = await read(0, 30)\n if (!head) return undefined\n const u16be = (b: Uint8Array, i: number) => (b[i]! << 8) | b[i + 1]!\n const u32be = (b: Uint8Array, i: number) => u16be(b, i) * 0x10000 + u16be(b, i + 2)\n const ascii = (b: Uint8Array, i: number, n: number) =>\n String.fromCharCode(...Array.from(b.subarray(i, i + n)))\n // PNG: the signature, then IHDR - always the first chunk.\n if (ascii(head, 1, 3) === 'PNG' && head[0] === 0x89 && ascii(head, 12, 4) === 'IHDR')\n return sized(u32be(head, 16), u32be(head, 20))\n // WebP: RIFF … WEBP, then its first chunk - lossy (VP8), lossless (VP8L) or extended (VP8X).\n if (ascii(head, 0, 4) === 'RIFF' && ascii(head, 8, 4) === 'WEBP') {\n const chunk = ascii(head, 12, 4)\n const u16le = (i: number) => head[i]! | (head[i + 1]! << 8)\n const u24le = (i: number) => u16le(i) | (head[i + 2]! << 16)\n if (chunk === 'VP8X') return sized(u24le(24) + 1, u24le(27) + 1)\n if (chunk === 'VP8L' && head[20] === 0x2f) {\n const bits = (u16le(21) | (u16le(23) << 16)) >>> 0\n return sized((bits & 0x3fff) + 1, ((bits >>> 14) & 0x3fff) + 1)\n }\n if (chunk === 'VP8 ' && head[23] === 0x9d && head[24] === 0x01 && head[25] === 0x2a)\n return sized(u16le(26) & 0x3fff, u16le(28) & 0x3fff)\n return undefined\n }\n // JPEG: walk the segments (EXIF, XMP, ICC… each up to 64 KB, any number) to the frame header.\n if (head[0] === 0xff && head[1] === 0xd8) {\n let p = 2\n for (let segments = 0; segments < 4096; segments++) {\n const m = await read(p, 4)\n if (!m || m[0] !== 0xff) return undefined\n const marker = m[1]!\n if (marker === 0xff) {\n p += 1 // a fill byte\n continue\n }\n if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {\n p += 2 // a marker without a length\n continue\n }\n if (marker === 0xd9 || marker === 0xda) return undefined // image data before any frame\n const length = u16be(m, 2)\n if (length < 2) return undefined\n if (SOF.has(marker)) {\n const frame = await read(p + 4, 5)\n return frame ? sized(u16be(frame, 3), u16be(frame, 1)) : undefined\n }\n p += 2 + length\n }\n }\n return undefined\n } catch {\n return undefined\n }\n}\n\n/** The image, smaller when it is larger than the limits; the original otherwise. */\nexport const downscaleImage = async (file: Blob, opts: DownscaleOptions = {}): Promise<Blob> => {\n const maxDimension = opts.maxDimension ?? 1568\n const maxPixels = opts.maxPixels ?? 1_150_000\n if (\n typeof createImageBitmap !== 'function' ||\n !file.type.startsWith('image/') ||\n file.type === 'image/gif' ||\n file.type === 'image/svg+xml'\n ) {\n return file\n }\n let bitmap: ImageBitmap\n try {\n bitmap = await createImageBitmap(file)\n } catch {\n return file // a format the browser can't decode: send it as it is\n }\n const { width, height } = bitmap\n const scale = Math.min(\n 1,\n maxDimension / Math.max(width, height),\n Math.sqrt(maxPixels / Math.max(1, width * height)),\n )\n if (scale >= 1) {\n bitmap.close()\n return file\n }\n const w = Math.max(1, Math.round(width * scale))\n const h = Math.max(1, Math.round(height * scale))\n const canvas = canvasOf(w, h)\n const ctx = canvas?.getContext('2d') as\n OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D | null | undefined\n if (!canvas || !ctx) {\n bitmap.close()\n return file\n }\n ctx.drawImage(bitmap, 0, 0, w, h)\n bitmap.close()\n // Screenshots (PNG) stay lossless so text stays readable; photos go to JPEG.\n const type = file.type === 'image/png' || file.type === 'image/webp' ? file.type : 'image/jpeg'\n const out = await toBlob(canvas, type, opts.quality ?? 0.9)\n return out && out.size < file.size ? out : file\n}\n","/** Compact one-line preview of a tool input/output value, truncated. */\nexport const previewValue = (value: unknown, max = 140): string => {\n if (value === undefined) return ''\n let text: string\n if (typeof value === 'string') text = value\n else {\n try {\n text = JSON.stringify(value)\n } catch {\n text = String(value)\n }\n }\n text = text.replace(/\\s+/g, ' ').trim()\n return text.length > max ? `${text.slice(0, max - 1)}…` : text\n}\n\n/** 1234 → \"1.2k\", 12345 → \"12k\". */\nexport const formatTokens = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n)\n\n/** 340 → \"340 ms\", 4200 → \"4.2 s\", 125_000 → \"2m 5s\". */\nexport const formatDuration = (ms: number): string => {\n if (ms < 1000) return `${Math.round(ms)} ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)} s`\n const s = Math.round(ms / 1000)\n return `${Math.floor(s / 60)}m ${s % 60}s`\n}\n\nconst isDataImage = (v: unknown): v is string =>\n typeof v === 'string' && /^data:image\\/[\\w.+-]+;base64,/.test(v)\n\n/**\n * Images inside a tool result, as data URLs: MCP image parts\n * (`{ type: 'image', data, mimeType }`), data-URL strings, and objects that\n * carry one (`{ dataUrl }` / `{ url: 'data:…' }`). Looks two levels deep.\n */\nexport const imagesInOutput = (output: unknown, depth = 0): string[] => {\n if (depth > 2 || output == null) return []\n if (isDataImage(output)) return [output]\n if (Array.isArray(output)) return output.flatMap((v) => imagesInOutput(v, depth + 1))\n if (typeof output === 'object') {\n const o = output as Record<string, unknown>\n if (o.type === 'image' && typeof o.data === 'string') {\n const mime = typeof o.mimeType === 'string' ? o.mimeType : 'image/png'\n return [o.data.startsWith('data:') ? o.data : `data:${mime};base64,${o.data}`]\n }\n for (const key of ['dataUrl', 'url', 'image'])\n if (isDataImage(o[key])) return [o[key] as string]\n if (depth < 2) return Object.values(o).flatMap((v) => imagesInOutput(v, depth + 1))\n }\n return []\n}\n\n/** One result of the core's `web_search` tool, as far as a UI shows it. */\nexport interface WebSearchResultView {\n title: string\n /** An http(s) address - anything else is left out. */\n url: string\n /** The host of `url`, for the line under the title. */\n host: string\n snippet: string\n date?: string\n}\n\nexport interface WebSearchView {\n query: string\n results: WebSearchResultView[]\n /** Results the egress policy left out. */\n filtered: number\n truncated: boolean\n}\n\nconst text = (v: unknown, max: number): string =>\n typeof v === 'string' ? v.replace(/\\s+/g, ' ').trim().slice(0, max) : ''\n\n/**\n * The result of the core's `web_search` tool (`{ query, results: [{ title, url, snippet, date? }],\n * filtered?, truncated?, untrusted: true }`), or undefined when `output` is not one. Titles and\n * snippets are third-party text: they come back as plain strings, to be rendered as text. A\n * result whose `url` is not http(s) is dropped, so a link can never be a `javascript:` one.\n */\nexport const webSearchOf = (output: unknown): WebSearchView | undefined => {\n let value = output\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const o = value as Record<string, unknown>\n if (typeof o.query !== 'string' || !Array.isArray(o.results)) return undefined\n const results: WebSearchResultView[] = []\n for (const r of o.results.slice(0, 10)) {\n if (!r || typeof r !== 'object') continue\n const item = r as Record<string, unknown>\n if (typeof item.url !== 'string') continue\n let url: URL\n try {\n url = new URL(item.url)\n } catch {\n continue\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') continue\n const date = text(item.date, 40)\n results.push({\n title: text(item.title, 200) || url.host,\n url: url.href,\n host: url.host,\n snippet: text(item.snippet, 400),\n ...(date ? { date } : {}),\n })\n }\n return {\n query: text(o.query, 300),\n results,\n filtered: typeof o.filtered === 'number' && o.filtered > 0 ? o.filtered : 0,\n truncated: o.truncated === true,\n }\n}\n\n/** 0.934 → \"0.93\", 0.8 → \"0.8\", 1 → \"1\". */\nexport const formatProbability = (p: number): string => String(Math.round(p * 100) / 100)\n","import type {\n ToolApprovalContext,\n ToolApprovalDecision,\n ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\n\n/** The consent requests waiting for a person, by request id. */\nexport interface ApprovalQueue {\n /**\n * The core's `toolApproval.onRequest`: resolves when `approve` / `deny` is called. A request\n * the core stops waiting for (`ctx.signal`: its `timeoutMs` ran out, the run stopped) leaves\n * the queue at once, so no stale answer is kept for it.\n */\n handler: (req: ToolApprovalRequest, ctx?: ToolApprovalContext) => Promise<ToolApprovalDecision>\n /** Allow one. False when no such request is waiting (answered, expired, settled). */\n approve: (id: string, options?: { remember?: boolean }) => boolean\n /** Deny one. False when no such request is waiting. */\n deny: (id: string, reason?: string) => boolean\n /** Answer every waiting request with `decision` (the run ended, the view closed). */\n settleAll: (decision: ToolApprovalDecision) => void\n /** The ids of the requests waiting, oldest first. */\n pending: () => string[]\n}\n\n/**\n * The queue behind `useAgent`'s `approve` / `deny`: `request.id → resolver`. A request leaves it\n * exactly once - answered, settled by `settleAll`, or dropped when the core no longer wants the\n * answer (its signal aborted; the core has already denied the call and said so in its event).\n */\nexport const createApprovalQueue = (): ApprovalQueue => {\n const waiting = new Map<string, (decision: ToolApprovalDecision) => void>()\n\n const handler: ApprovalQueue['handler'] = (req, ctx) =>\n new Promise<ToolApprovalDecision>((resolve) => {\n const signal = ctx?.signal\n if (signal?.aborted) {\n resolve({ approved: false, reason: 'no longer asked' })\n return\n }\n const onAbort = (): void => {\n if (waiting.get(req.id) !== settle) return\n settle({ approved: false, reason: 'no longer asked' })\n }\n // Called only for the request in the map (every caller looks it up first): exactly once.\n const settle = (decision: ToolApprovalDecision): void => {\n waiting.delete(req.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(decision)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n waiting.set(req.id, settle)\n })\n\n const answer = (id: string, decision: ToolApprovalDecision): boolean => {\n const settle = waiting.get(id)\n if (!settle) return false\n settle(decision)\n return true\n }\n\n return {\n handler,\n approve: (id, options) => answer(id, { approved: true, remember: options?.remember }),\n deny: (id, reason) => answer(id, { approved: false, reason }),\n settleAll: (decision) => {\n for (const settle of [...waiting.values()]) settle(decision)\n },\n pending: () => [...waiting.keys()],\n }\n}\n","import type {\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './mcp-types.js'\n\n/**\n * MCP elicitation, the part of it that is not React: what a field of a server's form is drawn\n * as, what the user typed turned into the answer, the checks an answer must pass before it is\n * sent (the core's own rules, so the form says what is wrong instead of the tool call failing),\n * what a link may be opened as, and the queue of questions waiting for the user.\n *\n * Pure, and free of the MCP SDK and of the core's `./mcp` subpath: the prompt is in the main\n * entry of this package, the hooks that fill the queue are in `./mcp`.\n *\n * Nothing here keeps, logs or returns a value the user entered except to the one caller that\n * hands it to the server: an issue names the field and the rule, never the value.\n */\n\n// ── a question waiting for the user ──────────────────────────────────────\n\n/**\n * A question waiting for the user: the core's request (every string in it is the SERVER's\n * text), and when the core will stop waiting for the answer.\n */\nexport interface PendingElicitation extends McpElicitationRequest {\n /** Epoch ms after which the core cancels the question by itself; absent when it has no limit. */\n expiresAt?: number\n}\n\n/** The core's default for `elicitation.timeoutMs` (`MCP_ELICITATION_TIMEOUT_MS`). */\nexport const ELICITATION_TIMEOUT_MS = 300_000\n\n/**\n * The hooks' `elicitation` option as the core's settings, or `undefined` when it is off - and\n * then NOTHING is passed to the core: no capability is declared and the wire is what it was.\n */\nexport const elicitationSettings = (\n option: boolean | McpElicitationOptions | undefined | null,\n): McpElicitationOptions | undefined => {\n if (option === true) return {}\n if (typeof option === 'object' && option !== null) return { ...option }\n return undefined\n}\n\n/**\n * What the hooks add to the options of the core's `connectMcpHttp`: the handler and the\n * settings when elicitation is on, and NOTHING - not even the keys - when it is off.\n */\nexport const elicitationConnectOptions = (\n option: boolean | McpElicitationOptions | undefined | null,\n handler: McpElicitationHandler,\n): { onElicitation?: McpElicitationHandler; elicitation?: McpElicitationOptions } => {\n const settings = elicitationSettings(option)\n return settings ? { onElicitation: handler, elicitation: settings } : {}\n}\n\n/** The longest wait a timer holds (2^31 - 1 ms); the core takes a longer `timeoutMs` as none. */\nconst TIMER_MAX_MS = 2_147_483_647\n\n/**\n * How long the core waits for an answer with these settings; `undefined` = no limit of its own\n * (`0`, `Infinity`, more than a timer holds - the core's own rules).\n */\nexport const elicitationTimeoutOf = (settings: McpElicitationOptions): number | undefined => {\n const raw = settings.timeoutMs\n if (raw === undefined || raw === null) return ELICITATION_TIMEOUT_MS\n if (typeof raw !== 'number' || !(raw > 0) || raw > TIMER_MAX_MS) return undefined\n return Math.max(1, Math.floor(raw))\n}\n\nexport interface ElicitationQueueOptions {\n /**\n * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read\n * when a question arrives (the settings of the connection that is open then).\n */\n timeoutMs?: number | (() => number | undefined)\n /** Called whenever the list of pending questions changed. */\n onChange?: (pending: PendingElicitation[]) => void\n /** The clock (tests). */\n now?: () => number\n}\n\nexport interface ElicitationQueue {\n /** The core's `onElicitation`: resolves when the user answers, or as `cancel`. */\n handler: McpElicitationHandler\n /** The questions waiting, oldest first. */\n pending: () => PendingElicitation[]\n /** Answer one. False when no such question is waiting (answered, expired, cancelled). */\n answer: (id: string, result: McpElicitationResult) => boolean\n /** Cancel the waiting questions - all of them, or those `match` picks (one server's). */\n cancel: (match?: (request: PendingElicitation) => boolean) => void\n /** Cancel everything and stop reporting: the owner is gone. A later question is cancelled at once. */\n dispose: () => void\n}\n\n/**\n * The questions MCP servers are waiting on: `request.id → resolver`. A question leaves the queue\n * exactly once - answered by the user, cancelled because the core no longer wants the answer\n * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (a disconnect, an\n * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.\n */\nexport const createElicitationQueue = (options: ElicitationQueueOptions = {}): ElicitationQueue => {\n const now = options.now ?? Date.now\n const waiting = new Map<\n string,\n { request: PendingElicitation; settle: (result: McpElicitationResult) => void }\n >()\n let disposed = false\n\n const list = (): PendingElicitation[] => [...waiting.values()].map((w) => w.request)\n const changed = (): void => {\n if (!disposed) options.onChange?.(list())\n }\n\n const handler: McpElicitationHandler = (request, ctx) =>\n new Promise<McpElicitationResult>((resolve) => {\n const signal = ctx?.signal\n // Nobody to ask, or nobody wants the answer any more.\n if (disposed || signal?.aborted || waiting.has(request.id)) {\n resolve({ action: 'cancel' })\n return\n }\n // The core no longer wants the answer: its time ran out, or the run stopped.\n const onAbort = (): void => {\n if (waiting.get(request.id)?.settle !== settle) return\n settle({ action: 'cancel' })\n changed()\n }\n const settle = (result: McpElicitationResult): void => {\n // Exactly once: a second answer to the same question finds nothing to resolve.\n if (waiting.get(request.id)?.settle !== settle) return\n waiting.delete(request.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(result)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n const timeoutMs =\n typeof options.timeoutMs === 'function' ? options.timeoutMs() : options.timeoutMs\n waiting.set(request.id, {\n request: {\n ...request,\n ...(timeoutMs !== undefined ? { expiresAt: now() + timeoutMs } : {}),\n },\n settle,\n })\n changed()\n })\n\n return {\n handler,\n pending: list,\n answer: (id, result) => {\n const entry = waiting.get(id)\n if (!entry) return false\n entry.settle(result)\n changed()\n return true\n },\n cancel: (match) => {\n let any = false\n for (const entry of [...waiting.values()]) {\n if (match && !match(entry.request)) continue\n entry.settle({ action: 'cancel' })\n any = true\n }\n if (any) changed()\n },\n dispose: () => {\n disposed = true\n for (const entry of [...waiting.values()]) entry.settle({ action: 'cancel' })\n },\n }\n}\n\n// ── a form: fields, values, the answer ───────────────────────────────────\n\n/** What a field is drawn as. */\nexport type ElicitationControl =\n 'text' | 'email' | 'url' | 'date' | 'datetime' | 'number' | 'checkbox' | 'select' | 'multiselect'\n\nexport interface ElicitationOption {\n /** What goes back to the server, verbatim. */\n value: string\n /** What the user reads (the option's title, or the value). */\n label: string\n}\n\n/** One field of a form, ready to draw. `label`, `description` and option labels are the server's text. */\nexport interface ElicitationField {\n name: string\n label: string\n description?: string\n required: boolean\n control: ElicitationControl\n /** `select` / `multiselect`. */\n options?: ElicitationOption[]\n schema: McpElicitationFieldSchema\n}\n\n/** What the form holds while it is being filled in: text as typed, a tick, the ticked options. */\nexport type ElicitationDraftValue = string | boolean | string[]\nexport type ElicitationDraft = Record<string, ElicitationDraftValue>\n\nconst titled = (options: { const: string; title: string }[]): ElicitationOption[] =>\n options.map((o) => ({ value: o.const, label: o.title || o.const }))\n\n/** The options of a select, in the three forms the core lets through. */\nconst optionsOf = (schema: McpElicitationFieldSchema): ElicitationOption[] | undefined => {\n if (schema.type === 'array') {\n const items = schema.items\n if (items?.anyOf) return titled(items.anyOf)\n return (items?.enum ?? []).map((value) => ({ value, label: value }))\n }\n if (schema.type !== 'string') return undefined\n if (schema.oneOf) return titled(schema.oneOf)\n if (schema.enum) {\n const names = schema.enumNames\n return schema.enum.map((value, i) => ({ value, label: names?.[i] || value }))\n }\n return undefined\n}\n\nconst controlOf = (schema: McpElicitationFieldSchema): ElicitationControl => {\n switch (schema.type) {\n case 'boolean':\n return 'checkbox'\n case 'number':\n case 'integer':\n return 'number'\n case 'array':\n return 'multiselect'\n default:\n if (schema.enum || schema.oneOf) return 'select'\n switch (schema.format) {\n case 'email':\n return 'email'\n case 'uri':\n return 'url'\n case 'date':\n return 'date'\n case 'date-time':\n return 'datetime'\n default:\n return 'text'\n }\n }\n}\n\n/**\n * The fields of a form in the order the server listed them - exactly the set the core's schema\n * guard lets through: a text (plain, email, uri, date, date-time), a number / integer, a\n * boolean, a single select (`enum`, `enum` + `enumNames`, `oneOf`) and a multi-select (an array\n * of `enum` or `anyOf` options).\n */\nexport const elicitationFields = (schema: McpElicitationSchema | undefined): ElicitationField[] => {\n const required = new Set(schema?.required ?? [])\n return Object.entries(schema?.properties ?? {}).map(([name, field]) => {\n const options = optionsOf(field)\n return {\n name,\n label: field.title || name,\n ...(field.description ? { description: field.description } : {}),\n required: required.has(name),\n control: controlOf(field),\n ...(options ? { options } : {}),\n schema: field,\n }\n })\n}\n\nconst pad = (n: number): string => String(n).padStart(2, '0')\n\n// A date-time default as `<input type=\"datetime-local\">` wants it (local time, to the minute).\nconst toLocalInput = (value: string): string => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return ''\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/** What the form starts with: the schema's defaults (the core dropped the ones that do not fit). */\nexport const elicitationInitialDraft = (\n schema: McpElicitationSchema | undefined,\n): ElicitationDraft => {\n const draft: ElicitationDraft = {}\n for (const field of elicitationFields(schema)) {\n const preset = field.schema.default\n switch (field.control) {\n case 'checkbox':\n draft[field.name] = preset === true\n break\n case 'multiselect':\n draft[field.name] = Array.isArray(preset) ? [...preset] : []\n break\n case 'number':\n draft[field.name] = typeof preset === 'number' ? String(preset) : ''\n break\n case 'datetime':\n draft[field.name] = typeof preset === 'string' ? toLocalInput(preset) : ''\n break\n default:\n draft[field.name] = typeof preset === 'string' ? preset : ''\n }\n }\n return draft\n}\n\n/** The rules an answer can break. An issue never carries the value. */\nexport type ElicitationIssueKind =\n | 'required'\n | 'tooShort'\n | 'tooLong'\n | 'email'\n | 'uri'\n | 'date'\n | 'dateTime'\n | 'notNumber'\n | 'notInteger'\n | 'belowMinimum'\n | 'aboveMaximum'\n | 'notAnOption'\n | 'tooFew'\n | 'tooMany'\n\nexport interface ElicitationIssue {\n kind: ElicitationIssueKind\n /** The limit the rule states (a length, a bound, a count), when it has one. */\n limit?: number\n}\n\n/** The longest text a field without its own `maxLength` takes (the core's cap). */\nexport const ELICITATION_VALUE_MAX_CHARS = 10_000\n/** The most options one multi-select may be answered with (the core's cap). */\nexport const ELICITATION_MAX_OPTIONS = 100\n\n// A number as a person types it: digits, a sign, a decimal point, an exponent. `Number('')` is\n// 0 and `Number(' 1 ')` is 1, so the text is checked first.\nconst NUMBER = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)(e[+-]?\\d+)?$/i\n\nconst numberOf = (text: string): number | undefined => {\n const trimmed = text.trim()\n if (!NUMBER.test(trimmed)) return undefined\n const n = Number(trimmed)\n return Number.isFinite(n) ? n : undefined\n}\n\n// The core's `validFormat`, rule for rule.\nconst formatIssue = (\n format: McpElicitationFieldSchema['format'],\n value: string,\n): ElicitationIssueKind | undefined => {\n switch (format) {\n case 'email':\n return /^[^@\\s]+@[^@\\s]+$/.test(value) ? undefined : 'email'\n case 'uri':\n try {\n return new URL(value) ? undefined : 'uri'\n } catch {\n return 'uri'\n }\n case 'date':\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'date'\n case 'date-time':\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'dateTime'\n default:\n return undefined\n }\n}\n\n// A date-time goes back as RFC 3339 with its offset (UTC): the input's value is local time\n// without one, which a server could read as any zone.\nconst dateTimeOf = (value: string): string => {\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? value : date.toISOString()\n}\n\ntype FieldAnswer =\n { issue: ElicitationIssue } | { value: string | number | boolean | string[] } | { empty: true }\n\n// One field: its value as the server gets it, why it does not fit, or \"left empty\".\nconst answerOf = (field: ElicitationField, raw: ElicitationDraftValue | undefined): FieldAnswer => {\n const { schema } = field\n switch (field.control) {\n case 'checkbox':\n // A tick box always has a value: unticked is `false`, which is an answer.\n return { value: raw === true }\n case 'multiselect': {\n const picked = Array.isArray(raw) ? raw : []\n // Nothing ticked in an optional list is \"not answered\", as an empty text is.\n if (picked.length === 0 && !field.required) return { empty: true }\n const allowed = new Set((field.options ?? []).map((o) => o.value))\n if (!picked.every((item) => allowed.has(item))) return { issue: { kind: 'notAnOption' } }\n if (schema.minItems !== undefined && picked.length < schema.minItems) {\n return { issue: { kind: 'tooFew', limit: schema.minItems } }\n }\n const max = Math.min(schema.maxItems ?? ELICITATION_MAX_OPTIONS, ELICITATION_MAX_OPTIONS)\n if (picked.length > max) return { issue: { kind: 'tooMany', limit: max } }\n return { value: [...picked] }\n }\n case 'number': {\n const text = typeof raw === 'string' ? raw.trim() : ''\n if (!text) return { empty: true }\n const n = numberOf(text)\n if (n === undefined) return { issue: { kind: 'notNumber' } }\n if (schema.type === 'integer' && !Number.isInteger(n)) {\n return { issue: { kind: 'notInteger' } }\n }\n if (schema.minimum !== undefined && n < schema.minimum) {\n return { issue: { kind: 'belowMinimum', limit: schema.minimum } }\n }\n if (schema.maximum !== undefined && n > schema.maximum) {\n return { issue: { kind: 'aboveMaximum', limit: schema.maximum } }\n }\n return { value: n }\n }\n case 'select': {\n const text = typeof raw === 'string' ? raw : ''\n if (!text) return { empty: true }\n return (field.options ?? []).some((o) => o.value === text)\n ? { value: text }\n : { issue: { kind: 'notAnOption' } }\n }\n default: {\n const typed = typeof raw === 'string' ? raw : ''\n if (!typed) return { empty: true }\n const text = field.control === 'datetime' ? dateTimeOf(typed) : typed\n const max = schema.maxLength ?? ELICITATION_VALUE_MAX_CHARS\n if (text.length > max) return { issue: { kind: 'tooLong', limit: max } }\n if (schema.minLength !== undefined && text.length < schema.minLength) {\n return { issue: { kind: 'tooShort', limit: schema.minLength } }\n }\n const format = formatIssue(schema.format, text)\n return format ? { issue: { kind: format } } : { value: text }\n }\n }\n}\n\nexport type ElicitationFormOutcome =\n | { ok: true; content: Record<string, string | number | boolean | string[]> }\n | { ok: false; issues: Record<string, ElicitationIssue> }\n\n/**\n * A filled-in form as the answer the core will accept, or what is wrong with it, per field. The\n * rules are the core's (`validateMcpElicitationContent`): a required field is there, every\n * value is of its field's type and within its limits, and nothing the form did not ask for is\n * sent. A field left empty is left out, not sent as an empty text.\n */\nexport const elicitationFormAnswer = (\n schema: McpElicitationSchema | undefined,\n draft: ElicitationDraft,\n): ElicitationFormOutcome => {\n const content: Record<string, string | number | boolean | string[]> = {}\n const issues: Record<string, ElicitationIssue> = {}\n for (const field of elicitationFields(schema)) {\n const answer = answerOf(field, Object.hasOwn(draft, field.name) ? draft[field.name] : undefined)\n if ('issue' in answer) {\n issues[field.name] = answer.issue\n } else if ('empty' in answer) {\n if (field.required) issues[field.name] = { kind: 'required' }\n } else {\n content[field.name] = answer.value\n }\n }\n return Object.keys(issues).length > 0 ? { ok: false, issues } : { ok: true, content }\n}\n\n// ── a link ───────────────────────────────────────────────────────────────\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\nexport interface ElicitationLink {\n /** The host the link leads to (with its port), as the browser will resolve it; '' if unparseable. */\n host: string\n /** The whole link as text: the parsed form when it parses, what the server sent otherwise. */\n href: string\n /** Whether an \"Open\" action may exist for it: https, or http on a loopback host, no credentials. */\n openable: boolean\n}\n\n/**\n * A link a server wants the user to open, as the prompt may show it. The core already refuses\n * anything but https (http on loopback); this is the same rule applied again where the link is\n * about to be opened, because a host may hand the prompt a request the core never checked.\n */\nexport const elicitationLink = (raw: unknown): ElicitationLink => {\n const text = typeof raw === 'string' ? raw : ''\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return { host: '', href: text, openable: false }\n }\n const secure =\n url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n return {\n host: url.host,\n href: url.href,\n openable: secure && !url.username && !url.password && !/\\s/.test(text),\n }\n}\n\n// ── an answer nobody gave ────────────────────────────────────────────────\n\n/**\n * Why a question was answered without anybody deciding: the core's reasons\n * (`mcp.elicitation-answered` with `automatic: true`), and `stopped`, which the reducer sets on\n * whatever was still waiting when the run stopped.\n */\nexport type ElicitationOutcomeReason =\n | 'timeout'\n | 'step-timeout'\n | 'aborted'\n | 'stopped'\n | 'cap-per-call'\n | 'cap-per-run'\n | 'unsupported-schema'\n | 'unsupported-mode'\n | 'insecure-url'\n | 'invalid-request'\n | 'subagent'\n | 'handler-error'\n | 'invalid-answer'\n | 'after-failure'\n | 'no-tool-call'\n\n/** \"4:05\" - what is left of a question's time. */\nexport const formatCountdown = (ms: number): string => {\n const total = Math.max(0, Math.ceil(ms / 1000))\n return `${Math.floor(total / 60)}:${pad(total % 60)}`\n}\n","/**\n * Input protection for the buttons that SAY YES to an MCP App (its tool call's \"Allow once\" /\n * \"Always allow\", a link's \"Open\", a file's \"Save\", sampling's \"Allow\"): the way a browser's own\n * permission prompts guard theirs. A prompt an app causes appears when the APP chooses - while\n * the person types, holds a key or double-clicks something in the app - and where its layout\n * puts it, so an input aimed at something else must not land on \"yes\".\n *\n * A button is ARMED only once it has been on screen, in one place, for `PROMPT_ARM_MS`; it is\n * disarmed again the moment it moves, is covered, leaves the screen or the page is hidden. A\n * click counts only when it is armed now AND began while it was armed: its pointerdown (a\n * pointer's click) or its Enter / Space keydown (a key's) came after the arming. A key repeat\n * never counts, and a keydown that does not count is swallowed. A click with no key and no\n * pointer behind it (assistive technology activating the button) counts when it is armed.\n *\n * Pure: the clock and the button's place are passed in (`ArmedButton` reads them from the DOM).\n */\n\n/** How long a button must have been shown, still, before it takes a click. */\nexport const PROMPT_ARM_MS = 500\n\nexport interface PromptArming {\n /** Armed now. */\n readonly armed: boolean\n /**\n * One look at the button: where it is on screen (any string that changes when it moves), or\n * `undefined` when it is not shown (off screen, covered, the page hidden). Returns `armed`.\n */\n sample: (where: string | undefined, now: number) => boolean\n /** A pointer went down on the button. */\n pointerDown: (at: number) => void\n /** A key went down on the button. False: swallow it (`preventDefault`) - it must not act. */\n keyDown: (key: { key: string; repeat: boolean }, at: number) => boolean\n /** A click reached the button (`detail` > 0 for a pointer's). True: it may act. */\n click: (detail: number, now: number) => boolean\n}\n\nconst ACTIVATING_KEYS = new Set(['Enter', ' ', 'Spacebar'])\n\nexport const createPromptArming = (delayMs: number = PROMPT_ARM_MS): PromptArming => {\n const delay = Number.isFinite(delayMs) && delayMs >= 0 ? delayMs : PROMPT_ARM_MS\n let where: string | undefined\n // When it came to where it is; when it was armed (Infinity: it is not).\n let since = 0\n let armedAt = Number.POSITIVE_INFINITY\n // The press behind the next click: a pointer's, a key's.\n let downAt = Number.NEGATIVE_INFINITY\n let key: 'none' | 'counts' | 'blocked' = 'none'\n let keyAt = Number.NEGATIVE_INFINITY\n return {\n get armed() {\n return armedAt !== Number.POSITIVE_INFINITY\n },\n sample(next, now) {\n if (next === undefined || next !== where) {\n where = next\n since = now\n armedAt = Number.POSITIVE_INFINITY\n return false\n }\n if (armedAt === Number.POSITIVE_INFINITY && now - since >= delay) armedAt = now\n return armedAt !== Number.POSITIVE_INFINITY\n },\n pointerDown(at) {\n downAt = at\n },\n keyDown(k, at) {\n if (!ACTIVATING_KEYS.has(k.key)) return true\n if (k.repeat || at < armedAt) {\n key = 'blocked'\n keyAt = at\n return false\n }\n key = 'counts'\n keyAt = at\n return true\n },\n click(detail, now) {\n const armedNow = armedAt <= now\n const ok =\n detail > 0\n ? armedNow && downAt >= armedAt\n : armedNow && (key === 'none' || (key === 'counts' && keyAt >= armedAt))\n downAt = Number.NEGATIVE_INFINITY\n key = 'none'\n return ok\n },\n }\n}\n","import * as core from '@dudko.dev/agent-web'\nimport type { IUsage } from '@dudko.dev/agent-web'\nimport type { ChatAttachment, ChatMessage } from './types.js'\n\n/**\n * Saved conversations — the transcript a chat UI shows (messages with their\n * tool calls, usage and image attachments), one record per conversation. The\n * agent's own memory (what the MODEL sees) lives in the core's ContextStore\n * under the same id; keep both and a reloaded chat continues where it was.\n */\nexport interface ChatRecord {\n /** Also the agent's memory session id. */\n id: string\n title: string\n createdAt: number\n updatedAt: number\n messages: ChatMessage[]\n totalUsage?: IUsage\n}\n\n/** A list entry (no messages). */\nexport type ChatSummary = Omit<ChatRecord, 'messages'> & { messageCount: number }\n\nexport interface ChatHistoryStoreOptions {\n /** IndexedDB database (default 'agent-web-react'). */\n dbName?: string\n /** Object store (default 'chats'). */\n storeName?: string\n /** Keep chats in memory only (tests, private mode; also the fallback without IndexedDB). */\n memory?: boolean\n}\n\nconst DB_VERSION = 1\n\nconst req = <T>(r: IDBRequest<T>): Promise<T> =>\n new Promise((resolve, reject) => {\n r.onsuccess = () => resolve(r.result)\n r.onerror = () => reject(r.error)\n })\n\n/**\n * A write, settled when its transaction COMMITTED (a request's success comes before that: the\n * transaction can still abort). Only then may the other tabs be told.\n */\nconst committed = (tx: IDBTransaction, r: IDBRequest): Promise<void> =>\n new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve()\n tx.onabort = () => reject(tx.error ?? r.error ?? new Error('the transaction was aborted'))\n tx.onerror = () => reject(tx.error ?? r.error)\n })\n\n/**\n * IndexedDB-backed chat history (raw IndexedDB — no extra dependency). Every tab of the origin\n * shares it: once a write has committed the other tabs hear which chat changed (a `chats`\n * notice from the core's `postStorageChange` - the id, never a message), and `useChatHistory`\n * there refreshes.\n */\nexport class ChatHistoryStore {\n /** The IndexedDB database (undefined in memory): the name its `chats` notices go out under. */\n readonly dbName: string | undefined\n private readonly name: string\n private readonly storeName: string\n private readonly memory?: Map<string, ChatRecord>\n private db?: Promise<IDBDatabase>\n\n constructor(opts: ChatHistoryStoreOptions = {}) {\n this.name = opts.dbName ?? 'agent-web-react'\n this.storeName = opts.storeName ?? 'chats'\n if (opts.memory || typeof indexedDB === 'undefined') this.memory = new Map()\n this.dbName = this.memory ? undefined : this.name\n }\n\n /**\n * The store's connection, opened on first use. Never in another tab's way: when another\n * connection asks to delete or upgrade the database (`versionchange` - another tab's\n * `indexedDB.deleteDatabase`, a newer copy of this package), it is closed at once, so that\n * request goes ahead instead of waiting for this tab to close; one the browser closed by itself\n * (site data cleared) is let go too. The next use opens the database again - after a deletion a\n * new, empty one (no chats: `list()` is empty, a save starts it again); after an upgrade by a\n * newer copy, the open fails until the page is reloaded with that copy.\n */\n private open(): Promise<IDBDatabase> {\n if (this.db) return this.db\n const opening: Promise<IDBDatabase> = new Promise<IDBDatabase>((resolve, reject) => {\n const r = indexedDB.open(this.name, DB_VERSION)\n r.onupgradeneeded = () => {\n if (!r.result.objectStoreNames.contains(this.storeName)) {\n r.result.createObjectStore(this.storeName, { keyPath: 'id' })\n }\n }\n r.onsuccess = () => {\n const db = r.result\n const forget = () => {\n if (this.db === opening) this.db = undefined\n }\n // Listeners, not `onversionchange` / `onclose`: a host's own handler on the connection\n // is not replaced, and cannot replace these.\n db.addEventListener('versionchange', () => {\n forget()\n db.close()\n })\n db.addEventListener('close', forget)\n resolve(db)\n }\n r.onerror = () => reject(r.error)\n }).catch((err: unknown) => {\n if (this.db === opening) this.db = undefined\n throw err\n })\n this.db = opening\n return opening\n }\n\n private async tx(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open()\n return db.transaction(this.storeName, mode).objectStore(this.storeName)\n }\n\n /** One write in its own transaction, resolved once it committed - then the notice. */\n private async write(\n op: (store: IDBObjectStore) => IDBRequest,\n notice: { op: 'put' | 'delete' | 'clear'; key?: string },\n ): Promise<void> {\n const db = await this.open()\n const tx = db.transaction(this.storeName, 'readwrite')\n await committed(tx, op(tx.objectStore(this.storeName)))\n this.announce(notice)\n }\n\n private announce(notice: { op: 'put' | 'delete' | 'clear'; key?: string }): void {\n if (typeof core.postStorageChange === 'function') {\n core.postStorageChange(this.dbName, { kind: 'chats', ...notice })\n }\n }\n\n /**\n * Read the stored record and write what `merge` makes of it in ONE readwrite transaction: no\n * other tab's save can land between the read and the write. `merge` is synchronous (a\n * transaction does not survive an await). Resolves with what was written, once committed.\n */\n async putMerged(\n id: string,\n merge: (stored: ChatRecord | undefined) => ChatRecord,\n ): Promise<ChatRecord> {\n if (this.memory) {\n const record = merge(this.memory.get(id))\n this.memory.set(record.id, structuredClone(record))\n return record\n }\n const db = await this.open()\n const tx = db.transaction(this.storeName, 'readwrite')\n const store = tx.objectStore(this.storeName)\n let written: ChatRecord | undefined\n let failed: unknown\n const read = store.get(id) as IDBRequest<ChatRecord | undefined>\n const done = committed(tx, read)\n read.onsuccess = () => {\n try {\n written = merge(read.result)\n store.put(written)\n } catch (err) {\n failed = err\n tx.abort()\n }\n }\n try {\n await done\n } catch (err) {\n throw failed ?? err\n }\n if (!written) throw new Error('the chat could not be saved')\n this.announce({ op: 'put', key: id })\n return written\n }\n\n async list(): Promise<ChatSummary[]> {\n const all = this.memory\n ? [...this.memory.values()]\n : await req((await this.tx('readonly')).getAll() as IDBRequest<ChatRecord[]>)\n return all\n .map(({ messages, ...rest }) => ({ ...rest, messageCount: messages.length }))\n .sort((a, b) => b.updatedAt - a.updatedAt)\n }\n\n async get(id: string): Promise<ChatRecord | undefined> {\n if (this.memory) return this.memory.get(id)\n return req((await this.tx('readonly')).get(id) as IDBRequest<ChatRecord | undefined>)\n }\n\n async put(record: ChatRecord): Promise<void> {\n if (this.memory) {\n this.memory.set(record.id, structuredClone(record))\n return\n }\n await this.write((store) => store.put(record), { op: 'put', key: record.id })\n }\n\n async delete(id: string): Promise<void> {\n if (this.memory) {\n this.memory.delete(id)\n return\n }\n await this.write((store) => store.delete(id), { op: 'delete', key: id })\n }\n\n async clear(): Promise<void> {\n if (this.memory) {\n this.memory.clear()\n return\n }\n await this.write((store) => store.clear(), { op: 'clear' })\n }\n}\n\n/** The words a chat's title and a message of attachments only are said with (`AgentLabels`'). */\nexport interface AttachmentTexts {\n /** A recording - audio attachments only (default \"Voice message\"). */\n voiceMessage?: string\n}\n\n/**\n * A message of attachments only, in words - where a text is needed (a chat's title, the name a\n * screen reader gives the message): `voiceMessage` when every attachment is audio (a voice\n * message), else the files' names.\n */\nexport const attachmentsText = (\n attachments: readonly ChatAttachment[],\n texts: AttachmentTexts = {},\n): string =>\n attachments.length > 0 && attachments.every((a) => a.mediaType.toLowerCase().startsWith('audio/'))\n ? (texts.voiceMessage ?? 'Voice message')\n : attachments.map((a) => a.name).join(', ')\n\nconst oneLine = (text: string | undefined): string => (text ?? '').replace(/\\s+/g, ' ').trim()\n\n/**\n * A chat's title: its first user message, trimmed. A first message of attachments only is named\n * by what was said in it once the run has transcribed it (the next answer's transcript of an\n * attachment), else by `attachmentsText` - \"Voice message\", or the files' names.\n */\nexport const chatTitle = (messages: ChatMessage[], texts: AttachmentTexts = {}): string => {\n const at = messages.findIndex((m) => m.role === 'user')\n const user = at >= 0 ? messages[at] : undefined\n let first = oneLine(user?.content)\n if (!first && user?.attachments?.length) {\n const answer = messages.slice(at + 1).find((m) => m.role === 'assistant')\n const heard = answer?.transcripts?.find((t) => t.source === 'attachment')?.text\n first = oneLine(heard) || oneLine(attachmentsText(user.attachments, texts))\n }\n if (!first) return 'New chat'\n return first.length > 60 ? `${first.slice(0, 59)}…` : first\n}\n\n/** A fresh, sortable conversation id (also a valid memory session id). */\nexport const newChatId = (): string =>\n `chat-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n\n// ── Two tabs, one chat: the merge of a save ─────────────────────────────────\n\nconst USAGE_KEYS = [\n 'inputTokens',\n 'outputTokens',\n 'totalTokens',\n 'reasoningTokens',\n 'cachedInputTokens',\n 'cacheWriteTokens',\n] as const\n\nconst sumUsage = (base: IUsage | undefined, more: (IUsage | undefined)[]): IUsage => {\n const out = { ...(base ?? {}) } as Record<string, number>\n for (const u of more) {\n if (!u) continue\n for (const k of USAGE_KEYS) out[k] = (out[k] ?? 0) + (u[k] ?? 0)\n }\n for (const k of USAGE_KEYS) out[k] ??= 0\n return out as unknown as IUsage\n}\n\n/** Ids for messages appended after `after`'s: past its highest `msg-<n>`, so none collide. */\nconst renumber = (own: ChatMessage[], after: ChatMessage[]): ChatMessage[] => {\n let next = after.reduce(\n (max, m) => Math.max(max, Number(/^msg-(\\d+)$/.exec(m.id)?.[1] ?? -1)),\n -1,\n )\n return own.map((m) => ({ ...m, id: `msg-${(next += 1)}` }))\n}\n\n/** When a message's turn began, if it says (a finite number: a record from elsewhere may not). */\nconst turnAt = (m: ChatMessage): number | undefined =>\n typeof m.startedAt === 'number' && Number.isFinite(m.startedAt) ? m.startedAt : undefined\n\n/**\n * The stored messages with this tab's own new ones (in their order) among them, each where its\n * turn belongs: after every stored message, except a stored turn that began LATER - another tab's,\n * run once this tab's had given the session back and saved first (this tab was frozen before its\n * save) - which it goes before. Only what the times tell: a stored message without one is never\n * passed (a chat saved before turns had times merges as it always did: this tab's own after it),\n * nor is one of the same time, and an own message without one goes after all that is stored. It\n * only inserts: nothing is dropped, doubled or moved among the stored ones.\n */\nconst placeByTurn = (stored: ChatMessage[], own: ChatMessage[]): ChatMessage[] => {\n // The stored messages that may be passed: those after the last one without a time.\n let i = stored.length\n while (i > 0 && turnAt(stored[i - 1]) !== undefined) i -= 1\n const out = stored.slice(0, i)\n for (const m of own) {\n const at = turnAt(m)\n // Every stored message up to the first whose turn began after this one's (all of them when\n // this one has no time). Past the last untimed one, each stored message has a time.\n while (i < stored.length && (at === undefined || turnAt(stored[i])! <= at)) {\n out.push(stored[i])\n i += 1\n }\n out.push(m)\n }\n return [...out, ...stored.slice(i)]\n}\n\n/** What this tab last read or wrote of a chat: the very message objects, and when. */\nexport interface ChatBase {\n /** The messages as read or written (by identity: an edit, a reset or a trim is not \"known\"). */\n known: ReadonlySet<ChatMessage>\n updatedAt: number\n}\n\n/** This tab's view holds a message of its own (not another tab's, relayed) it never read or wrote. */\nexport const ownUnsaved = (messages: ChatMessage[], base: ChatBase | undefined): boolean =>\n messages.some((m) => !m.remote && !base?.known.has(m))\n\n/** This tab's view says nothing new (every message is one it read or wrote). */\nexport const unchangedSince = (messages: ChatMessage[], base: ChatBase | undefined): boolean =>\n base !== undefined &&\n messages.length === base.known.size &&\n messages.every((m) => base.known.has(m))\n\n/**\n * The record to save. A turn this tab only followed from another tab (`remote`) is never saved\n * from here - that tab saves its own, unclipped copy. When another tab saved the chat after this\n * tab last read or wrote it (or saved a chat this tab never read), THAT record is the truth for\n * everything that is not this tab's own: this tab's own new messages - by identity, not by count,\n * so a reset or a trim here drops nothing there - go after it, each before a stored turn that\n * began after its own (`ChatMessage.startedAt`: this tab saved its turn late, after another tab\n * ran the next one and saved first). Without times, after it all.\n */\nexport const mergeChatRecord = (\n view: ChatRecord,\n stored: ChatRecord | undefined,\n base: ChatBase | undefined,\n /** The words of a title of attachments only (`chatTitle`). */\n texts?: AttachmentTexts,\n): { record: ChatRecord; merged: boolean } => {\n const local = view.messages.filter((m) => !m.remote)\n if (!stored || (base && stored.updatedAt <= base.updatedAt)) {\n return { record: { ...view, messages: local }, merged: false }\n }\n const own = local.filter((m) => !base?.known.has(m))\n const messages = placeByTurn(stored.messages, renumber(own, stored.messages))\n return {\n record: {\n ...view,\n createdAt: stored.createdAt,\n title: chatTitle(messages, texts),\n messages,\n totalUsage: sumUsage(\n stored.totalUsage,\n own.map((m) => (m.role === 'assistant' ? m.usage : undefined)),\n ),\n },\n merged: true,\n }\n}\n\n/**\n * What `useChatHistory` does to save the open chat: the stored record is read and the merged one\n * written in ONE readwrite transaction (`ChatHistoryStore.putMerged`), so another tab's save\n * cannot land between the two.\n */\nexport const saveChat = async (\n store: ChatHistoryStore,\n view: ChatRecord,\n base: ChatBase | undefined,\n texts?: AttachmentTexts,\n): Promise<{ record: ChatRecord; merged: boolean }> => {\n let merged = false\n const record = await store.putMerged(view.id, (stored) => {\n const out = mergeChatRecord(view, stored, base, texts)\n merged = out.merged\n return out.record\n })\n return { record, merged }\n}\n","/** Normalize any thrown value into a message string. */\nexport const errMessage = (err: unknown): string =>\n err instanceof Error ? err.message : String(err)\n\n/**\n * Calls `fn` once, `ms` after the LAST of a burst of calls (trailing): another tab writing a file\n * per tool call, or a chat per settled run, refreshes a view once, not once per notice. `cancel`\n * drops a pending call (on unmount).\n */\nexport const coalesce = (fn: () => void, ms = 100): { call: () => void; cancel: () => void } => {\n let timer: ReturnType<typeof setTimeout> | undefined\n return {\n call: () => {\n if (timer !== undefined) clearTimeout(timer)\n timer = setTimeout(() => {\n timer = undefined\n fn()\n }, ms)\n },\n cancel: () => {\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n },\n }\n}\n\n/**\n * The core's `onStorageChange`, or a no-op where the core predates it (the hooks then work as\n * before: this tab's own changes only). One place for the guard every hook needs.\n */\nexport const listenToOtherTabs = (\n core: { onStorageChange?: unknown },\n dbName: string | undefined,\n listener: (change: { kind: string; op: string; key?: string; namespace?: string }) => void,\n): (() => void) =>\n typeof core.onStorageChange === 'function' && dbName\n ? (core.onStorageChange as (db: string, l: typeof listener) => () => void)(dbName, listener)\n : () => undefined\n\n/**\n * Follow another tab's writes to one database: `accept` sees every notice (and says whether it\n * matters here), `settle` runs once, ~`ms` after the last accepted one of a burst. What every hook\n * that follows other tabs uses. The returned function unsubscribes and drops a pending settle.\n */\nexport const followOtherTabs = (\n core: { onStorageChange?: unknown },\n dbName: string | undefined,\n accept: (change: { kind: string; op: string; key?: string; namespace?: string }) => boolean,\n settle: () => void,\n ms = 100,\n): (() => void) => {\n const later = coalesce(settle, ms)\n const off = listenToOtherTabs(core, dbName, (change) => {\n if (accept(change)) later.call()\n })\n return () => {\n off()\n later.cancel()\n }\n}\n\n/**\n * What `sendRemote` makes of `watchSession().send`'s answer: `true` - that tab took it; `false`\n * while this view still watches that conversation - refused, or that run ended without it (the text\n * is offered again); `false` after the watch was closed (another conversation, the view gone) -\n * unknown: that tab may still take it, so nothing is offered.\n */\nexport const remoteAnswerOf = (\n ok: boolean,\n stillWatching: boolean,\n): 'taken' | 'refused' | 'unknown' => (ok ? 'taken' : stillWatching ? 'refused' : 'unknown')\n","/**\n * Recording from the microphone, for dictation through a model and for voice messages. No React:\n * a hook and the composer are built on it. The browser's `getUserMedia` and `MediaRecorder` can\n * be handed in (`RecordingDeps`), which is how the tests drive it.\n *\n * The rules it keeps:\n * - the permission is asked only by `startRecording` - call it from the person's tap;\n * - every track of the stream is stopped when the recording ends: stopped, cancelled, cut at its\n * longest, or failed - the browser's \"recording\" indicator goes away;\n * - nothing is kept here: the audio is handed to the caller once, as a `Blob`.\n */\n\n/** Why the microphone could not be used, as the composer says it (`micProblemLabel`). */\nexport type MicProblem =\n /** The person (or the browser, for this site) refused the permission. */\n | 'not-allowed'\n /** No microphone on the device (or none that fits). */\n | 'audio-capture'\n /** The microphone is held by another app (or the system refused to start it). */\n | 'busy'\n /** No recording here at all: no `mediaDevices` (an insecure page) or no `MediaRecorder`. */\n | 'unsupported'\n | 'failed'\n\n/** An error of the microphone, with its `MicProblem`. */\nexport class MicError extends Error {\n readonly code: MicProblem\n constructor(code: MicProblem, message: string = code) {\n super(message)\n this.name = 'MicError'\n this.code = code\n }\n}\n\n/** What a recording gave: the bytes, their media type (no codec parameters) and how long it ran. */\nexport interface RecordedAudio {\n blob: Blob\n /** `audio/webm`, `audio/mp4` (Safari, iOS), `audio/ogg`... - the container, without `;codecs=`. */\n mediaType: string\n durationMs: number\n}\n\n/** The slice of `MediaRecorder` this module drives. */\nexport interface MediaRecorderLike {\n readonly mimeType: string\n readonly state: 'inactive' | 'recording' | 'paused'\n start(timeslice?: number): void\n stop(): void\n ondataavailable: ((event: { data: Blob }) => void) | null\n onstop: (() => void) | null\n onerror: ((event: unknown) => void) | null\n}\n\nexport interface MediaRecorderConstructorLike {\n new (stream: MediaStream, options?: { mimeType?: string }): MediaRecorderLike\n isTypeSupported?(type: string): boolean\n}\n\nexport interface RecordingDeps {\n /** Default: `navigator.mediaDevices.getUserMedia`. */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>\n /** Default: the page's `MediaRecorder`. */\n MediaRecorder?: MediaRecorderConstructorLike\n /** Default: `Date.now`. */\n now?: () => number\n}\n\n/** The longest recording unless the caller says otherwise: five minutes. */\nexport const RECORDING_DEFAULT_MAX_MS = 5 * 60 * 1000\n\n/**\n * The containers asked for, in order: Opus in WebM (Chrome, Edge, Firefox), AAC in MP4 (Safari -\n * iOS records nothing else), Opus in Ogg. Every one is a type the core transcribes and plays.\n */\nexport const RECORDING_TYPES = [\n 'audio/webm;codecs=opus',\n 'audio/webm',\n 'audio/mp4',\n 'audio/ogg;codecs=opus',\n 'audio/ogg',\n] as const\n\n/** The first type the recorder takes, or undefined (the browser then picks its own). */\nexport const pickRecordingType = (\n isTypeSupported: ((type: string) => boolean) | undefined,\n): string | undefined => {\n if (!isTypeSupported) return undefined\n for (const type of RECORDING_TYPES) {\n try {\n if (isTypeSupported(type)) return type\n } catch {\n /* a browser that throws for a type it does not know */\n }\n }\n return undefined\n}\n\n/**\n * A recorder's media type as a file's: the container without parameters, and the names browsers\n * use for the same thing brought to one (`audio/x-m4a`, `audio/m4a`, `video/mp4` from Safari →\n * `audio/mp4`; `video/webm` → `audio/webm`). Unknown or empty: `audio/webm`.\n */\nexport const audioTypeOf = (type: string | undefined): string => {\n const base = (type ?? '').toLowerCase().split(';')[0].trim()\n if (/^(audio|video)\\/(mp4|x-m4a|m4a|aac-mp4)$/.test(base)) return 'audio/mp4'\n if (/^(audio|video)\\/webm$/.test(base)) return 'audio/webm'\n if (base === 'audio/ogg' || base === 'application/ogg') return 'audio/ogg'\n if (base === 'audio/wav' || base === 'audio/x-wav' || base === 'audio/wave') return 'audio/wav'\n if (base === 'audio/mpeg' || base === 'audio/mp3') return 'audio/mpeg'\n if (base === 'audio/aac') return 'audio/aac'\n return 'audio/webm'\n}\n\n/** The file extension of an audio type (`audioTypeOf`'s): `webm`, `m4a`, `ogg`, `wav`, `mp3`, `aac`. */\nexport const audioExtensionOf = (type: string): string =>\n (\n ({\n 'audio/mp4': 'm4a',\n 'audio/ogg': 'ogg',\n 'audio/wav': 'wav',\n 'audio/mpeg': 'mp3',\n 'audio/aac': 'aac',\n }) as Record<string, string>\n )[audioTypeOf(type)] ?? 'webm'\n\n/** What a failed `getUserMedia` (or recorder) means, by the DOMException's name. */\nexport const micProblemOf = (err: unknown): MicProblem => {\n if (err instanceof MicError) return err.code\n const name = err && typeof err === 'object' ? String((err as { name?: unknown }).name) : ''\n if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError')\n return 'not-allowed'\n if (\n name === 'NotFoundError' ||\n name === 'OverconstrainedError' ||\n name === 'DevicesNotFoundError'\n )\n return 'audio-capture'\n if (name === 'NotReadableError' || name === 'TrackStartError' || name === 'AbortError')\n return 'busy'\n if (name === 'NotSupportedError' || name === 'TypeError') return 'unsupported'\n return 'failed'\n}\n\nconst defaults = (deps: RecordingDeps) => {\n const g = globalThis as unknown as {\n navigator?: { mediaDevices?: { getUserMedia?: RecordingDeps['getUserMedia'] } }\n MediaRecorder?: MediaRecorderConstructorLike\n }\n const devices = g.navigator?.mediaDevices\n return {\n getUserMedia:\n deps.getUserMedia ?? (devices?.getUserMedia ? devices.getUserMedia.bind(devices) : undefined),\n MediaRecorder: deps.MediaRecorder ?? g.MediaRecorder,\n now: deps.now ?? Date.now,\n }\n}\n\n/** Whether this browser can record at all (it does not ask for anything). */\nexport const recordingSupported = (deps: RecordingDeps = {}): boolean => {\n const d = defaults(deps)\n return Boolean(d.getUserMedia && d.MediaRecorder)\n}\n\n/** Stop every track of a stream: the microphone is let go. */\nexport const stopTracks = (stream: MediaStream | undefined): void => {\n for (const track of stream?.getTracks() ?? []) {\n try {\n track.stop()\n } catch {\n /* already stopped */\n }\n }\n}\n\n/** A recording under way. */\nexport interface Recording {\n /** When it started (the clock of `RecordingDeps.now`). */\n readonly startedAt: number\n /** Stop it and get the audio. The microphone is let go first. */\n stop(): Promise<RecordedAudio>\n /** Throw it away. The microphone is let go; `stop` then rejects. */\n cancel(): void\n /** Settles when the recording has ended, whichever way (the tracks are stopped by then). */\n readonly ended: Promise<void>\n}\n\nexport interface StartRecordingOptions extends RecordingDeps {\n /** Cut it here (default `RECORDING_DEFAULT_MAX_MS`); `onLimit` is told, `stop` still gives the audio. */\n maxMs?: number\n onLimit?: () => void\n}\n\n/**\n * Ask for the microphone and start recording. Rejects with a `MicError` when the microphone\n * cannot be had (the permission refused, no device, held elsewhere, no recorder) - and then no\n * track is left running.\n */\nexport const startRecording = async (options: StartRecordingOptions = {}): Promise<Recording> => {\n const d = defaults(options)\n if (!d.getUserMedia || !d.MediaRecorder) throw new MicError('unsupported')\n let stream: MediaStream\n try {\n stream = await d.getUserMedia({ audio: true })\n } catch (err) {\n throw new MicError(micProblemOf(err))\n }\n let recorder: MediaRecorderLike\n try {\n const type = pickRecordingType(d.MediaRecorder.isTypeSupported?.bind(d.MediaRecorder))\n recorder = new d.MediaRecorder(stream, type ? { mimeType: type } : undefined)\n } catch (err) {\n stopTracks(stream)\n throw new MicError(micProblemOf(err) === 'failed' ? 'unsupported' : micProblemOf(err))\n }\n const startedAt = d.now()\n const chunks: Blob[] = []\n let cancelled = false\n let failure: MicError | undefined\n let settle: () => void = () => {}\n const ended = new Promise<void>((resolve) => (settle = resolve))\n let finish: ((audio: RecordedAudio) => void) | undefined\n let fail: ((err: Error) => void) | undefined\n const result = new Promise<RecordedAudio>((resolve, reject) => {\n finish = resolve\n fail = reject\n })\n // The promise is awaited only by `stop`; a cancelled recording rejects it unseen.\n result.catch(() => {})\n let limit: ReturnType<typeof setTimeout> | undefined\n const end = () => {\n stopTracks(stream)\n clearTimeout(limit)\n settle()\n }\n recorder.ondataavailable = (event) => {\n if (event.data && event.data.size > 0) chunks.push(event.data)\n }\n recorder.onerror = () => {\n failure = new MicError('failed')\n end()\n fail?.(failure)\n }\n recorder.onstop = () => {\n end()\n if (cancelled) return fail?.(new MicError('failed', 'cancelled'))\n if (failure) return fail?.(failure)\n const mediaType = audioTypeOf(recorder.mimeType || chunks[0]?.type)\n finish?.({\n blob: new Blob(chunks, { type: mediaType }),\n mediaType,\n durationMs: Math.max(0, d.now() - startedAt),\n })\n }\n const stopRecorder = () => {\n try {\n if (recorder.state !== 'inactive') recorder.stop()\n else recorder.onstop?.()\n } catch {\n recorder.onstop?.()\n }\n }\n const maxMs = options.maxMs ?? RECORDING_DEFAULT_MAX_MS\n limit = setTimeout(() => {\n stopRecorder()\n options.onLimit?.()\n }, maxMs)\n try {\n // Chunks every second: a recording cut short (a tab closed) has most of its audio.\n recorder.start(1000)\n } catch (err) {\n end()\n throw new MicError(micProblemOf(err) === 'failed' ? 'unsupported' : micProblemOf(err))\n }\n return {\n startedAt,\n ended,\n stop: () => {\n stopRecorder()\n return result\n },\n cancel: () => {\n cancelled = true\n chunks.length = 0\n stopRecorder()\n // Some recorders never fire `stop` after an error: the tracks go now in any case.\n end()\n },\n }\n}\n","import {\n micProblemOf,\n startRecording,\n type RecordedAudio,\n type Recording,\n type RecordingDeps,\n} from './record.js'\n\n/** The slice of the Web Speech API recognizer `useSpeechToText` (and any other front end) drives. */\nexport interface SpeechRecognizerLike {\n lang: string\n continuous: boolean\n interimResults: boolean\n start(): void\n stop(): void\n abort?(): void\n onresult: ((ev: SpeechResultEventLike) => void) | null\n /**\n * `error` is the Web Speech API's code (`not-allowed`, `audio-capture`, `network`, ...) or a\n * recognizer's own; `message`, when given, is what to say - in the host's words.\n */\n onerror: ((ev: { error?: string; message?: string }) => void) | null\n onend: (() => void) | null\n}\n\ninterface SpeechResultEventLike {\n resultIndex: number\n results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>\n}\n\n/** Turn a recording into text: the host's call to a speech-to-text model. */\nexport type TranscribeAudio = (\n audio: RecordedAudio,\n context: {\n /** The recognizer's language (BCP-47), a hint for the model. */\n lang: string\n /** Aborted when the person cancels (or the composer goes away). */\n signal: AbortSignal\n },\n) => Promise<string>\n\nexport interface RecordingRecognizerOptions extends RecordingDeps {\n /** The speech-to-text call - a provider's transcription model, an on-device engine. */\n transcribe: TranscribeAudio\n /** The longest dictation (default: the recorder's five minutes). */\n maxMs?: number\n}\n\n/**\n * A recognizer for `useSpeechToText` / the composer's mic (`speech.createRecognizer`) that\n * RECORDS and then hands the audio to `transcribe`: tap to start (the microphone is asked for\n * then), tap again to stop - the words arrive once, as one final result, after the model has\n * answered (`useSpeechToText().finishing` meanwhile). The microphone is let go as soon as the\n * recording stops; the audio is given to `transcribe` and kept nowhere.\n *\n * Errors come as the Web Speech API's codes where there is one (`not-allowed`, `audio-capture`),\n * the recorder's otherwise (`busy`, `unsupported`), and `transcription` with the thrown error's\n * `message` - say it in the host's words: the composer shows the message as given.\n */\nexport const createRecordingRecognizer =\n (options: RecordingRecognizerOptions): (() => SpeechRecognizerLike) =>\n () => {\n let recording: Recording | undefined\n let starting: Promise<void> | undefined\n let stopAsked = false\n let aborted = false\n let ended = false\n const controller = new AbortController()\n const rec: SpeechRecognizerLike = {\n lang: '',\n continuous: true,\n interimResults: false,\n onresult: null,\n onerror: null,\n onend: null,\n start() {\n if (starting) return\n starting = (async () => {\n try {\n recording = await startRecording({\n ...options,\n maxMs: options.maxMs,\n onLimit: () => rec.stop(),\n })\n } catch (err) {\n if (!aborted) rec.onerror?.({ error: micProblemOf(err) })\n return finish()\n }\n // Stopped (or aborted) while the permission was being asked: nothing is kept.\n if (aborted) {\n recording.cancel()\n return finish()\n }\n if (stopAsked) void transcribeNow()\n })()\n },\n stop() {\n if (stopAsked || ended) return\n stopAsked = true\n if (recording) void transcribeNow()\n },\n abort() {\n if (ended) return\n aborted = true\n controller.abort()\n recording?.cancel()\n if (!starting || recording) finish()\n },\n }\n const finish = () => {\n if (ended) return\n ended = true\n rec.onend?.()\n }\n let transcribing = false\n const transcribeNow = async () => {\n if (transcribing || !recording) return\n transcribing = true\n let audio: RecordedAudio\n try {\n audio = await recording.stop()\n } catch (err) {\n if (!aborted) rec.onerror?.({ error: micProblemOf(err) })\n return finish()\n }\n if (aborted) return finish()\n if (audio.blob.size === 0) return finish()\n try {\n const text = (\n await options.transcribe(audio, { lang: rec.lang, signal: controller.signal })\n )\n .replace(/\\s+/g, ' ')\n .trim()\n if (!aborted && text)\n rec.onresult?.({\n resultIndex: 0,\n results: [{ isFinal: true, 0: { transcript: text } }],\n })\n } catch (err) {\n if (!aborted)\n rec.onerror?.({\n error: 'transcription',\n message: err instanceof Error ? err.message : String(err),\n })\n }\n finish()\n }\n return rec\n }\n","/**\n * Reading answers aloud: the text an answer is read as (`speakableText`), and two engines behind\n * one shape (`SpeakText`) - the browser's own `speechSynthesis` (on the device, free, offline\n * where the voice is local) and any engine that makes audio (`createAudioSpeaker`: a provider's\n * text-to-speech model, played from a `blob:` URL). No React; `useReadAloud` and the message\n * list's Listen button are built on it.\n */\n\n/** Where a reading is: making its audio, playing, paused. */\nexport type ReadAloudState = 'loading' | 'playing' | 'paused'\n\n/** A reading under way. */\nexport interface SpeechPlayback {\n pause(): void\n resume(): void\n /** End it now; `done` then resolves. */\n stop(): void\n /** Resolves when the reading ends - read to the end, or stopped; rejects when it failed. */\n readonly done: Promise<void>\n}\n\n/** Start reading a text. `onState` hears every change of state until `done` settles. */\nexport type SpeakText = (\n text: string,\n options: { lang?: string; onState: (state: ReadAloudState) => void },\n) => SpeechPlayback\n\n/**\n * A reading that failed in the engine itself (the browser's voice, the audio element) - a code,\n * not words for the person: the Listen button says its own label. An error a host's\n * `synthesize` throws is shown with its message.\n */\nexport class SpeechOutputError extends Error {\n readonly code: string\n constructor(code: string) {\n super(code)\n this.name = 'SpeechOutputError'\n this.code = code\n }\n}\n\nconst asOutputError = (err: unknown): SpeechOutputError =>\n err instanceof SpeechOutputError\n ? err\n : new SpeechOutputError(\n err && typeof err === 'object' && 'name' in err ? String(err.name) : 'playback-failed',\n )\n\n// ── the text that is read ───────────────────────────────────────────────────\n\nexport interface SpeakableOptions {\n /** Said in place of a code block (default: nothing - the block is skipped). */\n code?: string\n}\n\n/**\n * An answer's Markdown as the words to say: no markers (`#`, `*`, `_`, backticks, `>`, list\n * bullets, table rules), a link as its text, a picture as its alt text, a bare URL as its host, a\n * code block NOT read symbol by symbol (left out, or said as `options.code`), inline code as its\n * text, a table's cells one after another. Blocks end in a stop so the voice pauses between them.\n */\nexport const speakableText = (markdown: string, options: SpeakableOptions = {}): string => {\n const out: string[] = []\n const lines = markdown.replace(/\\r\\n?/g, '\\n').split('\\n')\n let fence: string | undefined\n let fenceSaid = false\n for (const raw of lines) {\n const line = raw.trimEnd()\n const opener = /^\\s*(`{3,}|~{3,})/.exec(line)\n if (fence !== undefined) {\n if (opener && opener[1][0] === fence[0] && opener[1].length >= fence.length) fence = undefined\n continue\n }\n if (opener) {\n fence = opener[1]\n if (options.code && !fenceSaid) out.push(options.code)\n fenceSaid = true\n continue\n }\n fenceSaid = false\n // A table's rule line, a thematic break: nothing to say.\n if (/^\\s*\\|?\\s*:?-{2,}:?\\s*(\\|\\s*:?-{2,}:?\\s*)*\\|?\\s*$/.test(line)) continue\n if (/^\\s*([-*_])\\s*(\\1\\s*){2,}$/.test(line)) continue\n let text = line\n .replace(/^\\s{0,3}#{1,6}\\s+/, '')\n .replace(/^\\s*>\\s?/, '')\n .replace(/^\\s*(?:[-*+]|\\d+[.)])\\s+(\\[[ xX]\\]\\s+)?/, '')\n // A table row: its cells, one after another.\n if (/^\\s*\\|.*\\|\\s*$/.test(text))\n text = text\n .replace(/^\\s*\\||\\|\\s*$/g, '')\n .split('|')\n .map((c) => c.trim())\n .filter(Boolean)\n .join(', ')\n text = text\n .replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/<(https?:\\/\\/[^>\\s]+)>/g, (_m, url: string) => hostOf(url))\n .replace(/\\bhttps?:\\/\\/[^\\s)]+/g, (url) => hostOf(url))\n .replace(/`+([^`]*)`+/g, '$1')\n .replace(/(\\*\\*|__)(.+?)\\1/g, '$2')\n .replace(/(^|[^\\w*])[*_]([^*_\\s][^*_]*?)[*_](?=[^\\w*]|$)/g, '$1$2')\n .replace(/~~(.+?)~~/g, '$1')\n .replace(/<\\/?[a-z][^>]*>/gi, '')\n .replace(/[*_#`~>|]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n if (!text) continue\n out.push(/[.!?…:;。!?]$/.test(text) ? text : `${text}.`)\n }\n return out.join(' ').trim()\n}\n\nconst hostOf = (url: string): string => {\n try {\n return new URL(url).hostname.replace(/^www\\./, '')\n } catch {\n return ''\n }\n}\n\n/**\n * A text in pieces of at most `max` characters, cut after a sentence where one ends in time,\n * else after a word: engines read long text badly in one go (Chrome's voices stop after some\n * seconds; a provider takes a few thousand characters per call).\n */\nexport const splitForSpeech = (text: string, max = 220): string[] => {\n const pieces: string[] = []\n let rest = text.trim()\n while (rest.length > max) {\n const window = rest.slice(0, max + 1)\n let cut = -1\n for (const m of window.matchAll(/[.!?…。!?;:](\\s|$)/g))\n if (m.index !== undefined && m.index + 1 <= max) cut = m.index + 1\n if (cut < max / 3) cut = window.lastIndexOf(' ')\n if (cut <= 0) cut = max\n pieces.push(rest.slice(0, cut).trim())\n rest = rest.slice(cut).trim()\n }\n if (rest) pieces.push(rest)\n return pieces\n}\n\n// ── the language of a text ──────────────────────────────────────────────────\n\n/** A writing system, as far as a voice needs to know: the letters it can read. */\nexport type SpeechScript =\n | 'latin'\n | 'cyrillic'\n | 'greek'\n | 'arabic'\n | 'hebrew'\n | 'han'\n | 'kana'\n | 'hangul'\n | 'devanagari'\n | 'thai'\n | 'georgian'\n | 'armenian'\n\nconst SCRIPT_RANGES: readonly (readonly [SpeechScript, RegExp])[] = [\n ['latin', /\\p{Script=Latin}/u],\n ['cyrillic', /\\p{Script=Cyrillic}/u],\n ['greek', /\\p{Script=Greek}/u],\n ['arabic', /\\p{Script=Arabic}/u],\n ['hebrew', /\\p{Script=Hebrew}/u],\n ['kana', /[\\p{Script=Hiragana}\\p{Script=Katakana}]/u],\n ['han', /\\p{Script=Han}/u],\n ['hangul', /\\p{Script=Hangul}/u],\n ['devanagari', /\\p{Script=Devanagari}/u],\n ['thai', /\\p{Script=Thai}/u],\n ['georgian', /\\p{Script=Georgian}/u],\n ['armenian', /\\p{Script=Armenian}/u],\n]\n\n/** The languages (BCP-47 base) written in a script other than Latin; any other is Latin. */\nconst LANGUAGE_SCRIPT: Readonly<Record<string, SpeechScript>> = {\n ru: 'cyrillic',\n uk: 'cyrillic',\n be: 'cyrillic',\n bg: 'cyrillic',\n sr: 'cyrillic',\n mk: 'cyrillic',\n kk: 'cyrillic',\n ky: 'cyrillic',\n tg: 'cyrillic',\n mn: 'cyrillic',\n el: 'greek',\n ar: 'arabic',\n fa: 'arabic',\n ur: 'arabic',\n he: 'hebrew',\n yi: 'hebrew',\n zh: 'han',\n ja: 'kana',\n ko: 'hangul',\n hi: 'devanagari',\n mr: 'devanagari',\n ne: 'devanagari',\n th: 'thai',\n ka: 'georgian',\n hy: 'armenian',\n}\n\n/** The language a script is read in when none of the person's languages is written in it. */\nconst SCRIPT_DEFAULT: Readonly<Record<SpeechScript, string>> = {\n latin: 'en',\n cyrillic: 'ru',\n greek: 'el',\n arabic: 'ar',\n hebrew: 'he',\n han: 'zh',\n kana: 'ja',\n hangul: 'ko',\n devanagari: 'hi',\n thai: 'th',\n georgian: 'ka',\n armenian: 'hy',\n}\n\n/** The script a language (BCP-47) is written in: `sr-Latn` is Latin, `zh-*` Han, `ja` kana. */\nexport const scriptOfLanguage = (lang: string): SpeechScript => {\n const parts = lang.toLowerCase().replace(/_/g, '-').split('-')\n if (parts.includes('latn')) return 'latin'\n if (parts.includes('cyrl')) return 'cyrillic'\n return LANGUAGE_SCRIPT[parts[0]] ?? 'latin'\n}\n\n/**\n * The script most of a text's letters are written in (digits, signs and spaces do not count);\n * a text with any kana is Japanese (it is mostly Han letters too). Undefined: no letters.\n */\nexport const scriptOfText = (text: string): SpeechScript | undefined => {\n const counts = new Map<SpeechScript, number>()\n for (const ch of text) {\n if (!/\\p{L}/u.test(ch)) continue\n const found = SCRIPT_RANGES.find(([, re]) => re.test(ch))\n if (!found) continue\n counts.set(found[0], (counts.get(found[0]) ?? 0) + 1)\n }\n if (counts.has('kana')) {\n counts.set('kana', (counts.get('kana') ?? 0) + (counts.get('han') ?? 0))\n counts.delete('han')\n }\n let best: SpeechScript | undefined\n let most = 0\n for (const [script, n] of counts)\n if (n > most) {\n best = script\n most = n\n }\n return best\n}\n\n/**\n * The language to read a text in: the first of `preferred` (the UI's language, then the\n * browser's, `navigator.languages`) written in the text's script - so a Russian answer in an\n * English interface is read in Russian, not spelled by an English voice -, else the script's\n * usual language. A text without letters: the first preferred. Which of the languages of ONE\n * script (English or French) cannot be told from the letters: the person's order decides.\n */\nexport const languageOfText = (\n text: string,\n preferred: readonly (string | undefined)[] = [],\n): string | undefined => {\n const mine = preferred.filter((l): l is string => Boolean(l))\n const script = scriptOfText(text)\n if (!script) return mine[0]\n return mine.find((l) => scriptOfLanguage(l) === script) ?? SCRIPT_DEFAULT[script]\n}\n\n// ── the browser's voices ────────────────────────────────────────────────────\n\n/** The slice of a `SpeechSynthesisVoice` used here. */\nexport interface SpeechVoiceLike {\n voiceURI: string\n name: string\n lang: string\n localService?: boolean\n default?: boolean\n}\n\n/**\n * The voice to read a language with: the person's (by `voiceURI`) while the browser has it and it\n * reads that language's script; else\n * one of exactly that language (`pt-BR`), then of its base (`pt`) - a voice on the device before a\n * network one, the browser's default of the language first. Undefined: none for the language (the\n * browser then reads with its own default).\n */\nexport const voiceFor = <V extends SpeechVoiceLike>(\n voices: readonly V[],\n lang: string | undefined,\n preferred?: string,\n): V | undefined => {\n if (preferred) {\n // The person's voice - for a text it can read: a voice of another script spells it.\n const chosen = voices.find((v) => v.voiceURI === preferred)\n if (chosen && (!lang || scriptOfLanguage(chosen.lang) === scriptOfLanguage(lang))) return chosen\n }\n if (!lang) return undefined\n const norm = (l: string) => l.toLowerCase().replace(/_/g, '-')\n const want = norm(lang)\n const base = want.split('-')[0]\n const rank = (v: V) => [v.localService ? 1 : 0, v.default ? 1 : 0]\n const best = (list: V[]) =>\n [...list].sort((a, b) => {\n const ra = rank(a)\n const rb = rank(b)\n return rb[0] - ra[0] || rb[1] - ra[1] || a.name.localeCompare(b.name)\n })[0]\n const exact = voices.filter((v) => norm(v.lang) === want)\n if (exact.length) return best(exact)\n const same = voices.filter((v) => norm(v.lang).split('-')[0] === base)\n return same.length ? best(same) : undefined\n}\n\n/** The voices of a language (`voiceFor`'s matching), for a picker. */\nexport const voicesOf = <V extends SpeechVoiceLike>(\n voices: readonly V[],\n lang: string | undefined,\n): V[] => {\n if (!lang) return [...voices]\n const base = lang.toLowerCase().split(/[-_]/)[0]\n return voices.filter((v) => v.lang.toLowerCase().split(/[-_]/)[0] === base)\n}\n\n/** The slice of `speechSynthesis` this module drives. */\nexport interface SpeechSynthesisLike {\n speak(utterance: SpeechUtteranceLike): void\n cancel(): void\n pause(): void\n resume(): void\n getVoices(): SpeechVoiceLike[]\n readonly speaking?: boolean\n}\n\nexport interface SpeechUtteranceLike {\n text: string\n lang: string\n voice: SpeechVoiceLike | null\n rate: number\n onstart: (() => void) | null\n onend: (() => void) | null\n onerror: ((event: { error?: string }) => void) | null\n}\n\n/** Whether the browser can read aloud (it has `speechSynthesis`). */\nexport const speechSynthesisSupported = (): boolean =>\n typeof globalThis !== 'undefined' &&\n 'speechSynthesis' in globalThis &&\n typeof (globalThis as { SpeechSynthesisUtterance?: unknown }).SpeechSynthesisUtterance ===\n 'function'\n\nexport interface BrowserSpeakerOptions {\n /** The person's voice (`voiceURI`); else one of the text's language (`voiceFor`). */\n voice?: string\n /** 0.1-10, default 1. */\n rate?: number\n /** Default: the page's `speechSynthesis` and `SpeechSynthesisUtterance` (tests hand in their own). */\n synth?: SpeechSynthesisLike\n createUtterance?: (text: string) => SpeechUtteranceLike\n}\n\n/**\n * Read with the browser's `speechSynthesis`: on the device (a local voice works offline), free.\n * The text goes in pieces (`splitForSpeech`); one reading at a time in the whole page - starting\n * one cancels any other.\n */\nexport const createBrowserSpeaker =\n (options: BrowserSpeakerOptions = {}): SpeakText =>\n (text, { lang, onState }) => {\n const synth =\n options.synth ??\n (globalThis as unknown as { speechSynthesis: SpeechSynthesisLike }).speechSynthesis\n const make =\n options.createUtterance ??\n ((t: string) =>\n new (\n globalThis as unknown as {\n SpeechSynthesisUtterance: new (t: string) => SpeechUtteranceLike\n }\n ).SpeechSynthesisUtterance(t))\n const voice = voiceFor(synth.getVoices(), lang, options.voice)\n let settle!: () => void\n let fail!: (err: Error) => void\n const done = new Promise<void>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n done.catch(() => {})\n let over = false\n const end = (err?: Error) => {\n if (over) return\n over = true\n if (err) fail(err)\n else settle()\n }\n const pieces = splitForSpeech(text)\n synth.cancel()\n if (pieces.length === 0) {\n end()\n return { pause() {}, resume() {}, stop() {}, done }\n }\n let started = false\n pieces.forEach((piece, i) => {\n const u = make(piece)\n u.lang = voice?.lang ?? lang ?? ''\n try {\n u.voice = voice ?? null\n } catch {\n // Not one of this browser's voice objects: the language picks one.\n }\n u.rate = options.rate ?? 1\n u.onstart = () => {\n if (!started && !over) onState('playing')\n started = true\n }\n u.onend = () => {\n if (i === pieces.length - 1) end()\n }\n u.onerror = (event) => {\n // `interrupted` / `canceled`: this reading was stopped (by us, or by another one).\n if (event.error === 'interrupted' || event.error === 'canceled') end()\n else end(new SpeechOutputError(event.error || 'synthesis-failed'))\n }\n synth.speak(u)\n })\n onState('loading')\n return {\n pause: () => {\n if (over) return\n synth.pause()\n onState('paused')\n },\n resume: () => {\n if (over) return\n synth.resume()\n onState('playing')\n },\n stop: () => {\n if (over) return\n synth.cancel()\n end()\n },\n done,\n }\n }\n\n// ── an engine that makes audio ───────────────────────────────────────────────\n\n/** Make the audio of a text: the host's call to a text-to-speech model. */\nexport type SynthesizeSpeech = (\n text: string,\n context: { lang?: string; signal: AbortSignal },\n) => Promise<Blob>\n\n/** The slice of an `HTMLAudioElement` this module drives. */\nexport interface AudioLike {\n src: string\n paused: boolean\n play(): Promise<void>\n pause(): void\n onended: (() => void) | null\n onerror: (() => void) | null\n}\n\nexport interface AudioSpeakerOptions {\n synthesize: SynthesizeSpeech\n /** Characters per call (default 2000): a long answer is several calls, the next made while one plays. */\n maxChars?: number\n /** Default: `new Audio()`. */\n createAudio?: () => AudioLike\n /** Default: `URL.createObjectURL` / `URL.revokeObjectURL`. */\n objectUrl?: { create: (blob: Blob) => string; revoke: (url: string) => void }\n /**\n * Play a moment of silence on the element at once, inside the person's tap (default true): iOS\n * Safari plays an element later - after the audio was made - only if it was played inside the\n * gesture. Call `speak` from the click handler for it to count.\n */\n unlock?: boolean\n}\n\n/** A WAV of a few samples of silence: what unlocks an audio element inside a tap. */\nconst silence = (): Blob => {\n const samples = 16\n const view = new DataView(new ArrayBuffer(44 + samples * 2))\n const text = (at: number, s: string) => {\n for (let i = 0; i < s.length; i++) view.setUint8(at + i, s.charCodeAt(i))\n }\n text(0, 'RIFF')\n view.setUint32(4, 36 + samples * 2, true)\n text(8, 'WAVEfmt ')\n view.setUint32(16, 16, true)\n view.setUint16(20, 1, true)\n view.setUint16(22, 1, true)\n view.setUint32(24, 8000, true)\n view.setUint32(28, 16000, true)\n view.setUint16(32, 2, true)\n view.setUint16(34, 16, true)\n text(36, 'data')\n view.setUint32(40, samples * 2, true)\n return new Blob([view.buffer], { type: 'audio/wav' })\n}\n\n/**\n * Read with an engine that makes audio - a provider's text-to-speech model: each piece of the text\n * (`maxChars`) is made by `synthesize` and played from a `blob:` URL, revoked when it has played\n * or the reading stops. Stopping aborts a call in flight (`signal`). Nothing is stored.\n */\nexport const createAudioSpeaker =\n (options: AudioSpeakerOptions): SpeakText =>\n (text, { lang, onState }) => {\n const urls = options.objectUrl ?? {\n create: (b: Blob) => URL.createObjectURL(b),\n revoke: (u: string) => URL.revokeObjectURL(u),\n }\n const audio = options.createAudio?.() ?? (new Audio() as unknown as AudioLike)\n const controller = new AbortController()\n const pieces = splitForSpeech(text, options.maxChars ?? 2000)\n let settle!: () => void\n let fail!: (err: Error) => void\n const done = new Promise<void>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n done.catch(() => {})\n let over = false\n let paused = false\n let current: string | undefined\n const made = new Map<number, Promise<Blob>>()\n const make = (i: number) => {\n if (!made.has(i)) {\n const p = options.synthesize(pieces[i], { lang, signal: controller.signal })\n p.catch(() => {})\n made.set(i, p)\n }\n return made.get(i)!\n }\n const release = () => {\n if (current) urls.revoke(current)\n current = undefined\n }\n const end = (err?: Error) => {\n if (over) return\n over = true\n controller.abort()\n audio.pause()\n audio.onended = null\n audio.onerror = null\n release()\n if (err) fail(err)\n else settle()\n }\n const playFrom = async (i: number) => {\n if (over) return\n if (i >= pieces.length) return end()\n onState(i === 0 || !current ? 'loading' : 'playing')\n let blob: Blob\n try {\n blob = await make(i)\n } catch (err) {\n return end(err instanceof Error ? err : new Error(String(err)))\n }\n if (over) return\n // The next piece is made while this one plays.\n if (i + 1 < pieces.length) make(i + 1)\n release()\n current = urls.create(blob)\n audio.src = current\n audio.onended = () => void playFrom(i + 1)\n audio.onerror = () => end(new SpeechOutputError('playback-failed'))\n if (paused) return onState('paused')\n try {\n await audio.play()\n if (!over) onState('playing')\n } catch (err) {\n end(asOutputError(err))\n }\n }\n if (pieces.length === 0) end()\n else {\n if (options.unlock !== false) {\n // Inside the tap: a moment of silence, so that the element may play once the audio is made.\n current = urls.create(silence())\n audio.src = current\n audio.play().catch(() => {})\n }\n void playFrom(0)\n }\n return {\n pause: () => {\n if (over) return\n paused = true\n audio.pause()\n onState('paused')\n },\n resume: () => {\n if (over || !paused) return\n paused = false\n if (current)\n audio.play().then(\n () => !over && onState('playing'),\n (err) => end(asOutputError(err)),\n )\n else onState('loading')\n },\n stop: () => end(),\n done,\n }\n }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAIK;;;ACkBA,IAAM,qBAAqB;AAG3B,IAAM,sBAAsB;AAGnC,IAAM,eAAe;AAiBd,IAAM,oBAAoB,CAC/B,YACuB;AACvB,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,YAAY,OAAO,SAAY,QAAQ;AACnD,MAAI,QAAQ,UAAa,QAAQ,KAAM,QAAO;AAC9C,MAAI,OAAO,QAAQ,YAAY,EAAE,MAAM,MAAM,MAAM,aAAc,QAAO;AACxE,SAAO,KAAK,IAAI,GAAG,KAAK,MAAM,GAAG,CAAC;AACpC;AAOO,IAAM,cAAc,CACzB,SACA,YACwC;AACxC,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,YAAY,KAAM,QAAO,EAAE,YAAY,QAAQ;AACnD,SAAO,QAAQ,aAAa,UAAU,EAAE,GAAG,SAAS,YAAY,QAAQ;AAC1E;AA+BA,IAAM,WAA0B,EAAE,UAAU,KAAK;AAQ1C,IAAM,sBAAsB,CAAC,UAAgC,CAAC,MAAqB;AACxF,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,UAAU,oBAAI,IAGlB;AACF,MAAI,WAAW;AAEf,QAAM,OAAO,MAAyB,CAAC,GAAG,QAAQ,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ;AACjF,QAAM,U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U,MAAM,KAAK,SAAS,IAAI,CAAC;AACzC,UAAM,UAAU,MAAM,IAAI,IAAI,kBAAkB,iBAAiB,CAAC;AAClE,QAAI,OAAQ,QAAO,QAAQ,QAAQ;AACnC,QAAI;AACF,YAAM,MAAM,KAAK;AACjB,UAAI,CAAC,KAAM,SAAQ,SAAS;AAAA,IAC9B,SAAS,KAAK;AACZ,UAAI,cAAc,GAAG,CAAC;AAAA,IACxB;AAAA,EACF;AACA,MAAI,OAAO,WAAW,EAAG,KAAI;AAAA,OACxB;AACH,QAAI,QAAQ,WAAW,OAAO;AAE5B,gBAAU,KAAK,OAAO,QAAQ,CAAC;AAC/B,YAAM,MAAM;AACZ,YAAM,KAAK,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC7B;AACA,SAAK,SAAS,CAAC;AAAA,EACjB;AACA,SAAO;AAAA,IACL,OAAO,MAAM;AACX,UAAI,KAAM;AACV,eAAS;AACT,YAAM,MAAM;AACZ,cAAQ,QAAQ;AAAA,IAClB;AAAA,IACA,QAAQ,MAAM;AACZ,UAAI,QAAQ,CAAC,OAAQ;AACrB,eAAS;AACT,UAAI;AACF,cAAM,KAAK,EAAE;AAAA,UACX,MAAM,CAAC,QAAQ,QAAQ,SAAS;AAAA,UAChC,CAAC,QAAQ,IAAI,cAAc,GAAG,CAAC;AAAA,QACjC;AAAA,UACG,SAAQ,SAAS;AAAA,IACxB;AAAA,IACA,MAAM,MAAM,IAAI;AAAA,IAChB;AAAA,EACF;AACF;","names":["text","text","m","text","text","text","req","TIMER_MAX_MS","text","text","core","text","text"]}
|
|
1
|
+
{"version":3,"sources":["../src/composer.ts","../src/labels.ts","../src/follow-scroll.ts","../src/dom-root.ts","../src/file-kinds.ts","../src/image-resize.ts","../src/format.ts","../src/elicitation.ts","../src/prompt-arming.ts","../src/chat-history.ts","../src/voice/record.ts","../src/voice/recognizer.ts","../src/voice/speak.ts"],"sourcesContent":["import type { AgentLabels } from './labels.js'\nimport type { AgentUiState } from './types.js'\n\n/**\n * Pure helpers behind `<AgentComposer>`: slash commands, attachments, notices\n * and the elapsed-time label. No React, no DOM — unit-tested on their own.\n */\n\n/** A command offered when the input starts with \"/\". */\nexport interface SlashCommand {\n /** Typed after the slash, e.g. \"compact\" for \"/compact\". */\n name: string\n description: string\n /**\n * 'action' runs at once on Enter (e.g. /compact); 'prefix' stays in the\n * input and rewrites the goal on submit (e.g. /chess-coach <goal>).\n */\n kind?: 'action' | 'prefix'\n /** For 'action' commands: what to do (receives the text after the name). */\n run?: (args: string) => void | Promise<void>\n /** For 'prefix' commands: the goal to send, built from the text after the name. */\n transform?: (args: string) => string\n /** Grouping label in the palette (\"Commands\", \"Skills\", …). */\n group?: string\n}\n\n/** \"/name rest of text\" → { name, args }; undefined unless the text starts with \"/\". */\nexport const parseSlash = (text: string): { name: string; args: string } | undefined => {\n const m = /^\\/([\\w-]*)(?:\\s+([\\s\\S]*))?$/.exec(text.trimStart())\n return m ? { name: m[1].toLowerCase(), args: (m[2] ?? '').trim() } : undefined\n}\n\n/** What pressing Enter does while the agent is working (see {@link steerIntent}). */\nexport type SteerIntent =\n /** The agent is idle: submit as usual. */\n | 'idle'\n /** Say it to the running agent. */\n | 'steer'\n /** There are attachments, which cannot be added to a run that is going. */\n | 'attachments'\n /** Nothing to do (empty, a slash command, or steering is switched off). */\n | 'ignore'\n\n/**\n * Decide what Enter means while the agent works: text goes to the running agent,\n * files cannot (they are sent with the next message), a \"/command\" is not a message,\n * and a host that switched steering off gets the old behaviour (nothing happens).\n */\nexport const steerIntent = (input: {\n /** The trimmed text. */\n raw: string\n busy: boolean\n steering: boolean\n hasAttachments: boolean\n}): SteerIntent => {\n if (!input.busy) return 'idle'\n if (!input.steering) return 'ignore'\n if (!input.raw && !input.hasAttachments) return 'ignore'\n if (parseSlash(input.raw)) return 'ignore'\n return input.hasAttachments ? 'attachments' : 'steer'\n}\n\n/** What a send (Enter or the Send button) does when the agent is not working (see {@link notReadyIntent}). */\nexport type NotReadyIntent =\n /** The agent is ready: send now. */\n | 'send'\n /** The agent is starting: remember the send and make it when the agent is ready. */\n | 'wait'\n /** The send cannot go and is not remembered: say why ({@link NotReadyReason}), keep the text. */\n | 'refuse'\n /** Nothing to send (an empty box): nothing happens, as before. */\n | 'ignore'\n\n/** Why a send cannot go now. */\nexport type NotReadyReason =\n /** The host turned the composer off (`disabled`). */\n | 'disabled'\n /** The agent could not be built (`status === 'error'`). */\n | 'failed'\n /** There is no agent: nothing is being built (no model yet, say). */\n | 'unavailable'\n\n/** What decides {@link notReadyIntent} and {@link waitingSendStep}. */\nexport interface NotReadyInput {\n /** The agent's status as the composer shows it (`useAgent().status`). */\n status: AgentUiState['status']\n /** The agent can take a run now (`useAgent().isReady`). */\n ready: boolean\n /** The host turned the composer off. */\n disabled: boolean\n}\n\n/**\n * Decide what a send means when the agent is not working: a ready agent takes it now; one that\n * is starting takes it when it is ready (the composer remembers it, keeping the text in the box);\n * every other state refuses it out loud - never a send that does nothing and says nothing.\n * A run that goes on is {@link steerIntent}'s, decided before this.\n */\nexport const notReadyIntent = (input: NotReadyInput & { hasContent: boolean }): NotReadyIntent => {\n if (!input.hasContent) return 'ignore'\n if (input.disabled) return 'refuse'\n if (input.ready) return 'send'\n if (input.status === 'initializing') return 'wait'\n return 'refuse'\n}\n\n/** Why a send is refused now (the words of the notice). */\nexport const notReadyReason = (\n input: Pick<NotReadyInput, 'status' | 'disabled'>,\n): NotReadyReason =>\n input.disabled ? 'disabled' : input.status === 'error' ? 'failed' : 'unavailable'\n\n/** What becomes of a remembered send as the agent's state changes. */\nexport type WaitingSendStep =\n /** Still starting (or another tab's run holds the conversation): keep waiting. */\n | 'wait'\n /** Ready: send what is in the box now. */\n | 'send'\n /** The agent could not start: the wait ends, nothing is sent, the text stays. */\n | 'failed'\n /** Anything else (turned off, no agent any more): the wait ends, nothing is sent. */\n | 'stop'\n\n/** Where a remembered send stands now (see {@link notReadyIntent}). */\nexport const waitingSendStep = (input: NotReadyInput): WaitingSendStep => {\n if (input.disabled) return 'stop'\n if (input.ready) return 'send'\n if (input.status === 'initializing' || input.status === 'running') return 'wait'\n if (input.status === 'error') return 'failed'\n return 'stop'\n}\n\n/** Commands matching what was typed after \"/\" — name prefix first, then substring. */\nexport const filterCommands = (commands: SlashCommand[], query: string): SlashCommand[] => {\n const q = query.toLowerCase()\n if (!q) return commands\n const starts = commands.filter((c) => c.name.toLowerCase().startsWith(q))\n const contains = commands.filter(\n (c) =>\n !starts.includes(c) &&\n (c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q)),\n )\n return [...starts, ...contains]\n}\n\n/**\n * Something attached to the next message:\n * - `text` — its content is inlined into the goal (works with every model);\n * - `image` / `pdf` / `file` — sent to the model as a file part (needs a model\n * that takes that kind — see the core's `agent.capabilities`).\n */\nexport interface ComposerAttachment {\n id: string\n name: string\n kind: 'text' | 'image' | 'pdf' | 'file'\n mediaType: string\n /** Text content (kind 'text'). */\n text?: string\n /** Data URL (kinds image / pdf / file). */\n dataUrl?: string\n bytes: number\n /** Where it was saved in the virtual file system, if it was. */\n path?: string\n /** \"converted from report.pdf\" and the like. */\n note?: string\n /** A recording's length in milliseconds (a voice message). */\n durationMs?: number\n /**\n * A text the host made (`convertFile`): it carries its own note and goes to the model as it is,\n * never cut to an excerpt by `longText` (the host decides how much of a document goes).\n */\n converted?: boolean\n}\n\n/** The kind of an attachment from its media type and name. */\nexport const attachmentKindOf = (mediaType: string, name: string): ComposerAttachment['kind'] => {\n if (mediaType.startsWith('image/')) return 'image'\n if (mediaType === 'application/pdf' || /\\.pdf$/i.test(name)) return 'pdf'\n if (\n mediaType.startsWith('text/') ||\n /json|xml|yaml|javascript|typescript|csv|markdown|x-sh|sql|toml/.test(mediaType) ||\n /\\.(txt|md|markdown|json|csv|tsv|ya?ml|xml|html?|css|m?[jt]sx?|py|sh|log|sql|toml|ini|env)$/i.test(\n name,\n )\n ) {\n return 'text'\n }\n return 'file'\n}\n\n/** What `withAttachments` does with a long text attachment (`<AgentComposer longText>`). */\nexport interface AttachmentTextOptions {\n /**\n * OFF unless given. A text attachment longer than this many characters that was saved in the\n * workspace (`path`) goes as its BEGINNING with a note naming the file that holds it whole -\n * never whole. Only for an agent that can read the file: the core's `createFileTools` over the\n * same workspace (its `fs_read`, or the name `readTool` gives). One the host converted\n * (`converted`), or one without a `path`, goes whole.\n */\n excerptChars?: number\n /** The tool the note tells the model to read on with (default `fs_read`: `createFileTools`' prefix + `read`). */\n readTool?: string\n}\n\n/** The beginning of a long text, cut at a line's end when one is in its second half. */\nexport interface TextExcerpt {\n text: string\n /** The line the excerpt ends in (1-based). */\n lastLine: number\n /** Whether that line is whole in the excerpt (false: it is cut inside it). */\n lineWhole: boolean\n /** Lines of the whole text, counted as the core's `fs_read` counts them (a last line break\n * starts no line). */\n totalLines: number\n}\n\n/** A text's lines as the core's `fs_read` counts them: a text that ends with a line break has no\n * empty last line. */\nexport const lineCountOf = (text: string): number => {\n const lines = text.split('\\n')\n return lines.length > 1 && lines[lines.length - 1] === '' ? lines.length - 1 : lines.length\n}\n\n/**\n * At most `maxChars` characters from the start of `text`: at the last line break when it is in\n * the second half of them (a model reads on by line), never in the middle of a surrogate pair.\n */\nexport const textExcerpt = (text: string, maxChars: number): TextExcerpt => {\n const totalLines = lineCountOf(text)\n if (text.length <= maxChars) return { text, lastLine: totalLines, lineWhole: true, totalLines }\n let end = Math.max(0, Math.floor(maxChars))\n const code = text.charCodeAt(end - 1)\n if (code >= 0xd800 && code <= 0xdbff) end -= 1\n const head = text.slice(0, end)\n const lineEnd = head.lastIndexOf('\\n')\n const atLine = lineEnd >= end / 2\n const cut = atLine ? head.slice(0, lineEnd) : head\n const lastLine = cut.split('\\n').length\n return { text: cut, lastLine, lineWhole: atLine, totalLines }\n}\n\n/**\n * The note in front of an excerpt (for the MODEL, in English like the rest of the goal): how much\n * of the text this is, and how to read on. The file's path is NOT in it - the block's heading\n * names it once (a host that renames a placed file rewrites each mention it counts).\n */\nexport const excerptNote = (\n excerpt: TextExcerpt,\n totalChars: number,\n readTool = 'fs_read',\n): string => {\n const from = excerpt.lineWhole ? excerpt.lastLine + 1 : excerpt.lastLine\n return `[This is only the beginning of a long text: the first ${excerpt.text.length} of ${totalChars} characters (lines 1-${excerpt.lastLine} of ${excerpt.totalLines}${excerpt.lineWhole ? '' : `, line ${excerpt.lastLine} cut`}). The whole text is in the file named above - read on with ${readTool} from line ${from} (startLine / endLine), or search it, only when the answer needs it.]`\n}\n\n/**\n * The goal the agent receives: the typed text followed by each attached TEXT\n * file in a fenced block. Binary attachments travel as file parts instead; the\n * ones saved in the workspace (`path`) are named with it, so a tool can take\n * the file itself (`generate_image`'s reference pictures). With `excerptChars`,\n * a long text saved in the workspace goes as its beginning and the file's path\n * (`AttachmentTextOptions`).\n */\nexport const withAttachments = (\n text: string,\n files: ComposerAttachment[],\n options: AttachmentTextOptions = {},\n): string => {\n const texts = files.filter((f) => f.kind === 'text' && f.text !== undefined)\n // A picture or a file the model gets as itself: where it is in the workspace, so that a tool\n // can take it by its path (generate_image's reference pictures, a PDF to convert).\n const saved = files.filter((f) => f.kind !== 'text' && f.path)\n if (texts.length === 0 && saved.length === 0) return text\n const limit = options.excerptChars\n const blocks = texts.map((f) => {\n const whole = f.text as string\n const cuts = limit !== undefined && f.path !== undefined && !f.converted && whole.length > limit\n const excerpt = cuts ? textExcerpt(whole, limit) : undefined\n const body = excerpt ? excerpt.text : whole\n const fence = body.includes('```') ? '~~~' : '```'\n if (excerpt)\n return `### ${f.name} (its beginning; the whole text: ${f.path})\\n${excerptNote(excerpt, whole.length, options.readTool)}\\n${fence}\\n${body}\\n${fence}`\n const where = f.path ? ` (also saved as ${f.path})` : ''\n return `### ${f.name}${where}\\n${fence}\\n${body}\\n${fence}`\n })\n const kind = (f: ComposerAttachment) =>\n f.kind === 'image' ? 'picture' : f.kind === 'pdf' ? 'PDF' : 'file'\n const lines = saved.map(\n (f) => `- ${kind(f)} \"${f.name.replace(/[\"\\s]+/g, ' ').trim()}\" (also saved as ${f.path})`,\n )\n return [\n text,\n ...(blocks.length ? [`Attached file(s):\\n${blocks.join('\\n\\n')}`] : []),\n ...(lines.length ? [`Also attached:\\n${lines.join('\\n')}`] : []),\n ].join('\\n\\n')\n}\n\n/**\n * The size bounds of an attachment (`<AgentComposer attachments={…}>`; these are the defaults).\n * - `maxBytes`: what is SENT. A file that goes as it is, by its size; one the composer transforms\n * first, by the result - an image it downscales (a 13 MB photo goes as a few hundred KB), a\n * file the host's `convertFile` turns into text (a 30 MB PDF goes as its Markdown).\n * - `maxSourceBytes`: the ORIGINAL of one it transforms, judged before it is read or decoded.\n * - `imageMaxSourcePixels`: the original of an image it downscales, by the pixels its header\n * declares (`imageSizeOf`) - a decoded picture takes ~4 bytes a pixel. A format whose header is\n * not read is held to the bytes only.\n * - `maxImages` / `maxTotalBytes`: ONE message - its pictures, and what all its attachments carry\n * together (`messageOverLimit`), so a batch never meets the provider's request-size error.\n */\nexport interface AttachmentBounds {\n maxBytes: number\n maxSourceBytes: number\n imageMaxSourcePixels: number\n maxImages: number\n maxTotalBytes: number\n}\n\nexport const ATTACHMENT_BOUNDS: AttachmentBounds = {\n maxBytes: 20 * 1024 * 1024,\n // The largest JPEGs a phone writes (a 200 MP shot: ~20-40 MB) pass, and a long PDF with its\n // pictures; past this it is read into memory for nothing the model would get.\n maxSourceBytes: 50 * 1024 * 1024,\n // The largest phone sensor (200 MP: 16320 × 12240) passes, ~800 MB decoded; past this is a\n // scan, a render or a decompression bomb (a PNG of a few KB can declare 30000 × 30000 px).\n imageMaxSourcePixels: 200_000_000,\n // Under what the providers take in one request (Anthropic: 100 pictures, 32 MB; OpenAI: 50 MB).\n maxImages: 20,\n maxTotalBytes: 20 * 1024 * 1024,\n}\n\n/**\n * How an attachment goes to the model: `'convert'` - as the text the host's `convertFile` makes\n * of it (`converts`: the composer will call it for this file); `'downscale'` - an image of a type\n * the composer draws smaller (not GIF - animated - or SVG - drawn at any size), while\n * `imageMaxDimension` is not false; `'none'` - as it is.\n */\nexport type AttachmentTransform = 'none' | 'downscale' | 'convert'\n\nexport const attachmentTransformOf = (input: {\n kind: ComposerAttachment['kind']\n mediaType: string\n imageMaxDimension: number | false\n converts: boolean\n}): AttachmentTransform =>\n input.converts\n ? 'convert'\n : input.kind === 'image' &&\n input.imageMaxDimension !== false &&\n input.mediaType !== 'image/gif' &&\n input.mediaType !== 'image/svg+xml'\n ? 'downscale'\n : 'none'\n\n/** The bound an attachment is over, and its value (bytes or pixels). */\nexport type AttachmentOverLimit = { bound: 'bytes' | 'pixels'; limit: number }\n\n/**\n * Which bound an attachment is over, or undefined. `stage` is when it is judged: `'original'` -\n * the file as picked (and, for an image to downscale, its pixels when known); `'sent'` - what\n * goes to the model (the downscaled image, the converted text, or the file as it is). The\n * original of one the composer transforms is held to `maxSourceBytes` - never below `maxBytes`,\n * so nothing that passed before is refused for its size - and an image's to\n * `imageMaxSourcePixels`; what is sent, to `maxBytes`. One it does not transform: `maxBytes` on\n * the original, as it is.\n */\nexport const attachmentOverLimit = (\n file: { bytes: number; pixels?: number },\n stage: 'original' | 'sent',\n transform: AttachmentTransform,\n bounds: AttachmentBounds,\n): AttachmentOverLimit | undefined => {\n if (stage === 'original' && transform !== 'none') {\n const sourceBytes = Math.max(bounds.maxSourceBytes, bounds.maxBytes)\n if (file.bytes > sourceBytes) return { bound: 'bytes', limit: sourceBytes }\n if (\n transform === 'downscale' &&\n file.pixels !== undefined &&\n file.pixels > bounds.imageMaxSourcePixels\n )\n return { bound: 'pixels', limit: bounds.imageMaxSourcePixels }\n return undefined\n }\n return file.bytes > bounds.maxBytes ? { bound: 'bytes', limit: bounds.maxBytes } : undefined\n}\n\n/**\n * Which limit of ONE message adding `next` to the attachments already in it would break:\n * `'images'` - it is a picture and `maxImages` are there; `'bytes'` - what they would carry\n * together is over `maxTotalBytes`. Each counts as it goes (`bytes`): a picture as downscaled, a\n * converted file as its text, a text file as itself. undefined: it fits.\n */\nexport const messageOverLimit = (\n inMessage: readonly Pick<ComposerAttachment, 'kind' | 'bytes'>[],\n next: Pick<ComposerAttachment, 'kind' | 'bytes'>,\n bounds: Pick<AttachmentBounds, 'maxImages' | 'maxTotalBytes'>,\n): 'images' | 'bytes' | undefined => {\n if (\n next.kind === 'image' &&\n inMessage.filter((a) => a.kind === 'image').length >= bounds.maxImages\n )\n return 'images'\n const total = inMessage.reduce((n, a) => n + a.bytes, 0)\n return total + next.bytes > bounds.maxTotalBytes ? 'bytes' : undefined\n}\n\n/** The transcript label for a message with attachments. */\nexport const attachmentLabel = (text: string, files: ComposerAttachment[]): string =>\n files.length ? `${text}\\n📎 ${files.map((f) => f.name).join(', ')}` : text\n\n/**\n * Can the current model take this attachment? Returns the reason it can't\n * (an actionable sentence), or undefined. `caps` is the core agent's\n * `capabilities` (true / false / undefined per kind; undefined = will try).\n */\nexport const attachmentRefusal = (\n kind: ComposerAttachment['kind'],\n caps: { images?: boolean; pdf?: boolean; files?: boolean } | undefined,\n canConvertPdf = false,\n): string | undefined => {\n if (kind === 'text' || !caps) return undefined\n if (kind === 'image' && caps.images === false) {\n return \"This model can't see images — switch to a vision-capable model (Gemini, Claude, GPT-4o/5) to attach one.\"\n }\n if (kind === 'pdf' && caps.pdf === false && !canConvertPdf) {\n return \"This model can't read PDF files — convert it to text first, or switch to Gemini, Claude or GPT-4o/5.\"\n }\n if (kind === 'file' && caps.files === false) {\n return \"This model can't take file attachments — paste the text instead.\"\n }\n return undefined\n}\n\n/** One run of a chip menu's rows that share a `section` (none: rows drawn without a heading). */\nexport interface MenuSection<T> {\n section?: string\n options: T[]\n}\n\n/**\n * A chip menu's rows as the menu draws them: each run of rows that share a `section` under one\n * heading, in the order given (the host orders them - the keyboard goes the same way). A section\n * that comes back later is a new run: rows are never moved. Pure.\n */\nexport const menuSections = <T extends { section?: string }>(\n options: readonly T[],\n): MenuSection<T>[] => {\n const out: MenuSection<T>[] = []\n for (const option of options) {\n const section = option.section || undefined\n const last = out[out.length - 1]\n if (last && last.section === section) last.options.push(option)\n else out.push({ ...(section ? { section } : {}), options: [option] })\n }\n return out\n}\n\n/**\n * The row a key moves to in a menu of `count` rows from row `index` (-1: none focused): ArrowDown /\n * ArrowUp to the next / previous (around the ends), Home / End to the first / last. Undefined for\n * any other key, or an empty menu. Pure.\n */\nexport const menuKeyTarget = (key: string, index: number, count: number): number | undefined => {\n if (count <= 0) return undefined\n switch (key) {\n case 'ArrowDown':\n return index < 0 ? 0 : (index + 1) % count\n case 'ArrowUp':\n return index < 0 ? count - 1 : (index - 1 + count) % count\n case 'Home':\n return 0\n case 'End':\n return count - 1\n default:\n return undefined\n }\n}\n\n/** 950 → \"0s\", 61_000 → \"1m 1s\", 3_725_000 → \"1h 2m\". */\nexport const formatElapsed = (ms: number): string => {\n const s = Math.max(0, Math.floor(ms / 1000))\n if (s < 60) return `${s}s`\n const m = Math.floor(s / 60)\n if (m < 60) return `${m}m ${s % 60}s`\n return `${Math.floor(m / 60)}h ${m % 60}m`\n}\n\n/** A banner above the input. */\nexport interface ComposerNotice {\n /** Stable per occurrence, so a dismissal sticks until something new happens. */\n id: string\n tone: 'info' | 'warn' | 'error'\n text: string\n}\n\nconst kTokens = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : `${n}`\n\n/** The banner texts (override for another language). */\nexport interface NoticeTexts {\n /** A limit stopped the run; `kind` is 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls'. */\n limit: (kind: string, used: number, cap: number) => string\n /** The context was compacted. */\n compacted: (scope: string, before: number, after: number) => string\n}\n\nexport const defaultNoticeTexts: NoticeTexts = {\n limit: (kind, used, cap) => {\n const calls = kind === 'tool-calls'\n const what = calls ? 'Tool-call' : `${kind[0].toUpperCase()}${kind.slice(1)}-token`\n const amount = calls ? `${used}/${cap} calls` : `${kTokens(used)}/${kTokens(cap)} tokens`\n return `${what} limit reached · ${amount} — the agent stopped early and answered with what it had`\n },\n compacted: (scope, before, after) =>\n `Context compacted (${scope}) · ${kTokens(before)} → ${kTokens(after)} tokens`,\n}\n\n/**\n * The notices worth a banner for the current run: a limit that stopped it, the\n * latest compaction, a failure to start. Pure — derived from the UI state.\n */\nexport const noticesOf = (\n state: AgentUiState,\n texts: Partial<NoticeTexts> = {},\n): ComposerNotice[] => {\n const t = { ...defaultNoticeTexts, ...texts }\n const out: ComposerNotice[] = []\n if (state.status === 'error' && state.error) {\n out.push({ id: `error:${state.error}`, tone: 'error', text: state.error })\n }\n if (state.budget) {\n const b = state.budget\n out.push({\n id: `budget:${state.goal ?? ''}:${b.kind}:${b.cap}`,\n tone: 'warn',\n text: t.limit(b.kind, b.tokens, b.cap),\n })\n }\n const last = state.compactions.at(-1)\n if (last) {\n out.push({\n id: `compact:${state.compactions.length}:${last.beforeTokens}:${last.afterTokens}`,\n tone: 'info',\n text: t.compacted(last.scope, last.beforeTokens, last.afterTokens),\n })\n }\n return out\n}\n\n/** A recording's length as a clock: `0:07`, `12:30`, `1:02:05`. */\nexport const formatClock = (ms: number): string => {\n const s = Math.max(0, Math.floor(ms / 1000))\n const two = (n: number) => String(n).padStart(2, '0')\n const h = Math.floor(s / 3600)\n const m = Math.floor((s % 3600) / 60)\n return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${m}:${two(s % 60)}`\n}\n\n/**\n * What to say of a microphone or dictation failure: the recognizer's own words when it gave some\n * (a host's transcription error, already in its language), else the label of the code - a refused\n * permission says how to allow it again.\n */\nexport const micProblemText = (\n code: string | undefined,\n message: string | undefined,\n labels: Pick<\n AgentLabels,\n 'micDenied' | 'micMissing' | 'micBusy' | 'micUnsupported' | 'dictationFailed' | 'microphone'\n >,\n): string => {\n if (code === 'not-allowed' || code === 'service-not-allowed') return labels.micDenied\n if (code === 'audio-capture') return labels.micMissing\n if (code === 'busy') return labels.micBusy\n if (code === 'unsupported') return labels.micUnsupported\n if (message) return message\n return code && code !== 'transcription' && code !== 'failed'\n ? `${labels.dictationFailed} (${code})`\n : labels.dictationFailed\n}\n\n/** A voice message's file name, from when it was recorded: `voice-2026-11-29-1052.webm`. */\nexport const voiceMessageName = (at: Date, extension: string): string => {\n const two = (n: number) => String(n).padStart(2, '0')\n return `voice-${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())}-${two(\n at.getHours(),\n )}${two(at.getMinutes())}${two(at.getSeconds())}.${extension}`\n}\n\n// ── the message box's limit (`<AgentComposer longText>`) ─────────────────────\n\n/** The counter shows from this share of the limit on (\"3,650 / 4,000\"). */\nexport const INPUT_COUNTER_FROM = 0.9\n\n/** Whether the counter is shown for `count` characters of `max`. */\nexport const inputCounterShown = (count: number, max: number): boolean =>\n count >= Math.ceil(max * INPUT_COUNTER_FROM)\n\n/**\n * A text's length as the box will hold it: a textarea keeps every line break as one `\\n` (a\n * pasted CRLF or CR becomes LF), and its value is counted in UTF-16 code units - what the\n * counter shows and the limit is judged by (an emoji is 2, a letter 1, in every browser).\n */\nexport const boxLength = (text: string): number => text.replace(/\\r\\n?/g, '\\n').length\n\n/**\n * Whether inserting `inserted` into `current` over its selection `[start, end)` keeps the box\n * within `max` characters (`boxLength`).\n */\nexport const insertionFits = (\n current: string,\n start: number,\n end: number,\n inserted: string,\n max: number,\n): boolean => current.length - Math.max(0, end - start) + boxLength(inserted) <= max\n\n/**\n * Whether `text` is ONE character as a person types it: one grapheme (a letter, an emoji with its\n * modifiers, a line break) - what a key press inserts. At the limit that is typing, and it stops;\n * anything longer is never cut.\n */\nexport const isOneCharacter = (text: string): boolean => {\n if (text.length === 0) return false\n if (text.length === 1) return true\n const Segmenter = (Intl as { Segmenter?: typeof Intl.Segmenter }).Segmenter\n if (Segmenter) {\n const it = new Segmenter(undefined, { granularity: 'grapheme' })\n .segment(text)\n [Symbol.iterator]()\n it.next()\n return it.next().done === true\n }\n return [...text].length === 1\n}\n\n/**\n * Where text goes in a box with a limit:\n * - `'insert'` - into the box: it fits (or there is no limit);\n * - `'stop'` - nowhere, silently: ONE character typed into a full box (`fromBox`: it came through\n * the box's own editing - a key, a paste of one letter) - typing stops at the limit;\n * - `'attach'` - the WHOLE of it as a text attachment (never cut);\n * - `'refuse'` - nowhere, said in words: attachments are off.\n * Dictation and a draft are not `fromBox`: a single dictated word is attached, never dropped.\n */\nexport const longTextRoute = (input: {\n current: string\n start: number\n end: number\n inserted: string\n max: number | undefined\n attachments: boolean\n fromBox?: boolean\n}): 'insert' | 'stop' | 'attach' | 'refuse' => {\n if (input.max === undefined) return 'insert'\n if (insertionFits(input.current, input.start, input.end, input.inserted, input.max))\n return 'insert'\n if (input.fromBox && isOneCharacter(input.inserted)) return 'stop'\n return input.attachments ? 'attach' : 'refuse'\n}\n\nconst isHigh = (code: number) => code >= 0xd800 && code <= 0xdbff\nconst isLow = (code: number) => code >= 0xdc00 && code <= 0xdfff\n\n/**\n * What an edit the composer could not stop beforehand inserted (an IME's commit, an insertion\n * whose `beforeinput` cannot be cancelled): the part of `next` that is not in `prev`, found by\n * their common start and end - around the caret, never splitting a surrogate pair. Undefined\n * when the box is within `max`, or did not grow (a deletion is never taken back).\n */\nexport const overflowOf = (\n prev: string,\n next: string,\n max: number,\n): { inserted: string } | undefined => {\n if (next.length <= max || next.length <= prev.length) return undefined\n let head = 0\n const most = Math.min(prev.length, next.length)\n while (head < most && prev.charCodeAt(head) === next.charCodeAt(head)) head += 1\n if (head > 0 && isHigh(next.charCodeAt(head - 1)) && isLow(next.charCodeAt(head))) head -= 1\n let tail = 0\n while (\n tail < most - head &&\n prev.charCodeAt(prev.length - 1 - tail) === next.charCodeAt(next.length - 1 - tail)\n )\n tail += 1\n const to = next.length - tail\n if (tail > 0 && isLow(next.charCodeAt(to)) && isHigh(next.charCodeAt(to - 1))) tail -= 1\n return { inserted: next.slice(head, next.length - tail) }\n}\n\n/**\n * The name of a text attachment the composer made from a paste or a dictation, by when it was\n * made in local time: `pasted-2026-11-30-140509.txt` (`-2`, `-3`… when the message already holds\n * that name: two pastes in one second must not land in one file). `.txt`: it is plain text as it\n * was given - not Markdown (a paste of code or a log is no document) - and every reader of the\n * workspace (`fs_read`, a search index, a preview) takes it as text.\n */\nexport const longTextName = (\n at: Date,\n kind: 'pasted' | 'dictation' = 'pasted',\n taken: readonly string[] = [],\n): string => {\n const two = (n: number) => String(n).padStart(2, '0')\n const stem = `${kind}-${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())}-${two(\n at.getHours(),\n )}${two(at.getMinutes())}${two(at.getSeconds())}`\n let name = `${stem}.txt`\n for (let n = 2; taken.includes(name); n += 1) name = `${stem}-${n}.txt`\n return name\n}\n\n// ── saving a message's attachments (`<AgentComposer files>`) ────────────────\n\n/** What `saveAttachments` needs of a workspace (the core's `VirtualFileSystem` has it). */\nexport interface AttachmentFiles {\n read(path: string): Promise<unknown>\n write(path: string, content: string, opts?: { mimeType?: string }): Promise<unknown>\n writeDataUrl(path: string, dataUrl: string): Promise<unknown>\n delete(path: string): Promise<unknown>\n /**\n * A workspace that NAMES a message's attachments itself gives this, and then it decides where\n * each one goes: it is asked for `/attachments/<name>` and answers where the file is - never\n * over another file (beside it, `-2`…; or the very same file already there, `created: false`,\n * which is then never deleted again). The composer names THAT path to the model. Without it the\n * composer picks a name no file has (`freeAttachmentPath`) and writes there.\n */\n saveAttachment?(\n path: string,\n content: string,\n opts: { mimeType: string; encoding: 'utf8' | 'base64' },\n ): Promise<{ path: string; created: boolean }>\n}\n\n/** A data URL's parts as the core's `writeDataUrl` reads them (base64 or URL-encoded text). */\nexport const dataUrlParts = (\n dataUrl: string,\n): { content: string; encoding: 'utf8' | 'base64'; mimeType: string } => {\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 ? { content: m[3], encoding: 'base64', mimeType }\n : { content: decodeURIComponent(m[3]), encoding: 'utf8', mimeType }\n}\n\n/** One path segment out of an attachment's name (`a b.txt` → `a_b.txt`). */\nexport const attachmentFileName = (name: string): string =>\n name.replace(/[^\\w.-]+/g, '_').slice(0, 80) || 'file'\n\n/**\n * Where an attachment goes in the workspace: `/attachments/<name>`, or - when a file is there\n * already, or this message took the path - `<stem>-2<ext>`, `-3`…: never over another file.\n */\nexport const freeAttachmentPath = async (\n name: string,\n taken: (path: string) => Promise<boolean>,\n): Promise<string> => {\n const file = attachmentFileName(name)\n const dot = file.lastIndexOf('.')\n const stem = dot > 0 ? file.slice(0, dot) : file\n const ext = dot > 0 ? file.slice(dot) : ''\n let path = `/attachments/${file}`\n for (let n = 2; await taken(path); n += 1) path = `/attachments/${stem}-${n}${ext}`\n return path\n}\n\n/** What `saveAttachments` did: every file written, or the ones it could not write (none kept). */\nexport type SavedAttachments = { saved: true } | { saved: false; failed: string[] }\n\n/**\n * Write a message's attachments into the workspace before it is sent, each as a NEW file, and set\n * their `path`. Who names the file: the workspace, when it has `saveAttachment` (a host's policy -\n * the app keeps one file of the same bytes once); else this, by `freeAttachmentPath`. Never both:\n * a host that places a file the library already numbered writes it twice, under two names. All or\n * nothing: when one write fails (no room, over the workspace's file size, any error) the files\n * this message created are deleted again, no `path` is set, and the names of the ones that failed\n * come back - the message must not go (its text would otherwise reach the model whole, or not at\n * all).\n */\nexport const saveAttachments = async (\n files: AttachmentFiles,\n items: ComposerAttachment[],\n): Promise<SavedAttachments> => {\n const created: string[] = []\n const paths = new Map<ComposerAttachment, string>()\n const mine = new Set<string>()\n const taken = async (path: string) => mine.has(path) || (await files.read(path)) !== undefined\n for (const a of items) {\n if (!a.dataUrl && a.text === undefined) continue\n try {\n if (files.saveAttachment) {\n const { content, encoding, mimeType } = a.dataUrl\n ? dataUrlParts(a.dataUrl)\n : { content: a.text as string, encoding: 'utf8' as const, mimeType: a.mediaType }\n const placed = await files.saveAttachment(\n `/attachments/${attachmentFileName(a.name)}`,\n content,\n { mimeType, encoding },\n )\n if (placed.created) created.push(placed.path)\n paths.set(a, placed.path)\n continue\n }\n const path = await freeAttachmentPath(a.name, taken)\n mine.add(path)\n if (a.dataUrl) await files.writeDataUrl(path, a.dataUrl)\n else await files.write(path, a.text as string, { mimeType: a.mediaType })\n created.push(path)\n paths.set(a, path)\n } catch {\n for (const path of created) {\n try {\n await files.delete(path)\n } catch {\n /* best effort: the failure is what is said */\n }\n }\n return { saved: false, failed: [a.name] }\n }\n }\n for (const [a, path] of paths) a.path = path\n return { saved: true }\n}\n","import type {\n DecisionFallbackReason,\n EscalationReason,\n ModelTier,\n TierReason,\n ToolApprovalMode,\n} from '@dudko.dev/agent-web'\nimport { defaultNoticeTexts, type NoticeTexts } from './composer.js'\nimport type { ElicitationIssueKind, ElicitationOutcomeReason } from './elicitation.js'\nimport type { FileKind } from './file-kinds.js'\nimport type { McpAppSandboxReason } from './mcp-app.js'\nimport type { QuestionOutcomeReason } from './questions.js'\nimport type { AgentStatus } from './types.js'\n\n/**\n * Every string the pre-styled components render — override any of them for\n * another language or wording, per component (`labels` prop) or for a whole\n * tree (`<AgentLabelsProvider>`). Counted phrases are functions, so languages\n * with several plural forms can say them properly.\n */\nexport interface AgentLabels {\n // ── chat panel ─────────────────────────────────────────────────────────────\n emptyState: string\n status: Record<AgentStatus, string>\n history: string\n newChat: string\n files: string\n totalUsage: string\n showHistory: string\n showFiles: string\n close: string\n\n // ── transcript ─────────────────────────────────────────────────────────────\n steps: (n: number) => string\n toolCalls: (n: number) => string\n subagents: (n: number) => string\n skillsUsed: (names: string) => string\n /** \"learned: a, b\" - lessons the agent wrote down in this run. */\n learnedNow: (names: string) => string\n /** \"2 web requests\" - what the model fetched in this run. */\n fetches: (n: number) => string\n /** Why a web request was refused. */\n fetchRefused: (reason: string) => string\n answerThoughts: string\n /** In place of the answer of a run that was stopped before it wrote any (`ChatMessage.stopped`). */\n answerStopped: string\n stepThoughts: string\n usageTitle: string\n attachments: string\n planned: string\n replanned: (mode: string, reason: string) => string\n\n // ── notebook (the agent's own lessons) ─────────────────────────────────────\n notebookTitle: string\n notebookEmpty: string\n notebookForget: string\n notebookRevision: (n: number) => string\n /** Before the sources a lesson came from. */\n notebookFrom: string\n\n // ── memory cards (a fact the host's app saved, changed or forgot: `MemoryCard`) ──\n /** Before a fact that was just saved. */\n memorySaved: string\n /** Before a fact that was just changed. */\n memoryUpdated: string\n /** Before a fact that was just forgotten. */\n memoryForgotten: string\n /** The card's button that takes it back. */\n memoryUndo: string\n /** In place of the button once it was taken back. */\n memoryUndone: string\n\n // ── composer ───────────────────────────────────────────────────────────────\n placeholder: string\n listening: string\n message: string\n dropHint: string\n attach: string\n attachTitle: string\n commands: string\n commandsTitle: string\n send: string\n stop: string\n dismiss: string\n remove: (name: string) => string\n dictate: string\n dictateTitle: string\n stopDictation: string\n /**\n * The mic button's name while it listens: that it listens, and that a tap finishes (the title\n * stays `stopDictation`).\n */\n micListening: string\n microphone: string\n /** While a recording recognizer waits for its model (`useSpeechToText().finishing`). */\n transcribing: string\n /** The microphone was refused (`not-allowed`): how to allow it again. */\n micDenied: string\n /** No microphone on the device (`audio-capture`). */\n micMissing: string\n /** The microphone is held by another app (`busy`). */\n micBusy: string\n /** No recording here at all (`unsupported`: an insecure page, no `MediaRecorder`). */\n micUnsupported: string\n /** A dictation that failed without words of its own. */\n dictationFailed: string\n /** The composer's voice-message button (`voiceMessage` of the composer). */\n recordVoiceMessage: string\n /**\n * A recording, in words: the title of a chat a voice message starts (until its transcript is\n * there), the name a screen reader gives a message that is only a recording.\n */\n voiceMessage: string\n /** The length shown beside a voice message's player (`formatClock`: \"0:07\"). */\n audioDuration: (clock: string) => string\n /** The strip while a voice message is recorded: \"Recording 0:07\". */\n recording: (elapsed: string) => string\n /** Its button that keeps the recording as an attachment. */\n recordingDone: string\n /** Its button that throws the recording away. */\n recordingCancel: string\n /** A voice message that reached the longest recording and was stopped by itself. */\n recordingLimit: string\n model: string\n thinking: string\n toolConsent: string\n modes: Record<ToolApprovalMode, { label: string; hint: string }>\n timerRunning: string\n timerLast: string\n agents: (n: number) => string\n agentsTitle: string\n /** Banners: a limit stopped the run / the context was compacted. */\n notices: NoticeTexts\n /** No longer shown: a message of attachments only is shown as its attachments, with no text. */\n attachmentsOnly: string\n seeAttachments: string\n tooLarge: (name: string, mb: number) => string\n /** A picture with more pixels than `attachments.imageMaxSourcePixels` (in millions). */\n tooManyPixels: (name: string, megapixels: number) => string\n binaryText: (name: string) => string\n /** An attachment's note: an image sent smaller (`size` is `bytes` of the original). */\n downscaledFrom: (size: string) => string\n /** An attachment's note: a file sent as the text `convertFile` made of it. */\n convertedFrom: (name: string) => string\n /** Files left out: the message has `attachments.maxImages` pictures (`names`: up to three). */\n tooManyImages: (names: string, max: number) => string\n /** Files left out: the message would carry more than `attachments.maxTotalBytes` (in MB). */\n messageTooLarge: (names: string, mb: number) => string\n /** A paste too long for the message box, as an attachment's note (`longText`): its length. */\n pastedText: (chars: number) => string\n /** The same for a dictation too long for the box. */\n dictatedText: (chars: number) => string\n /** The box's counter near its limit (`longText`): \"3,650 / 4,000\". */\n inputCount: (count: number, max: number) => string\n /** The counter's label (its tooltip and accessible name). */\n inputLimit: (max: number) => string\n /** Said (politely, to a screen reader too) when the box is full. */\n inputLimitReached: (max: number) => string\n /** The same with attachments off: no file is promised. */\n inputLimitFull: (max: number) => string\n /** Said to a screen reader when a paste (or any insertion) became a file: its length. */\n pastedAsFile: (chars: number) => string\n /** The same for a dictation that became a file. */\n dictatedAsFile: (chars: number) => string\n /** A long paste with attachments off: it is not inserted, and not cut either. */\n longTextRefused: (max: number) => string\n /**\n * An attachment could not be written into the workspace (no room, too large, an error): the\n * message was NOT sent and everything stays in the composer.\n */\n attachmentSaveFailed: (names: string) => string\n commandGroups: { commands: string; consent: string; skills: string }\n commandDescriptions: {\n compact: string\n new: string\n stop: string\n autopilot: string\n ask: string\n askAll: string\n readOnly: string\n think: (levels: string) => string\n }\n /** `off` = the provider's default; `none` = thinking switched off. */\n thinkingLevels: { off: string; none: string; low: string; medium: string; high: string }\n\n // ── files panel ────────────────────────────────────────────────────────────\n filesEmpty: string\n upload: string\n download: string\n delete: string\n preview: string\n bytes: (n: number) => string\n\n // ── chat history ───────────────────────────────────────────────────────────\n historyEmpty: string\n deleteChat: string\n messagesCount: (n: number) => string\n\n // ── consent prompt ─────────────────────────────────────────────────────────\n approvalLead: string\n approve: string\n alwaysAllow: string\n deny: string\n declinedReason: string\n readOnlyTool: string\n consentWaiting: string\n consentAllowed: string\n consentDenied: (reason?: string) => string\n\n // ── steering a run that is going ───────────────────────────────────────────\n /** Composer placeholder while the agent works (what you type is sent to it). */\n placeholderBusy: string\n /** The send button while the agent works. */\n steer: string\n /** Shown when files are attached while the agent works (they can't be added then). */\n noAttachmentsWhileBusy: string\n\n // ── a send before the agent is ready ───────────────────────────────────────\n /** A send made while the agent starts: remembered, made when the agent is ready (a notice). */\n sendWhenReady: string\n /** The send button's name while the agent starts (a click is remembered). */\n sendWhenReadyButton: string\n /** The remembered send's notice: the button that cancels it. */\n cancelSendWhenReady: string\n /** Nothing was sent: the agent could not start (its error is shown on its own). */\n notSentFailed: string\n /** Nothing was sent: there is no agent to take it (no model yet, say). */\n notSentUnavailable: string\n /** Nothing was sent: the composer is turned off. */\n notSentDisabled: string\n /** A message waiting to reach the agent. */\n queuedWaiting: string\n /**\n * What the user sent, waiting with a run of this tab's that waits for the conversation's other\n * run (`sessionBusy`) - in another tab, or in this one - to finish. Shown only while that lasts.\n */\n queuedForSession: (heldBy: 'another-tab' | 'this-tab') => string\n /**\n * What this tab said to the conversation's run in another tab (`sendRemote`), while that tab has\n * not answered (it may be in the background, frozen by the browser): it is not refused.\n */\n queuedForOtherTab: string\n /** Where a note landed: between tool calls / after a step / before the answer. */\n noteAt: Record<'round' | 'step' | 'final', string>\n /** Messages the run ended without delivering, offered for sending. */\n undelivered: (n: number) => string\n sendUndelivered: string\n discardUndelivered: string\n stopSubagent: string\n subagentStopped: string\n\n // ── another tab of the same site ───────────────────────────────────────────\n /** The conversation is running in another tab: it is shown here live, and Stop / typing go there. */\n remoteRunning: string\n /** That run waits for a person's answer - which is given in that tab. */\n remoteWaitingConsent: string\n /** That tab closed (or crashed) before the run finished. */\n remoteGone: string\n /** This tab's run waits for the other run of the conversation (in another tab, or in this one). */\n sessionBusy: (heldBy: 'another-tab' | 'this-tab') => string\n /** The mark on a message written to this run from another tab (queued, and where it arrived). */\n fromAnotherTab: string\n\n // ── steps / tool calls ─────────────────────────────────────────────────────\n failed: string\n toolCostTitle: string\n\n // ── model tiers and escalation ─────────────────────────────────────────────\n /** The tier badge on a step. */\n tierNames: Record<ModelTier, string>\n /** The badge's tooltip: why the step started on its tier. */\n tierReasons: Record<TierReason, string>\n /** Why a step was retried on a stronger model. */\n escalationReasons: Record<EscalationReason, string>\n /** \"Escalated: light → strong (reported a blocker)\" - the names and the reason are already labels. */\n escalated: (from: string, to: string, reason: string) => string\n /** Opens what the failed attempt had written. */\n escalatedAttemptText: string\n /** \"1 escalation\" in the activity summary. */\n escalations: (n: number) => string\n /** On a tool call made by an attempt that was escalated. */\n attemptTag: (n: number) => string\n /** On a write the core did not run a second time (it succeeded in an earlier attempt). */\n replayed: string\n replayedTitle: string\n /** The replanner call failed; the run went on with the plan it had. */\n replanFailed: string\n\n // ── the subagent tree ──────────────────────────────────────────────────────\n /** The tag on a helper the model started itself (`spawn_subagent`). */\n subagentHelper: string\n /** A node's status, in words. */\n subagentStatus: Record<'running' | 'done' | 'error' | 'stopped', string>\n /** \"12k tokens\" - what was spent under a node; the number is already formatted. */\n subagentTokens: (tokens: string) => string\n /** \"tools: fs_read, web_fetch\" - what a helper was given. */\n subagentTools: (names: string) => string\n /** A helper that was given no tools at all (it only reasons). */\n subagentNoTools: string\n /** The consent prompt of a helper's call: `role` is what the model wrote for it, if anything. */\n approvalLeadHelper: (role: string | undefined, depth: number) => string\n\n // ── generated media and transcripts ────────────────────────────────────────\n /** Alt text of a generated image; `path` is where it is in the workspace. */\n mediaImage: (path: string) => string\n /** A picture in the transcript: the thumbnail's accessible name (it opens the viewer). */\n imageOpen: (name: string) => string\n /** The image viewer: the other pictures of the message, the zoom switch, \"2 of 5\". */\n imagePrevious: string\n imageNext: string\n imageZoom: string\n imageCount: (index: number, total: number) => string\n /** The accessible name of a generated audio player. */\n mediaAudio: (path: string) => string\n /** A generated file that cannot be shown here (no workspace, the file is gone, an unknown type). */\n mediaFile: (path: string) => string\n /** Under a generated picture made with reference pictures: their names (\"me.jpg, dog.png\"). */\n mediaReferences: (names: string) => string\n /** ...and when the image model took none: the picture was made from the text alone. */\n mediaReferencesUnused: (names: string) => string\n /** The summary of a transcript block. */\n transcriptOf: (name: string) => string\n /** Says whose words a transcript is: the content of the user's file, not the agent's. */\n transcriptNote: string\n /** The accessible name of an attached audio file's player (a voice message). */\n audioAttachment: (name: string) => string\n\n // ── read aloud (`readAloud`) ───────────────────────────────────────────────\n readAloud: string\n readAloudPause: string\n readAloudResume: string\n readAloudStop: string\n /** While the audio is made (a provider's voice). */\n readAloudLoading: string\n /** Said in place of a code block - the code is not read out. Empty: the block is skipped. */\n readAloudCode: string\n /** A reading that failed without words of its own. */\n readAloudFailed: string\n\n // ── files written in a turn ────────────────────────────────────────────────\n /** Above the chips: \"3 files written in this turn\". */\n filesWritten: (n: number) => string\n /**\n * Above the chips of the workspace files an answer NAMES (`showNamedFiles`) - it did not write\n * them: \"2 files in this answer\".\n */\n filesNamed: (n: number) => string\n /** In the activity summary: \"3 files\". */\n filesCount: (n: number) => string\n /** The link that opens the Files panel. */\n showInFiles: string\n /** What a file is, on its chip. */\n fileKinds: Record<FileKind, string>\n /** The open button of a chip (accessible name); `name` is the file's name. */\n fileOpen: (name: string) => string\n /** The same button while the preview is open. */\n fileClose: (name: string) => string\n /**\n * A link in an answer to a workspace file (`WorkspaceFileLink`): the button's accessible name,\n * from the link's words and the file's name.\n */\n fileLinkOpen: (text: string, name: string) => string\n /** The download button of a chip (accessible name). */\n fileDownload: (name: string) => string\n /** On a chip: the subagent that wrote the file. */\n fileBy: (name: string) => string\n /** On a chip whose file is not in the workspace any more. */\n fileGone: string\n /** In the preview of a file that cannot be shown as text or as an image. */\n fileNoPreview: string\n /** Under a preview that shows only the first `chars` characters. */\n fileCut: (chars: number) => string\n /** Unfold / fold a long text preview. */\n fileShowRest: string\n fileShowLess: string\n /** The two views of a text file the host can render (Markdown). */\n fileRendered: string\n fileSource: string\n closePreview: string\n /** Under a source view: \"64 lines\". */\n fileLines: (n: number) => string\n\n // ── HTML preview (the sandboxed frame) ─────────────────────────────────────\n /** The host's label on the frame of an HTML file. */\n htmlFrameTitle: string\n /** The two badges under it, while the page is shown. */\n htmlSandboxed: string\n htmlNoNetwork: string\n /** In their place, while the source is shown. */\n htmlSourceNote: string\n /** In the frame's footer. */\n htmlScripts: (on: boolean) => string\n /** The files the page links to that the preview does not load. */\n htmlLinkedFiles: (names: string) => string\n /** A page too large to frame. */\n htmlTooLarge: string\n /** The button that makes the frame taller / back. */\n htmlTaller: string\n htmlShorter: string\n /** The accessible name of the frame itself. */\n htmlFrameName: (path: string) => string\n\n // ── usage: calls that are not tokens ───────────────────────────────────────\n /**\n * `n` is the CALLS to the media models, failed ones included (`usage.mediaCalls`: what the\n * run's cap counts). `made` is what came of them (`imagesGenerated`, `speechCharacters`,\n * `transcriptionSeconds`): a label that says \"pictures made\" counts `made.imagesGenerated`,\n * never `n` - a call that failed made nothing. An empty string shows nothing.\n */\n usageMedia: (\n n: number,\n made: { imagesGenerated: number; speechCharacters: number; transcriptionSeconds: number },\n ) => string\n usageDecisions: (n: number) => string\n\n // ── decision model ─────────────────────────────────────────────────────────\n /** \"decision model: continue (0.93)\" - its answer was used; the probability is formatted. */\n decisionAccepted: (choice: string, confidence: string) => string\n /** \"decision model fell back: low confidence (0.41 < 0.8)\" - the ordinary model call ran. */\n decisionFellBack: (reason: string, detail: string) => string\n decisionReasons: Record<DecisionFallbackReason, string>\n\n // ── web search results ─────────────────────────────────────────────────────\n /** Before the query of a `web_search` call. */\n searchQuery: string\n searchNoResults: string\n /** Results left out by the egress policy. */\n searchFiltered: (n: number) => string\n /** The list was cut to the cap. */\n searchTruncated: string\n\n // ── a question from an MCP server (elicitation) ────────────────────────────\n /** The accessible name of the prompt. */\n elicitationTitle: string\n /** The host's own line: which server asks. */\n elicitationLead: (server: string) => string\n /** The same when the call that asks is a helper's; `role` is what the model wrote for it. */\n elicitationLeadHelper: (server: string, role: string | undefined) => string\n /** Before the tool's name: \"during\". */\n elicitationDuring: string\n /** \"1 of 3\" - several questions are waiting. */\n elicitationCount: (index: number, total: number) => string\n /** The caption over the server's own words. */\n elicitationFrom: (server: string) => string\n /** The meaning of the mark on a required field. */\n elicitationRequired: string\n /** The empty choice of a select. */\n elicitationChoose: string\n elicitationSubmit: string\n elicitationDecline: string\n elicitationCancel: string\n /** Why a field's value does not fit; `field` is its label, `limit` the rule's number. */\n elicitationErrors: Record<ElicitationIssueKind, (field: string, limit?: number) => string>\n /** Over the buttons, after a submit that was refused. */\n elicitationFix: (n: number) => string\n /** The host's line of a link request; the host name follows. */\n elicitationUrlLead: (server: string) => string\n /** The caption over the whole address. */\n elicitationUrlFull: string\n elicitationOpen: string\n /** After the link was opened. */\n elicitationOpened: string\n /** \"I have finished there\" - the accept of a link request. */\n elicitationUrlDone: string\n /** A link that will not be opened from here. */\n elicitationUrlRefused: string\n /** \"Expires in 4:05\". */\n elicitationExpiresIn: (time: string) => string\n /** The same note when the time left is not known. */\n elicitationExpires: string\n /** A question nobody answered: the server, and why (one of `elicitationReasons`). */\n elicitationAutomatic: (server: string, reason: string) => string\n /** Why a question was answered without anybody deciding, by the core's reason (+ `stopped`). */\n elicitationReasons: Record<ElicitationOutcomeReason, string>\n elicitationDismiss: string\n\n // ── a question from the agent (ask_user) ───────────────────────────────────\n /** The host's own line over the model's question. */\n questionLead: string\n /** The same when a helper asks; `role` is what the model wrote for it. */\n questionLeadHelper: (role: string | undefined, depth: number) => string\n /** \"1 of 2\" - several questions are waiting. */\n questionCount: (index: number, total: number) => string\n /** Under a question that takes several options. */\n questionSeveral: string\n /** Sends the options picked, or the person's own words. */\n questionSend: string\n /** Opens the field for an answer in the person's own words. */\n questionOther: string\n /** That field's label. */\n questionOtherLabel: string\n /** No answer: the agent goes on with its best judgment. */\n questionSkip: string\n /** \"...in 4:05\": when the agent stops waiting. */\n questionExpiresIn: (time: string) => string\n /** A question asked by the run in another tab: shown here, answered there. */\n questionRemote: string\n /** The agent went on without an answer; `reason` is one of `questionReasons`. */\n questionAutomatic: (reason: string) => string\n /** Why, by the core's reason (+ `timeout`, `stopped`). */\n questionReasons: Record<QuestionOutcomeReason, string>\n questionDismiss: string\n\n // ── MCP Apps (an app a server's tool came with) ────────────────────────────\n /** The host's label on an app's frame: \"App from server “travel”\". */\n appFrom: (server: string) => string\n /** The badge beside it. */\n appSandboxed: string\n /** The badge when the app runs on an origin of its own (the sandbox page answered). */\n appSandboxedOrigin: string\n /** The note (menu, badge title) for that: the sandbox origin. */\n appSandboxOrigin: (origin: string) => string\n /** A sandbox URL is set, and the app runs in the opaque frame all the same: why. */\n appSandboxFallback: (reason: string) => string\n /** The reasons, by `McpAppSandboxReason`. */\n appSandboxReasons: Record<McpAppSandboxReason, string>\n /** The app loaded its sandbox page again (navigated it) and was stopped. */\n appSandboxBroken: string\n /** The badge while a request of the app waits for the user. */\n appWaiting: string\n /** The \"waiting for you\" badge is a button: its title (it takes the focus to the prompt). */\n appWaitingFocus: string\n /** The region of an app's prompts drawn in its panel / sheet / full screen chrome. */\n appPromptsLabel: (server: string) => string\n /** The tag on the tool call an app came with, and the activity summary's count. */\n appTag: string\n appsCount: (n: number) => string\n appLoading: string\n /** The app could not be read or is refused (`reason` is the core's message). */\n appFailed: (reason: string) => string\n /** No connection to its server (not connected any more, or apps are off). */\n appUnavailable: (server: string) => string\n /** The folded line: \"App from server “travel” · hidden [Show]\". */\n appHidden: string\n appShow: string\n /** The app's menu and what is in it. */\n appMenu: string\n appReload: string\n appOpenPanel: string\n /** Under an inline app taller than the chat shows inline (`appHeightCap`): it scrolls inside. */\n appTaller: string\n appHide: string\n /** The note at the bottom of the menu. */\n appServedBy: (server: string, uri: string) => string\n /** The line left in the transcript while the app is in the panel, and its button. */\n appInPanel: string\n appBringBack: string\n appClosePanel: string\n /** The panel's footer. */\n appPanelNote: (server: string) => string\n /** The accessible name of the app's frame. */\n appFrameName: (server: string) => string\n /** Under the frame: the tools the app called, and the ones that were refused. */\n appRan: (names: string) => string\n appRefused: string\n /** A tool call the app asks for (`<ToolApprovalPrompt>`): the lead and the note. */\n approvalLeadApp: (server: string) => string\n approvalFromApp: (server: string, readOnly: boolean) => string\n /** A link the app asks to open (`<AppRequestPrompt>`). */\n appLinkLead: (server: string) => string\n appLinkNote: string\n appLinkOpen: string\n appCancel: string\n /** A message the app asks to put in the chat. */\n appMessageLead: (server: string) => string\n appMessageNote: string\n appMessageAccept: string\n appMessageDiscard: string\n /** The app shown full screen (`<McpAppFrame allowFullscreen>`): the badge, the way back. */\n appFullscreenBadge: string\n appFullscreenExit: string\n /** The note under an inline app taller than the chat: show it full screen (when it may be). */\n appFullscreenEnter: string\n /** The key that exits too, shown on the button. */\n appFullscreenKey: string\n /** A file the app asks to save (`<AppRequestPrompt>`). */\n appDownloadLead: (server: string) => string\n /** Name · type · size. */\n appDownloadType: (mimeType: string | undefined) => string\n appDownloadSize: (bytes: number) => string\n /** Where the bytes came from: the request itself, or read from the app's server. */\n appDownloadSource: (source: 'embedded' | 'link', server: string) => string\n appDownloadNote: string\n appDownloadSave: string\n /** The app asks the agent's model for an answer (`sampling/createMessage`). */\n appSamplingLead: (server: string) => string\n appSamplingSystem: string\n appSamplingRole: (role: 'user' | 'assistant') => string\n appSamplingImages: (count: number) => string\n appSamplingTokens: (tokens: number, asked: number) => string\n appSamplingNote: string\n appSamplingAllow: string\n appSamplingAlways: string\n appSamplingDeny: string\n /**\n * An MCP server's skill about to enter the model's context (`<ToolApprovalPrompt>`, a request\n * with `approval.skill`): the lead, its size and files, how it was found, the body preview.\n */\n skillConsentLead: (server: string, skill: string) => string\n /** The size of its SKILL.md, and how many more files it bundles. */\n skillConsentSize: (bytes: number, files: number) => string\n /** It was named by its address (`skills/get`), not in the server's list. */\n skillConsentByUri: string\n /** It sits inside another skill of the same server. */\n skillConsentNested: (enclosing: string) => string\n /**\n * A generated skill (`skill.dynamic`): the server publishes no checksums - the person approves\n * the copy the agent just read, and only that copy is used.\n */\n skillConsentDynamic: string\n /** (with `skillConsentDynamic`) The server cannot list the skill's files: SKILL.md alone. */\n skillConsentNoFileListing: string\n /** The summary of the collapsible preview of its instructions. */\n skillConsentPreview: string\n /** Under the preview: its other files, and how many more there are than are shown. */\n skillConsentFiles: (paths: string, more: number) => string\n /** What a yes means: `'once-per-skill'` - this text for the session; `'ask'` - this task. */\n skillConsentNote: (server: string, consent: 'ask' | 'once-per-skill') => string\n skillConsentAllow: string\n skillConsentAlways: string\n skillConsentDeny: string\n /** The reason a \"Deny\" gives the agent. */\n skillConsentDeclined: string\n}\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`\n\n/** \"12,345 characters\" (grouped: a long paste's length is read at a glance). */\nconst characters = (n: number) =>\n `${n.toLocaleString('en-US')} ${n === 1 ? 'character' : 'characters'}`\n\nconst kb = (n: number): string =>\n n < 1024\n ? `${n} B`\n : n < 1024 * 1024\n ? `${(n / 1024).toFixed(1)} KB`\n : `${(n / 1024 / 1024).toFixed(1)} MB`\n\nexport const defaultLabels: AgentLabels = {\n emptyState: 'Ask the agent to do something.',\n status: {\n idle: 'Idle',\n initializing: 'Loading model…',\n ready: 'Ready',\n running: 'Working…',\n error: 'Failed to start',\n },\n history: 'Chats',\n newChat: 'New chat',\n files: 'Files',\n totalUsage: 'Tokens this conversation used, by kind',\n showHistory: 'Show chats',\n showFiles: 'Show files',\n close: 'Close',\n\n steps: (n) => plural(n, 'step', 'steps'),\n toolCalls: (n) => plural(n, 'tool call', 'tool calls'),\n subagents: (n) => plural(n, 'subagent', 'subagents'),\n skillsUsed: (names) => `skills: ${names}`,\n learnedNow: (names) => `learned: ${names}`,\n fetches: (n) => plural(n, 'web request', 'web requests'),\n fetchRefused: (reason) => `refused: ${reason}`,\n answerThoughts: 'Thinking about the answer',\n answerStopped: 'Stopped.',\n stepThoughts: 'Thoughts',\n usageTitle: 'Tokens this answer spent, by kind',\n attachments: 'Attachments',\n planned: 'Plan',\n replanned: (mode, reason) => `Replanned (${mode}): ${reason}`,\n\n notebookTitle: 'Notebook',\n notebookEmpty: 'The agent has not written any lessons down yet.',\n notebookForget: 'Forget',\n notebookRevision: (n) => `revision ${n}`,\n notebookFrom: 'from',\n\n memorySaved: 'Remembered',\n memoryUpdated: 'Memory updated',\n memoryForgotten: 'Forgotten',\n memoryUndo: 'Undo',\n memoryUndone: 'Undone',\n\n placeholder: 'Ask the agent to do something… ( / for commands, Ctrl+V to paste an image )',\n listening: 'Listening…',\n message: 'Message',\n dropHint: 'Drop files or images to attach them',\n attach: 'Attach files',\n attachTitle: 'Attach files or images (or paste with Ctrl+V, or drop them here)',\n commands: 'Commands',\n commandsTitle: 'Commands and skills ( / )',\n send: 'Send',\n stop: 'Stop',\n dismiss: 'Dismiss',\n remove: (name) => `Remove ${name}`,\n dictate: 'Dictate (speech to text)',\n dictateTitle: 'Dictate — speech to text in the browser',\n stopDictation: 'Stop dictation',\n micListening: 'Listening — tap to finish',\n microphone: 'Microphone',\n transcribing: 'Transcribing…',\n micDenied:\n \"The microphone is blocked for this site. Allow it in the browser's site settings (the icon beside the address), then try again.\",\n micMissing: 'No microphone was found on this device.',\n micBusy: 'The microphone is in use by another app.',\n micUnsupported: 'This browser cannot record audio on this page.',\n dictationFailed: 'Dictation did not work.',\n recordVoiceMessage: 'Record a voice message',\n voiceMessage: 'Voice message',\n audioDuration: (clock) => clock,\n recording: (elapsed) => `Recording ${elapsed}`,\n recordingDone: 'Attach the recording',\n recordingCancel: 'Discard the recording',\n recordingLimit: 'The recording reached its longest and was stopped; it is attached.',\n model: 'Model',\n thinking: 'Thinking',\n toolConsent: 'Tool consent',\n modes: {\n autopilot: {\n label: 'Auto',\n hint: 'Never ask: every tool runs - the assistant’s and an app’s. Per-tool rules still apply',\n },\n 'ask-writes': {\n label: 'Ask',\n hint: 'Run read-only tools freely; ask before anything that may change state',\n },\n 'ask-all': { label: 'Ask all', hint: 'Ask before every tool call' },\n 'read-only': {\n label: 'Read-only',\n hint: 'Only read-only tools; refuse changes without asking',\n },\n },\n timerRunning: 'This run so far',\n timerLast: 'The last run took',\n agents: (n) => plural(n, 'agent', 'agents'),\n agentsTitle: 'Subagents running in this run',\n notices: defaultNoticeTexts,\n attachmentsOnly: '(attachments)',\n seeAttachments: 'See the attachments.',\n tooLarge: (name, mb) => `${name} is larger than ${mb} MB.`,\n tooManyPixels: (name, megapixels) =>\n `${name} has more than ${megapixels} megapixels — too large a picture to attach.`,\n binaryText: (name) => `${name} looks binary — it can't be attached as text.`,\n downscaledFrom: (size) => `downscaled from ${size}`,\n convertedFrom: (name) => `converted from ${name}`,\n tooManyImages: (names, max) => `${names}: not added — at most ${max} pictures go in one message.`,\n messageTooLarge: (names, mb) => `${names}: not added — the message would be over ${mb} MB.`,\n pastedText: (chars) => `Pasted text · ${characters(chars)}`,\n dictatedText: (chars) => `Dictated text · ${characters(chars)}`,\n inputCount: (count, max) => `${count.toLocaleString('en-US')} / ${max.toLocaleString('en-US')}`,\n inputLimit: (max) => `The message holds up to ${max.toLocaleString('en-US')} characters`,\n inputLimitReached: (max) =>\n `The message is full: ${max.toLocaleString('en-US')} characters. A longer paste is attached as a file.`,\n inputLimitFull: (max) => `The message is full: ${max.toLocaleString('en-US')} characters.`,\n pastedAsFile: (chars) => `Pasted text attached as a file: ${characters(chars)}`,\n dictatedAsFile: (chars) => `Dictated text attached as a file: ${characters(chars)}`,\n longTextRefused: (max) =>\n `The text is longer than a message holds (${max.toLocaleString('en-US')} characters) — it was not inserted.`,\n attachmentSaveFailed: (names) =>\n `${names}: could not be saved in the files, so the message was not sent. Free some space or remove it, then send again.`,\n commandGroups: { commands: 'Commands', consent: 'Consent', skills: 'Skills' },\n commandDescriptions: {\n compact: 'Summarise the conversation to free context',\n new: 'Start a new conversation',\n stop: 'Stop the current run',\n autopilot: 'Run every tool without asking',\n ask: 'Ask before tools that may change state',\n askAll: 'Ask before every tool call',\n readOnly: 'Only read; refuse changes',\n think: (levels) => `Set thinking: ${levels}`,\n },\n thinkingLevels: {\n off: 'Default',\n none: 'No thinking',\n low: 'Low',\n medium: 'Medium',\n high: 'High',\n },\n\n filesEmpty: 'No files yet. Attachments and files the agent writes appear here.',\n upload: 'Upload',\n download: 'Download',\n delete: 'Delete',\n preview: 'Preview',\n bytes: kb,\n\n historyEmpty: 'No saved chats yet.',\n deleteChat: 'Delete chat',\n messagesCount: (n) => plural(n, 'message', 'messages'),\n\n approvalLead: 'The agent wants to run',\n approve: 'Allow once',\n alwaysAllow: 'Always allow',\n deny: 'Deny',\n declinedReason: 'the user declined',\n readOnlyTool: 'read-only',\n consentWaiting: 'waiting for your consent',\n consentAllowed: 'allowed',\n consentDenied: (reason) => `denied${reason ? ` — ${reason}` : ''}`,\n\n placeholderBusy: 'Tell the agent something while it works…',\n steer: 'Send to the agent',\n noAttachmentsWhileBusy:\n 'Files can’t be added while the agent is working — send them with your next message.',\n sendWhenReady: 'Sends when the agent is ready',\n sendWhenReadyButton: 'Send when the agent is ready',\n cancelSendWhenReady: 'Don’t send',\n notSentFailed: 'Not sent: the agent could not start. Your message is still here.',\n notSentUnavailable: 'Not sent: the agent isn’t ready. Your message is still here.',\n notSentDisabled: 'Not sent: sending is turned off. Your message is still here.',\n queuedWaiting: 'waiting for the agent’s next step',\n queuedForSession: (heldBy) =>\n heldBy === 'this-tab'\n ? 'waiting for the other run to finish'\n : 'waiting for the other tab to finish',\n queuedForOtherTab: 'waiting for the other tab to pick it up',\n noteAt: {\n round: 'you said, between tool calls',\n step: 'you said, after this step',\n final: 'you said, before the answer',\n },\n undelivered: (n) => `Not delivered (${plural(n, 'message', 'messages')})`,\n sendUndelivered: 'Send now',\n discardUndelivered: 'Discard',\n stopSubagent: 'Stop this subagent',\n subagentStopped: 'stopped',\n\n remoteRunning: 'Running in another tab: follow it here, write to it or stop it.',\n remoteWaitingConsent: 'It waits for an answer in the other tab.',\n remoteGone: 'The tab running this conversation closed before it finished.',\n sessionBusy: (heldBy) =>\n heldBy === 'this-tab'\n ? 'Waiting for the other run of this conversation to finish…'\n : 'Waiting for the other tab to finish this conversation…',\n fromAnotherTab: 'from another tab',\n\n failed: 'failed',\n toolCostTitle:\n \"Estimated tokens of the arguments and of the result fed back to the model (chars / 4), and the call's duration\",\n\n tierNames: { light: 'light', standard: 'standard', strong: 'strong' },\n tierReasons: {\n planned: 'The planner rated this step for this model tier',\n default: 'The planner did not rate this step: it runs on the standard model',\n fallback: 'The tier the planner asked for is not configured: the nearest one runs the step',\n },\n escalationReasons: {\n blocked: 'reported a blocker',\n 'empty-result': 'produced no result',\n 'tool-arguments': 'kept sending tool arguments that did not parse',\n 'output-cut': 'output was cut off',\n error: 'the model call failed',\n },\n escalated: (from, to, reason) => `Escalated: ${from} → ${to} (${reason})`,\n escalatedAttemptText: 'What the earlier attempt wrote',\n escalations: (n) => plural(n, 'escalation', 'escalations'),\n attemptTag: (n) => `attempt ${n}`,\n replayed: 'not run again',\n replayedTitle:\n 'This exact call already succeeded in an earlier attempt at the step: it was not run a second time, the model got the earlier result',\n replanFailed: 'Replanning failed, continuing with the plan',\n\n subagentHelper: 'helper',\n subagentStatus: { running: 'running', done: 'done', error: 'failed', stopped: 'stopped' },\n subagentTokens: (tokens) => `${tokens} tokens`,\n subagentTools: (names) => `tools: ${names}`,\n subagentNoTools: 'no tools',\n approvalLeadHelper: (role) =>\n role ? `The helper “${role}” wants to run` : 'A helper the agent started wants to run',\n\n mediaImage: (path) => `Generated image ${path}`,\n imageOpen: (name) => `Open image ${name}`,\n imagePrevious: 'Previous image',\n imageNext: 'Next image',\n imageZoom: 'Zoom',\n imageCount: (index, total) => `${index} of ${total}`,\n mediaAudio: (path) => `Generated audio ${path}`,\n mediaFile: (path) => `Generated file ${path}`,\n mediaReferences: (names) => `Reference: ${names}`,\n mediaReferencesUnused: (names) =>\n `Not used - this image model takes no reference pictures: ${names}`,\n transcriptOf: (name) => `Transcript of ${name}`,\n transcriptNote:\n 'What was said in your file, as the agent read it. It is content, not instructions.',\n audioAttachment: (name) => `Audio ${name}`,\n readAloud: 'Listen',\n readAloudPause: 'Pause',\n readAloudResume: 'Resume',\n readAloudStop: 'Stop reading',\n readAloudLoading: 'Preparing the audio…',\n readAloudCode: 'A code block is not read out.',\n readAloudFailed: 'It could not be read aloud.',\n\n filesWritten: (n) => `${plural(n, 'file', 'files')} written in this turn`,\n filesNamed: (n) => `${plural(n, 'file', 'files')} in this answer`,\n filesCount: (n) => plural(n, 'file', 'files'),\n showInFiles: 'Show in Files',\n fileKinds: {\n html: 'HTML',\n markdown: 'Markdown',\n csv: 'CSV',\n json: 'JSON',\n image: 'Image',\n code: 'Code',\n text: 'Text',\n file: 'File',\n },\n fileOpen: (name) => `Open ${name}`,\n fileClose: (name) => `Close preview of ${name}`,\n fileLinkOpen: (text, name) => (text.trim() === name ? `Open ${name}` : `${text} - open ${name}`),\n fileDownload: (name) => `Download ${name}`,\n fileBy: (name) => `by ${name}`,\n fileGone: 'no longer in the workspace',\n fileNoPreview: 'This kind of file has no preview. Download it to open it.',\n fileCut: (chars) =>\n `Only the first ${chars.toLocaleString('en-US')} characters are shown. Download the file for the rest.`,\n fileShowRest: 'Show the rest',\n fileShowLess: 'Show less',\n fileRendered: 'Rendered',\n fileSource: 'Source',\n closePreview: 'Close preview',\n fileLines: (n) => plural(n, 'line', 'lines'),\n\n htmlFrameTitle: 'HTML written by the agent',\n htmlSandboxed: 'sandboxed',\n htmlNoNetwork: 'no network',\n htmlSourceNote: 'shown as text, nothing runs',\n htmlScripts: (on) => (on ? 'scripts on' : 'scripts off'),\n htmlLinkedFiles: (names) => `linked files are not loaded: ${names}`,\n htmlTooLarge: 'This page is too large to preview. It is shown as source.',\n htmlTaller: 'Make the preview taller',\n htmlShorter: 'Make the preview shorter',\n htmlFrameName: (path) => `Preview of ${path}`,\n\n usageMedia: (n) => plural(n, 'media call', 'media calls'),\n usageDecisions: (n) => plural(n, 'decision call', 'decision calls'),\n\n decisionAccepted: (choice, confidence) => `decision model: ${choice} (${confidence})`,\n decisionFellBack: (reason, detail) =>\n `decision model fell back: ${reason}${detail ? ` (${detail})` : ''}`,\n decisionReasons: {\n 'low-confidence': 'low confidence',\n 'invalid-choice': 'an answer that is not an option',\n 'invalid-confidence': 'a confidence that is not a probability',\n error: 'the call failed',\n timeout: 'timed out',\n 'needs-model': 'the choice needs the model',\n },\n\n searchQuery: 'Searched the web for',\n searchNoResults: 'no results',\n searchFiltered: (n) => `${n} left out by the web access policy`,\n searchTruncated: 'list cut short',\n\n elicitationTitle: 'A question from an MCP server',\n elicitationLead: (server) => `The MCP server “${server}” asks for your input`,\n elicitationLeadHelper: (server, role) =>\n role\n ? `The MCP server “${server}” asks for your input (a call by the helper “${role}”)`\n : `The MCP server “${server}” asks for your input (a call by a helper)`,\n elicitationDuring: 'during',\n elicitationCount: (index, total) => `${index} of ${total}`,\n elicitationFrom: (server) => `From the server “${server}”`,\n elicitationRequired: 'required',\n elicitationChoose: 'Choose…',\n elicitationSubmit: 'Submit',\n elicitationDecline: 'Decline',\n elicitationCancel: 'Cancel',\n elicitationErrors: {\n required: (field) => `${field} is required.`,\n tooShort: (field, limit) => `${field} must be at least ${limit} characters.`,\n tooLong: (field, limit) => `${field} must be at most ${limit} characters.`,\n email: (field) => `${field} must be an email address.`,\n uri: (field) => `${field} must be a full address, such as https://example.com.`,\n date: (field) => `${field} must be a date.`,\n dateTime: (field) => `${field} must be a date and a time.`,\n notNumber: (field) => `${field} must be a number.`,\n notInteger: (field) => `${field} must be a whole number.`,\n belowMinimum: (field, limit) => `${field} must be ${limit} or more.`,\n aboveMaximum: (field, limit) => `${field} must be ${limit} or less.`,\n notAnOption: (field) => `${field} must be one of the options.`,\n tooFew: (field, limit) => `${field}: choose at least ${limit}.`,\n tooMany: (field, limit) => `${field}: choose at most ${limit}.`,\n },\n elicitationFix: (n) => `${plural(n, 'field needs', 'fields need')} a correction.`,\n elicitationUrlLead: (server) => `The MCP server “${server}” asks you to open a page on`,\n elicitationUrlFull: 'Full address',\n elicitationOpen: 'Open in a new tab',\n elicitationOpened: 'Opened in a new tab. Finish there, then confirm here.',\n elicitationUrlDone: 'I have finished there',\n elicitationUrlRefused:\n 'This link is not a secure (https) address, so it is not opened from here.',\n elicitationExpiresIn: (time) => `Cancelled automatically in ${time}`,\n elicitationExpires: 'Cancelled automatically if it is left unanswered',\n elicitationAutomatic: (server, reason) =>\n `A question from the MCP server “${server}” was answered automatically, and its tool call did not finish: ${reason}.`,\n elicitationReasons: {\n timeout: 'nobody answered in time',\n 'step-timeout': 'the step ran out of time while the question was waiting',\n aborted: 'the run was stopped',\n stopped: 'the run was stopped',\n 'cap-per-call': 'the tool call had already asked too many questions',\n 'cap-per-run': 'too many questions had already been asked in this run',\n 'unsupported-schema': 'the form it sent cannot be shown',\n 'unsupported-mode': 'it asked in a way this app does not offer',\n 'insecure-url': 'the link it sent was refused',\n 'invalid-request': 'its request was malformed',\n subagent: 'a helper is not allowed to ask you',\n 'handler-error': 'the question could not be shown',\n 'invalid-answer': 'the answer did not fit the form and was not sent',\n 'after-failure': 'an earlier question of the same call had already failed',\n 'no-tool-call': 'no tool call was in progress',\n },\n elicitationDismiss: 'Dismiss',\n\n questionLead: 'The agent asks you',\n questionLeadHelper: (role) =>\n role ? `The helper “${role}” asks you` : 'A helper the agent started asks you',\n questionCount: (index, total) => `${index} of ${total}`,\n questionSeveral: 'Pick one or more, then Send.',\n questionSend: 'Send',\n questionOther: 'Other…',\n questionOtherLabel: 'Your answer',\n questionSkip: 'Skip',\n questionExpiresIn: (time) => `If you do not answer, the agent decides by itself in ${time}`,\n questionRemote: 'Answered in the other tab, where the agent is running.',\n questionAutomatic: (reason) => `The agent went on without your answer: ${reason}.`,\n questionReasons: {\n timeout: 'nobody answered in time',\n stopped: 'the run was stopped',\n 'handler-error': 'the question could not be shown',\n 'invalid-answer': 'the answer did not fit the question',\n 'cannot-park': 'the question could not wait here',\n },\n questionDismiss: 'Dismiss',\n\n appFrom: (server) => `App from server “${server}”`,\n appSandboxed: 'sandboxed',\n appSandboxedOrigin: 'sandboxed on its own origin',\n appSandboxOrigin: (origin) =>\n `Runs on its own origin, ${origin}: its storage is its own, never this page's.`,\n appSandboxFallback: (reason) =>\n `Not on an origin of its own (${reason}): it runs in an opaque sandbox, with no storage of its own.`,\n appSandboxReasons: {\n invalid: 'the sandbox URL is not valid',\n insecure: 'the sandbox URL is not https',\n 'same-origin': \"the sandbox URL is on this page's origin\",\n 'no-page-origin': 'this page has no origin of its own',\n 'server-name': \"the server's name is not a DNS label\",\n 'too-many-origins': 'it declares too many origins',\n 'no-answer': 'the sandbox page did not answer',\n },\n appSandboxBroken: 'The app reloaded its frame, so it was stopped. Reload it to start again.',\n appWaiting: 'waiting for you',\n appWaitingFocus: 'Go to what the app is waiting for',\n appPromptsLabel: (server) => `What the app from “${server}” is waiting for`,\n appTag: 'app',\n appsCount: (n) => plural(n, 'app', 'apps'),\n appLoading: 'Loading the app…',\n appFailed: (reason) => `The app could not be shown: ${reason}`,\n appUnavailable: (server) =>\n `The server “${server}” is not connected, so its app cannot be shown.`,\n appHidden: 'hidden',\n appShow: 'Show',\n appMenu: 'App menu',\n appReload: 'Reload app',\n appOpenPanel: 'Open in panel',\n appTaller: 'Taller than the chat - this app scrolls inside its frame.',\n appHide: 'Hide app',\n appServedBy: (server, uri) =>\n `Served by ${server} as ${uri}. It cannot read this chat, your keys or your files.`,\n appInPanel: 'open in the panel',\n appBringBack: 'Bring back',\n appClosePanel: 'Close the panel',\n appPanelNote: (server) =>\n `Content from the server “${server}”. It cannot read this chat, your keys or your files.`,\n appFrameName: (server) => `App from server ${server}`,\n appRan: (names) => `The app ran ${names}`,\n appRefused: 'refused',\n approvalLeadApp: (server) => `The app “${server}” wants to run`,\n approvalFromApp: (server, readOnly) =>\n `Asked by the app, not by the agent. This tool ${readOnly ? 'only reads' : 'changes'} data on the server “${server}”.`,\n appLinkLead: (server) => `The app “${server}” wants to open a link. Open it?`,\n appLinkNote: 'Opens in a new tab, outside this chat. Check the site name before you continue.',\n appLinkOpen: 'Open',\n appCancel: 'Cancel',\n appMessageLead: (server) => `The app “${server}” wants to put a message in your message box`,\n appMessageNote:\n 'Nothing is sent until you send it yourself, and you can change it first. It is the app’s text, not yours.',\n appMessageAccept: 'Put in the message box',\n appMessageDiscard: 'Discard',\n appFullscreenBadge: 'full screen',\n appFullscreenExit: 'Exit full screen',\n appFullscreenEnter: 'Full screen',\n appFullscreenKey: 'Esc',\n appDownloadLead: (server) => `The app “${server}” wants to save a file to your device`,\n appDownloadType: (mimeType) => mimeType ?? 'type not given',\n appDownloadSize: kb,\n appDownloadSource: (source, server) =>\n source === 'link'\n ? `Read from the server “${server}” for the app.`\n : 'Made by the app inside its frame.',\n appDownloadNote:\n 'This page saves it, not the app. Programs, scripts and web pages are never saved; check the name before you save.',\n appDownloadSave: 'Save file',\n appSamplingLead: (server) => `The app “${server}” asks the agent’s model for an answer`,\n appSamplingSystem: 'Its instructions',\n appSamplingRole: (role) => (role === 'user' ? 'Asks' : 'Earlier answer'),\n appSamplingImages: (count) => plural(count, 'image', 'images'),\n appSamplingTokens: (tokens, asked) =>\n tokens < asked\n ? `Up to ${tokens} tokens (the app asked for ${asked}).`\n : `Up to ${tokens} tokens.`,\n appSamplingNote:\n 'Only this text is sent - not your chat. The answer goes to the app only, and its tokens count in your total.',\n appSamplingAllow: 'Allow once',\n appSamplingAlways: 'Always for this app',\n appSamplingDeny: 'Deny',\n skillConsentLead: (server, skill) => `The server “${server}” offers the skill “${skill}”`,\n skillConsentSize: (bytes, files) =>\n `SKILL.md ${kb(bytes)}${files ? ` · ${plural(files, 'more file', 'more files')}` : ''}`,\n skillConsentByUri: 'Not in the server’s list: the agent asked for it by its address.',\n skillConsentNested: (enclosing) =>\n `It sits inside the skill “${enclosing}”: allowing that one did not allow this one.`,\n skillConsentDynamic:\n 'This server publishes no checksums for this skill: you approve the copy the agent just read, and only that copy is used.',\n skillConsentNoFileListing:\n 'The server cannot list this skill’s files: that copy is its SKILL.md alone.',\n skillConsentPreview: 'Show what the agent would read',\n skillConsentFiles: (paths, more) =>\n `Its files, read as text and never run: ${paths}${more ? ` and ${more} more` : ''}`,\n skillConsentNote: (server, consent) =>\n `Instructions written by the server “${server}”, not by you. They reach the agent only if you allow it${\n consent === 'ask'\n ? ', and you are asked again in every task that loads them.'\n : ' - you are asked again if the server changes them.'\n } They cannot change the agent’s rules or approvals.`,\n skillConsentAllow: 'Allow once',\n skillConsentAlways: 'Always for this server',\n skillConsentDeny: 'Deny',\n skillConsentDeclined: 'the user declined the skill',\n}\n\n/** Overrides: any label, with the nested groups merged key by key. */\nexport type AgentLabelsOverride = Partial<\n Omit<\n AgentLabels,\n | 'status'\n | 'modes'\n | 'commandGroups'\n | 'commandDescriptions'\n | 'thinkingLevels'\n | 'notices'\n | 'tierNames'\n | 'tierReasons'\n | 'escalationReasons'\n | 'subagentStatus'\n | 'decisionReasons'\n | 'elicitationErrors'\n | 'elicitationReasons'\n | 'questionReasons'\n | 'fileKinds'\n | 'appSandboxReasons'\n >\n> & {\n status?: Partial<AgentLabels['status']>\n modes?: Partial<AgentLabels['modes']>\n commandGroups?: Partial<AgentLabels['commandGroups']>\n commandDescriptions?: Partial<AgentLabels['commandDescriptions']>\n thinkingLevels?: Partial<AgentLabels['thinkingLevels']>\n notices?: Partial<AgentLabels['notices']>\n tierNames?: Partial<AgentLabels['tierNames']>\n tierReasons?: Partial<AgentLabels['tierReasons']>\n escalationReasons?: Partial<AgentLabels['escalationReasons']>\n subagentStatus?: Partial<AgentLabels['subagentStatus']>\n decisionReasons?: Partial<AgentLabels['decisionReasons']>\n elicitationErrors?: Partial<AgentLabels['elicitationErrors']>\n elicitationReasons?: Partial<AgentLabels['elicitationReasons']>\n questionReasons?: Partial<AgentLabels['questionReasons']>\n fileKinds?: Partial<AgentLabels['fileKinds']>\n appSandboxReasons?: Partial<AgentLabels['appSandboxReasons']>\n}\n\nconst NESTED = [\n 'status',\n 'modes',\n 'commandGroups',\n 'commandDescriptions',\n 'thinkingLevels',\n 'noteAt',\n 'tierNames',\n 'tierReasons',\n 'escalationReasons',\n 'subagentStatus',\n 'decisionReasons',\n 'elicitationErrors',\n 'elicitationReasons',\n 'questionReasons',\n 'fileKinds',\n 'appSandboxReasons',\n] as const\n\n/** `base` with `over` applied (nested groups merged, not replaced). */\nexport const mergeLabels = (base: AgentLabels, over?: AgentLabelsOverride): AgentLabels => {\n if (!over) return base\n const out = { ...base, ...over } as AgentLabels\n for (const key of NESTED) {\n if (over[key]) (out as unknown as Record<string, unknown>)[key] = { ...base[key], ...over[key] }\n }\n return out\n}\n","/**\n * The transcript's scroll position while content arrives - the rule, as a pure function (no DOM),\n * and the numbers it stands on. `useFollowScroll` (hooks/use-follow-scroll.ts) applies it.\n *\n * Two states. FOLLOWING: the view is at the end and stays there, whatever grows or shrinks.\n * READING: the person moved up, and the view is theirs - nothing that arrives moves what they\n * read; going back down to the end follows again.\n */\n\n/** A scroller's measures (CSS pixels). */\nexport interface ScrollMeasure {\n scrollTop: number\n scrollHeight: number\n clientHeight: number\n}\n\n/** How far from the end still counts as \"back at the end\" when moving down. */\nexport const FOLLOW_REJOIN_PX = 80\n/**\n * How far above the end a move up must leave the view to count as the person's. Under it, a\n * move up is the browser's own: the bounce at the end of a touch scroll (the position comes\n * back from beyond the end), or a sub-pixel rounding. Small on purpose: a slow drag moves a\n * few pixels between two pieces of an answer, and must not be pulled back.\n */\nexport const FOLLOW_LEAVE_PX = 2\n\nexport const endGap = (m: ScrollMeasure): number => m.scrollHeight - m.scrollTop - m.clientHeight\n\n/** The furthest position the view had a reason to be at: its own, or the end (a bounce is beyond it). */\nconst reach = (m: ScrollMeasure): number =>\n Math.min(m.scrollTop, Math.max(0, m.scrollHeight - m.clientHeight))\n\n/**\n * Whether the view follows after a scroll event: `before` is what the scroller measured when it\n * was last looked at, `now` what it measures in the event.\n *\n * - The content or the box changed size since: the move is the layout's (the browser keeps the\n * position inside a shorter transcript, a keyboard opens), not the person's - nothing changes.\n * - A move up that leaves the end: the person reads - stop following.\n * - A move down that ends near the end: follow again.\n */\nexport const followsAfterScroll = (\n following: boolean,\n before: ScrollMeasure,\n now: ScrollMeasure,\n): boolean => {\n if (before.scrollHeight !== now.scrollHeight || before.clientHeight !== now.clientHeight)\n return following\n if (now.scrollTop < reach(before) - FOLLOW_LEAVE_PX) return false\n if (now.scrollTop > before.scrollTop) return endGap(now) < FOLLOW_REJOIN_PX ? true : following\n return following\n}\n\n/**\n * Whether the view still follows when the transcript changed size: a piece of the answer often\n * lands between a move of the person's and its scroll event, and must not undo the move. With\n * the box as it was and the transcript no shorter, nothing but the person moves the view up\n * (the hook turns the browser's own scroll anchoring off: `useFollowScroll`).\n */\nexport const followsAfterResize = (\n following: boolean,\n before: ScrollMeasure,\n now: ScrollMeasure,\n): boolean =>\n following &&\n !(\n now.clientHeight === before.clientHeight &&\n now.scrollHeight >= before.scrollHeight &&\n now.scrollTop < reach(before) - FOLLOW_LEAVE_PX\n )\n","/**\n * Where a component lives: in the document, or in a shadow root (a web component's). The chat\n * reads the focus, the element under a point and the target of an event; seen from the DOCUMENT,\n * everything inside a shadow root is its HOST - `document.activeElement` is the host, a click\n * inside comes from the host, `document.elementFromPoint` over a button finds the host. These\n * helpers ask the component's own root instead, and look through open shadow roots where the\n * question is about the whole page (what is on top at a point).\n *\n * In the light DOM every helper answers exactly what the `document` call it replaces did: the\n * root is the document, nothing is retargeted, no shadow root is crossed.\n *\n * No framework, no DOM UI: they read the DOM and make nothing. Structural types (`nodeType`,\n * `host`), so they run - and are tested - without a DOM.\n */\n\nconst DOCUMENT_NODE = 9\nconst DOCUMENT_FRAGMENT_NODE = 11\n/** Nested shadow roots followed at most this deep (a cycle is impossible; a bound is cheap). */\nconst MAX_DEPTH = 64\n\n/** A shadow root: a document fragment with a host. */\nexport const isShadowRoot = (node: unknown): node is ShadowRoot =>\n typeof node === 'object' &&\n node !== null &&\n (node as Node).nodeType === DOCUMENT_FRAGMENT_NODE &&\n 'host' in node &&\n Boolean((node as ShadowRoot).host)\n\nconst isDocument = (node: unknown): node is Document =>\n typeof node === 'object' && node !== null && (node as Node).nodeType === DOCUMENT_NODE\n\n/**\n * The root `node` lives in: its shadow root, else its document. A node that is not in a document\n * yet (or any more) answers its owner document - never the detached subtree it hangs in.\n */\nexport const rootOf = (node: Node): Document | ShadowRoot => {\n if (isDocument(node)) return node\n const root = typeof node.getRootNode === 'function' ? node.getRootNode() : undefined\n if (isDocument(root) || isShadowRoot(root)) return root\n return node.ownerDocument as Document\n}\n\n/**\n * What has the focus, as seen from `at`'s root (or from that root itself): in a shadow root the\n * focused element of that tree (a nested component's host when the focus is deeper), `null`\n * when the focus is outside it; in the document, `document.activeElement`.\n */\nexport const activeElementOf = (at: Node | Document | ShadowRoot): Element | null => {\n const root = isDocument(at) || isShadowRoot(at) ? at : rootOf(at)\n return root.activeElement ?? null\n}\n\n/**\n * The element that really has the focus: from `root`'s active element down through every open\n * shadow root it is the host of. In the light DOM, `document.activeElement`.\n */\nexport const deepActiveElement = (root: Document | ShadowRoot): Element | null => {\n let active = root.activeElement ?? null\n for (let i = 0; active && i < MAX_DEPTH; i++) {\n const inner = active.shadowRoot?.activeElement\n if (!inner || inner === active) break\n active = inner\n }\n return active\n}\n\n/** Nothing on the page has the focus: the document's active element is none or its body. */\nexport const nothingFocused = (doc: Document): boolean => {\n const active = doc.activeElement\n return !active || active === doc.body\n}\n\n/**\n * `ancestor` contains `node` across shadow boundaries: up from `node` through its parents and,\n * at a shadow root, on to its host. In one tree, `ancestor.contains(node)`.\n */\nexport const composedContains = (ancestor: Node, node: Node | null | undefined): boolean => {\n let at: Node | null | undefined = node\n for (let i = 0; at && i < 100_000; i++) {\n if (at === ancestor) return true\n at = at.parentNode ?? (isShadowRoot(at) ? at.host : null)\n }\n return false\n}\n\n/** An event's path through the page, when the browser gives one (only while it is dispatched). */\nconst pathOf = (event: Event): EventTarget[] =>\n typeof event.composedPath === 'function' ? event.composedPath() : []\n\n/**\n * Where an event really began: the innermost target of its path (inside an open shadow root),\n * else `event.target`. A listener on the document sees the host as the target of an event from\n * inside a shadow root; this is the element itself. Only while the event is dispatched.\n */\nexport const eventTargetOf = (event: Event): EventTarget | null => pathOf(event)[0] ?? event.target\n\n/**\n * The event began inside `node`. In one tree (the target not retargeted), `node.contains(target)`\n * - exactly what a listener on the document asked before. From inside a shadow root (the\n * document sees the host as the target), whether `node` is on the event's composed path.\n * Only while the event is dispatched.\n */\nexport const isEventInside = (event: Event, node: Node | null | undefined): boolean => {\n if (!node) return false\n const target = event.target\n const path = pathOf(event)\n if (path.length > 0 && path[0] !== target) return path.includes(node)\n return typeof (target as Node | null)?.nodeType === 'number' && node.contains(target as Node)\n}\n\n/**\n * The element on top at a point of the viewport, looked for on the whole page: the document's\n * answer, then down through each open shadow root it is the host of. In the light DOM,\n * `document.elementFromPoint(x, y)`. A closed shadow root stays its host.\n */\nexport const deepElementFromPoint = (doc: Document, x: number, y: number): Element | null => {\n if (typeof doc.elementFromPoint !== 'function') return null\n let hit = doc.elementFromPoint(x, y)\n for (let i = 0; hit && i < MAX_DEPTH; i++) {\n const shadow = hit.shadowRoot\n if (!shadow || typeof shadow.elementFromPoint !== 'function') break\n const inner = shadow.elementFromPoint(x, y)\n // Only an element of that tree: what lies over the host from outside is already the answer.\n if (!inner || inner === hit || !composedContains(shadow, inner)) break\n hit = inner\n }\n return hit\n}\n\n/**\n * The shadow roots `node` is inside, innermost first; none in the light DOM. Events that do not\n * leave a shadow tree (`scroll`) are heard on these as well as on the window.\n */\nexport const shadowRootsAround = (node: Node): ShadowRoot[] => {\n const roots: ShadowRoot[] = []\n let root = rootOf(node)\n for (let i = 0; isShadowRoot(root) && i < MAX_DEPTH; i++) {\n roots.push(root)\n root = rootOf(root.host)\n }\n return roots\n}\n\n/**\n * Listens for `scroll` anywhere around `node` (capture: any scroller), on the window and on every\n * shadow root `node` is inside - a scroll inside a shadow tree never reaches the window. In the\n * light DOM, `window.addEventListener('scroll', listener, true)`. Returns the way to stop.\n */\nexport const listenScrollAround = (node: Node, listener: (event: Event) => void): (() => void) => {\n const view: EventTarget = node.ownerDocument?.defaultView ?? globalThis\n const targets: EventTarget[] = [view, ...shadowRootsAround(node)]\n for (const t of targets) t.addEventListener('scroll', listener, true)\n return () => {\n for (const t of targets) t.removeEventListener('scroll', listener, true)\n }\n}\n\n/**\n * Where a dialog opened from `from` is mounted so that the chat's theme applies: the nearest\n * ancestor matching `selector` (`.awr-chat, .awr-theme`), else the shadow root `from` lives in\n * (styles adopted there apply), else the document's body - what it was before.\n */\nexport const portalHostOf = (from: Element, selector: string): Element | ShadowRoot => {\n const near = from.closest(selector)\n if (near) return near\n const root = rootOf(from)\n return isShadowRoot(root) ? root : (from.ownerDocument as Document).body\n}\n","import { MEDIA_IMAGE_TYPES, isTextMime } from '@dudko.dev/agent-web'\n\n/**\n * What a workspace file is to the UI. `image` is only what the core's media tools accept\n * (PNG / JPEG / GIF / WebP - never SVG, which is shown as its source); `file` is anything that\n * cannot be shown as text: a chip with a download and no preview.\n */\nexport type FileKind = 'html' | 'markdown' | 'csv' | 'json' | 'image' | 'code' | 'text' | 'file'\n\nconst CODE =\n /\\.(?:js|mjs|cjs|jsx|ts|tsx|css|scss|py|rb|go|rs|java|kt|c|h|cpp|cs|php|sh|sql|xml|svg|yaml|yml|toml)$/i\n\nconst mimeOf = (mediaType: string): string => mediaType.toLowerCase().split(';')[0].trim()\n\n/** The kind of a file, by its MIME type first and its extension second. */\nexport const fileKindOf = (path: string, mediaType: string): FileKind => {\n const mime = mimeOf(mediaType)\n if (Object.hasOwn(MEDIA_IMAGE_TYPES, mime)) return 'image'\n if (mime === 'text/html' || mime === 'application/xhtml+xml' || /\\.x?html?$/i.test(path))\n return 'html'\n if (mime === 'text/markdown' || /\\.(?:md|markdown)$/i.test(path)) return 'markdown'\n if (mime === 'text/csv' || /\\.(?:csv|tsv)$/i.test(path)) return 'csv'\n if (mime === 'application/json' || /\\.json$/i.test(path)) return 'json'\n if (CODE.test(path)) return 'code'\n if (mime === 'text/plain' || /\\.(?:txt|log)$/i.test(path) || isTextMime(mime)) return 'text'\n return 'file'\n}\n\n/** The last segment of a path: what a chip is called and what a download is saved as. */\nexport const fileNameOf = (path: string): string => path.split('/').filter(Boolean).pop() || 'file'\n","/**\n * Downscale an image in the browser before it goes to a model. Providers bill\n * images by their pixel size and resize anything over ~1.15 MP / 1568 px on\n * the long edge themselves — sending more only costs upload time and, for\n * some providers, tokens. GIF and SVG are left as they are.\n */\nexport interface DownscaleOptions {\n /** Longest edge in pixels (default 1568). */\n maxDimension?: number\n /** Total pixels (default 1 150 000). */\n maxPixels?: number\n /** JPEG/WebP quality 0..1 (default 0.9). */\n quality?: number\n}\n\ntype AnyCanvas = OffscreenCanvas | HTMLCanvasElement\n\nconst canvasOf = (w: number, h: number): AnyCanvas | undefined => {\n if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(w, h)\n if (typeof document !== 'undefined') {\n const c = document.createElement('canvas')\n c.width = w\n c.height = h\n return c\n }\n return undefined\n}\n\nconst toBlob = (canvas: AnyCanvas, type: string, quality: number): Promise<Blob | null> =>\n 'convertToBlob' in canvas\n ? canvas.convertToBlob({ type, quality })\n : new Promise((resolve) => canvas.toBlob(resolve, type, quality))\n\n/** A picture's size in pixels, as its file declares it. */\nexport interface ImageSize {\n width: number\n height: number\n}\n\nconst WINDOW = 64 * 1024\n// JPEG markers that start a frame and carry its size (SOF0-15 but DHT, JPG and DAC).\nconst SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf])\n\n/**\n * A picture's size in pixels read from its file's header - a few small reads, nothing decoded -\n * for PNG, JPEG and WebP (by their bytes, whatever the file's type says). undefined for any\n * other format, a header that does not add up, or a file that cannot be read: the caller then\n * goes by the bytes alone. Never throws.\n */\nexport const imageSizeOf = async (file: Blob): Promise<ImageSize | undefined> => {\n let at = 0\n let buf = new Uint8Array(0)\n /** `length` bytes from `start` (a 64 KB window is read at a time), or undefined past the end. */\n const read = async (start: number, length: number): Promise<Uint8Array | undefined> => {\n if (start < 0 || start + length > file.size) return undefined\n if (start < at || start + length > at + buf.length) {\n at = start\n buf = new Uint8Array(\n await file\n .slice(start, Math.min(file.size, start + Math.max(WINDOW, length)))\n .arrayBuffer(),\n )\n }\n return buf.subarray(start - at, start - at + length)\n }\n const sized = (width: number, height: number): ImageSize | undefined =>\n width > 0 && height > 0 ? { width, height } : undefined\n try {\n const head = await read(0, 30)\n if (!head) return undefined\n const u16be = (b: Uint8Array, i: number) => (b[i]! << 8) | b[i + 1]!\n const u32be = (b: Uint8Array, i: number) => u16be(b, i) * 0x10000 + u16be(b, i + 2)\n const ascii = (b: Uint8Array, i: number, n: number) =>\n String.fromCharCode(...Array.from(b.subarray(i, i + n)))\n // PNG: the signature, then IHDR - always the first chunk.\n if (ascii(head, 1, 3) === 'PNG' && head[0] === 0x89 && ascii(head, 12, 4) === 'IHDR')\n return sized(u32be(head, 16), u32be(head, 20))\n // WebP: RIFF … WEBP, then its first chunk - lossy (VP8), lossless (VP8L) or extended (VP8X).\n if (ascii(head, 0, 4) === 'RIFF' && ascii(head, 8, 4) === 'WEBP') {\n const chunk = ascii(head, 12, 4)\n const u16le = (i: number) => head[i]! | (head[i + 1]! << 8)\n const u24le = (i: number) => u16le(i) | (head[i + 2]! << 16)\n if (chunk === 'VP8X') return sized(u24le(24) + 1, u24le(27) + 1)\n if (chunk === 'VP8L' && head[20] === 0x2f) {\n const bits = (u16le(21) | (u16le(23) << 16)) >>> 0\n return sized((bits & 0x3fff) + 1, ((bits >>> 14) & 0x3fff) + 1)\n }\n if (chunk === 'VP8 ' && head[23] === 0x9d && head[24] === 0x01 && head[25] === 0x2a)\n return sized(u16le(26) & 0x3fff, u16le(28) & 0x3fff)\n return undefined\n }\n // JPEG: walk the segments (EXIF, XMP, ICC… each up to 64 KB, any number) to the frame header.\n if (head[0] === 0xff && head[1] === 0xd8) {\n let p = 2\n for (let segments = 0; segments < 4096; segments++) {\n const m = await read(p, 4)\n if (!m || m[0] !== 0xff) return undefined\n const marker = m[1]!\n if (marker === 0xff) {\n p += 1 // a fill byte\n continue\n }\n if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {\n p += 2 // a marker without a length\n continue\n }\n if (marker === 0xd9 || marker === 0xda) return undefined // image data before any frame\n const length = u16be(m, 2)\n if (length < 2) return undefined\n if (SOF.has(marker)) {\n const frame = await read(p + 4, 5)\n return frame ? sized(u16be(frame, 3), u16be(frame, 1)) : undefined\n }\n p += 2 + length\n }\n }\n return undefined\n } catch {\n return undefined\n }\n}\n\n/** The image, smaller when it is larger than the limits; the original otherwise. */\nexport const downscaleImage = async (file: Blob, opts: DownscaleOptions = {}): Promise<Blob> => {\n const maxDimension = opts.maxDimension ?? 1568\n const maxPixels = opts.maxPixels ?? 1_150_000\n if (\n typeof createImageBitmap !== 'function' ||\n !file.type.startsWith('image/') ||\n file.type === 'image/gif' ||\n file.type === 'image/svg+xml'\n ) {\n return file\n }\n let bitmap: ImageBitmap\n try {\n bitmap = await createImageBitmap(file)\n } catch {\n return file // a format the browser can't decode: send it as it is\n }\n const { width, height } = bitmap\n const scale = Math.min(\n 1,\n maxDimension / Math.max(width, height),\n Math.sqrt(maxPixels / Math.max(1, width * height)),\n )\n if (scale >= 1) {\n bitmap.close()\n return file\n }\n const w = Math.max(1, Math.round(width * scale))\n const h = Math.max(1, Math.round(height * scale))\n const canvas = canvasOf(w, h)\n const ctx = canvas?.getContext('2d') as\n OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D | null | undefined\n if (!canvas || !ctx) {\n bitmap.close()\n return file\n }\n ctx.drawImage(bitmap, 0, 0, w, h)\n bitmap.close()\n // Screenshots (PNG) stay lossless so text stays readable; photos go to JPEG.\n const type = file.type === 'image/png' || file.type === 'image/webp' ? file.type : 'image/jpeg'\n const out = await toBlob(canvas, type, opts.quality ?? 0.9)\n return out && out.size < file.size ? out : file\n}\n","/** Compact one-line preview of a tool input/output value, truncated. */\nexport const previewValue = (value: unknown, max = 140): string => {\n if (value === undefined) return ''\n let text: string\n if (typeof value === 'string') text = value\n else {\n try {\n text = JSON.stringify(value)\n } catch {\n text = String(value)\n }\n }\n text = text.replace(/\\s+/g, ' ').trim()\n return text.length > max ? `${text.slice(0, max - 1)}…` : text\n}\n\n/** 1234 → \"1.2k\", 12345 → \"12k\". */\nexport const formatTokens = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n)\n\n/** 340 → \"340 ms\", 4200 → \"4.2 s\", 125_000 → \"2m 5s\". */\nexport const formatDuration = (ms: number): string => {\n if (ms < 1000) return `${Math.round(ms)} ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)} s`\n const s = Math.round(ms / 1000)\n return `${Math.floor(s / 60)}m ${s % 60}s`\n}\n\nconst isDataImage = (v: unknown): v is string =>\n typeof v === 'string' && /^data:image\\/[\\w.+-]+;base64,/.test(v)\n\n/**\n * Images inside a tool result, as data URLs: MCP image parts\n * (`{ type: 'image', data, mimeType }`), data-URL strings, and objects that\n * carry one (`{ dataUrl }` / `{ url: 'data:…' }`). Looks two levels deep.\n */\nexport const imagesInOutput = (output: unknown, depth = 0): string[] => {\n if (depth > 2 || output == null) return []\n if (isDataImage(output)) return [output]\n if (Array.isArray(output)) return output.flatMap((v) => imagesInOutput(v, depth + 1))\n if (typeof output === 'object') {\n const o = output as Record<string, unknown>\n if (o.type === 'image' && typeof o.data === 'string') {\n const mime = typeof o.mimeType === 'string' ? o.mimeType : 'image/png'\n return [o.data.startsWith('data:') ? o.data : `data:${mime};base64,${o.data}`]\n }\n for (const key of ['dataUrl', 'url', 'image'])\n if (isDataImage(o[key])) return [o[key] as string]\n if (depth < 2) return Object.values(o).flatMap((v) => imagesInOutput(v, depth + 1))\n }\n return []\n}\n\n/** One result of the core's `web_search` tool, as far as a UI shows it. */\nexport interface WebSearchResultView {\n title: string\n /** An http(s) address - anything else is left out. */\n url: string\n /** The host of `url`, for the line under the title. */\n host: string\n snippet: string\n date?: string\n}\n\nexport interface WebSearchView {\n query: string\n results: WebSearchResultView[]\n /** Results the egress policy left out. */\n filtered: number\n truncated: boolean\n}\n\nconst text = (v: unknown, max: number): string =>\n typeof v === 'string' ? v.replace(/\\s+/g, ' ').trim().slice(0, max) : ''\n\n/**\n * The result of the core's `web_search` tool (`{ query, results: [{ title, url, snippet, date? }],\n * filtered?, truncated?, untrusted: true }`), or undefined when `output` is not one. Titles and\n * snippets are third-party text: they come back as plain strings, to be rendered as text. A\n * result whose `url` is not http(s) is dropped, so a link can never be a `javascript:` one.\n */\nexport const webSearchOf = (output: unknown): WebSearchView | undefined => {\n let value = output\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const o = value as Record<string, unknown>\n if (typeof o.query !== 'string' || !Array.isArray(o.results)) return undefined\n const results: WebSearchResultView[] = []\n for (const r of o.results.slice(0, 10)) {\n if (!r || typeof r !== 'object') continue\n const item = r as Record<string, unknown>\n if (typeof item.url !== 'string') continue\n let url: URL\n try {\n url = new URL(item.url)\n } catch {\n continue\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') continue\n const date = text(item.date, 40)\n results.push({\n title: text(item.title, 200) || url.host,\n url: url.href,\n host: url.host,\n snippet: text(item.snippet, 400),\n ...(date ? { date } : {}),\n })\n }\n return {\n query: text(o.query, 300),\n results,\n filtered: typeof o.filtered === 'number' && o.filtered > 0 ? o.filtered : 0,\n truncated: o.truncated === true,\n }\n}\n\n/** 0.934 → \"0.93\", 0.8 → \"0.8\", 1 → \"1\". */\nexport const formatProbability = (p: number): string => String(Math.round(p * 100) / 100)\n","import type {\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './mcp-types.js'\n\n/**\n * MCP elicitation, the part of it that is not React: what a field of a server's form is drawn\n * as, what the user typed turned into the answer, the checks an answer must pass before it is\n * sent (the core's own rules, so the form says what is wrong instead of the tool call failing),\n * what a link may be opened as, and the queue of questions waiting for the user.\n *\n * Pure, and free of the MCP SDK and of the core's `./mcp` subpath: the prompt is in the main\n * entry of this package, the hooks that fill the queue are in `./mcp`.\n *\n * Nothing here keeps, logs or returns a value the user entered except to the one caller that\n * hands it to the server: an issue names the field and the rule, never the value.\n */\n\n// ── a question waiting for the user ──────────────────────────────────────\n\n/**\n * A question waiting for the user: the core's request (every string in it is the SERVER's\n * text), and when the core will stop waiting for the answer.\n */\nexport interface PendingElicitation extends McpElicitationRequest {\n /** Epoch ms after which the core cancels the question by itself; absent when it has no limit. */\n expiresAt?: number\n}\n\n/** The core's default for `elicitation.timeoutMs` (`MCP_ELICITATION_TIMEOUT_MS`). */\nexport const ELICITATION_TIMEOUT_MS = 300_000\n\n/**\n * The hooks' `elicitation` option as the core's settings, or `undefined` when it is off - and\n * then NOTHING is passed to the core: no capability is declared and the wire is what it was.\n */\nexport const elicitationSettings = (\n option: boolean | McpElicitationOptions | undefined | null,\n): McpElicitationOptions | undefined => {\n if (option === true) return {}\n if (typeof option === 'object' && option !== null) return { ...option }\n return undefined\n}\n\n/**\n * What the hooks add to the options of the core's `connectMcpHttp`: the handler and the\n * settings when elicitation is on, and NOTHING - not even the keys - when it is off.\n */\nexport const elicitationConnectOptions = (\n option: boolean | McpElicitationOptions | undefined | null,\n handler: McpElicitationHandler,\n): { onElicitation?: McpElicitationHandler; elicitation?: McpElicitationOptions } => {\n const settings = elicitationSettings(option)\n return settings ? { onElicitation: handler, elicitation: settings } : {}\n}\n\n/** The longest wait a timer holds (2^31 - 1 ms); the core takes a longer `timeoutMs` as none. */\nconst TIMER_MAX_MS = 2_147_483_647\n\n/**\n * How long the core waits for an answer with these settings; `undefined` = no limit of its own\n * (`0`, `Infinity`, more than a timer holds - the core's own rules).\n */\nexport const elicitationTimeoutOf = (settings: McpElicitationOptions): number | undefined => {\n const raw = settings.timeoutMs\n if (raw === undefined || raw === null) return ELICITATION_TIMEOUT_MS\n if (typeof raw !== 'number' || !(raw > 0) || raw > TIMER_MAX_MS) return undefined\n return Math.max(1, Math.floor(raw))\n}\n\nexport interface ElicitationQueueOptions {\n /**\n * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read\n * when a question arrives (the settings of the connection that is open then).\n */\n timeoutMs?: number | (() => number | undefined)\n /** Called whenever the list of pending questions changed. */\n onChange?: (pending: PendingElicitation[]) => void\n /** The clock (tests). */\n now?: () => number\n}\n\nexport interface ElicitationQueue {\n /** The core's `onElicitation`: resolves when the user answers, or as `cancel`. */\n handler: McpElicitationHandler\n /** The questions waiting, oldest first. */\n pending: () => PendingElicitation[]\n /** Answer one. False when no such question is waiting (answered, expired, cancelled). */\n answer: (id: string, result: McpElicitationResult) => boolean\n /** Cancel the waiting questions - all of them, or those `match` picks (one server's). */\n cancel: (match?: (request: PendingElicitation) => boolean) => void\n /** Cancel everything and stop reporting: the owner is gone. A later question is cancelled at once. */\n dispose: () => void\n}\n\n/**\n * The questions MCP servers are waiting on: `request.id → resolver`. A question leaves the queue\n * exactly once - answered by the user, cancelled because the core no longer wants the answer\n * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (a disconnect, an\n * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.\n */\nexport const createElicitationQueue = (options: ElicitationQueueOptions = {}): ElicitationQueue => {\n const now = options.now ?? Date.now\n const waiting = new Map<\n string,\n { request: PendingElicitation; settle: (result: McpElicitationResult) => void }\n >()\n let disposed = false\n\n const list = (): PendingElicitation[] => [...waiting.values()].map((w) => w.request)\n const changed = (): void => {\n if (!disposed) options.onChange?.(list())\n }\n\n const handler: McpElicitationHandler = (request, ctx) =>\n new Promise<McpElicitationResult>((resolve) => {\n const signal = ctx?.signal\n // Nobody to ask, or nobody wants the answer any more.\n if (disposed || signal?.aborted || waiting.has(request.id)) {\n resolve({ action: 'cancel' })\n return\n }\n // The core no longer wants the answer: its time ran out, or the run stopped.\n const onAbort = (): void => {\n if (waiting.get(request.id)?.settle !== settle) return\n settle({ action: 'cancel' })\n changed()\n }\n const settle = (result: McpElicitationResult): void => {\n // Exactly once: a second answer to the same question finds nothing to resolve.\n if (waiting.get(request.id)?.settle !== settle) return\n waiting.delete(request.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(result)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n const timeoutMs =\n typeof options.timeoutMs === 'function' ? options.timeoutMs() : options.timeoutMs\n waiting.set(request.id, {\n request: {\n ...request,\n ...(timeoutMs !== undefined ? { expiresAt: now() + timeoutMs } : {}),\n },\n settle,\n })\n changed()\n })\n\n return {\n handler,\n pending: list,\n answer: (id, result) => {\n const entry = waiting.get(id)\n if (!entry) return false\n entry.settle(result)\n changed()\n return true\n },\n cancel: (match) => {\n let any = false\n for (const entry of [...waiting.values()]) {\n if (match && !match(entry.request)) continue\n entry.settle({ action: 'cancel' })\n any = true\n }\n if (any) changed()\n },\n dispose: () => {\n disposed = true\n for (const entry of [...waiting.values()]) entry.settle({ action: 'cancel' })\n },\n }\n}\n\n// ── a form: fields, values, the answer ───────────────────────────────────\n\n/** What a field is drawn as. */\nexport type ElicitationControl =\n 'text' | 'email' | 'url' | 'date' | 'datetime' | 'number' | 'checkbox' | 'select' | 'multiselect'\n\nexport interface ElicitationOption {\n /** What goes back to the server, verbatim. */\n value: string\n /** What the user reads (the option's title, or the value). */\n label: string\n}\n\n/** One field of a form, ready to draw. `label`, `description` and option labels are the server's text. */\nexport interface ElicitationField {\n name: string\n label: string\n description?: string\n required: boolean\n control: ElicitationControl\n /** `select` / `multiselect`. */\n options?: ElicitationOption[]\n schema: McpElicitationFieldSchema\n}\n\n/** What the form holds while it is being filled in: text as typed, a tick, the ticked options. */\nexport type ElicitationDraftValue = string | boolean | string[]\nexport type ElicitationDraft = Record<string, ElicitationDraftValue>\n\nconst titled = (options: { const: string; title: string }[]): ElicitationOption[] =>\n options.map((o) => ({ value: o.const, label: o.title || o.const }))\n\n/** The options of a select, in the three forms the core lets through. */\nconst optionsOf = (schema: McpElicitationFieldSchema): ElicitationOption[] | undefined => {\n if (schema.type === 'array') {\n const items = schema.items\n if (items?.anyOf) return titled(items.anyOf)\n return (items?.enum ?? []).map((value) => ({ value, label: value }))\n }\n if (schema.type !== 'string') return undefined\n if (schema.oneOf) return titled(schema.oneOf)\n if (schema.enum) {\n const names = schema.enumNames\n return schema.enum.map((value, i) => ({ value, label: names?.[i] || value }))\n }\n return undefined\n}\n\nconst controlOf = (schema: McpElicitationFieldSchema): ElicitationControl => {\n switch (schema.type) {\n case 'boolean':\n return 'checkbox'\n case 'number':\n case 'integer':\n return 'number'\n case 'array':\n return 'multiselect'\n default:\n if (schema.enum || schema.oneOf) return 'select'\n switch (schema.format) {\n case 'email':\n return 'email'\n case 'uri':\n return 'url'\n case 'date':\n return 'date'\n case 'date-time':\n return 'datetime'\n default:\n return 'text'\n }\n }\n}\n\n/**\n * The fields of a form in the order the server listed them - exactly the set the core's schema\n * guard lets through: a text (plain, email, uri, date, date-time), a number / integer, a\n * boolean, a single select (`enum`, `enum` + `enumNames`, `oneOf`) and a multi-select (an array\n * of `enum` or `anyOf` options).\n */\nexport const elicitationFields = (schema: McpElicitationSchema | undefined): ElicitationField[] => {\n const required = new Set(schema?.required ?? [])\n return Object.entries(schema?.properties ?? {}).map(([name, field]) => {\n const options = optionsOf(field)\n return {\n name,\n label: field.title || name,\n ...(field.description ? { description: field.description } : {}),\n required: required.has(name),\n control: controlOf(field),\n ...(options ? { options } : {}),\n schema: field,\n }\n })\n}\n\nconst pad = (n: number): string => String(n).padStart(2, '0')\n\n// A date-time default as `<input type=\"datetime-local\">` wants it (local time, to the minute).\nconst toLocalInput = (value: string): string => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return ''\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/** What the form starts with: the schema's defaults (the core dropped the ones that do not fit). */\nexport const elicitationInitialDraft = (\n schema: McpElicitationSchema | undefined,\n): ElicitationDraft => {\n const draft: ElicitationDraft = {}\n for (const field of elicitationFields(schema)) {\n const preset = field.schema.default\n switch (field.control) {\n case 'checkbox':\n draft[field.name] = preset === true\n break\n case 'multiselect':\n draft[field.name] = Array.isArray(preset) ? [...preset] : []\n break\n case 'number':\n draft[field.name] = typeof preset === 'number' ? String(preset) : ''\n break\n case 'datetime':\n draft[field.name] = typeof preset === 'string' ? toLocalInput(preset) : ''\n break\n default:\n draft[field.name] = typeof preset === 'string' ? preset : ''\n }\n }\n return draft\n}\n\n/** The rules an answer can break. An issue never carries the value. */\nexport type ElicitationIssueKind =\n | 'required'\n | 'tooShort'\n | 'tooLong'\n | 'email'\n | 'uri'\n | 'date'\n | 'dateTime'\n | 'notNumber'\n | 'notInteger'\n | 'belowMinimum'\n | 'aboveMaximum'\n | 'notAnOption'\n | 'tooFew'\n | 'tooMany'\n\nexport interface ElicitationIssue {\n kind: ElicitationIssueKind\n /** The limit the rule states (a length, a bound, a count), when it has one. */\n limit?: number\n}\n\n/** The longest text a field without its own `maxLength` takes (the core's cap). */\nexport const ELICITATION_VALUE_MAX_CHARS = 10_000\n/** The most options one multi-select may be answered with (the core's cap). */\nexport const ELICITATION_MAX_OPTIONS = 100\n\n// A number as a person types it: digits, a sign, a decimal point, an exponent. `Number('')` is\n// 0 and `Number(' 1 ')` is 1, so the text is checked first.\nconst NUMBER = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)(e[+-]?\\d+)?$/i\n\nconst numberOf = (text: string): number | undefined => {\n const trimmed = text.trim()\n if (!NUMBER.test(trimmed)) return undefined\n const n = Number(trimmed)\n return Number.isFinite(n) ? n : undefined\n}\n\n// The core's `validFormat`, rule for rule.\nconst formatIssue = (\n format: McpElicitationFieldSchema['format'],\n value: string,\n): ElicitationIssueKind | undefined => {\n switch (format) {\n case 'email':\n return /^[^@\\s]+@[^@\\s]+$/.test(value) ? undefined : 'email'\n case 'uri':\n try {\n return new URL(value) ? undefined : 'uri'\n } catch {\n return 'uri'\n }\n case 'date':\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'date'\n case 'date-time':\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'dateTime'\n default:\n return undefined\n }\n}\n\n// A date-time goes back as RFC 3339 with its offset (UTC): the input's value is local time\n// without one, which a server could read as any zone.\nconst dateTimeOf = (value: string): string => {\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? value : date.toISOString()\n}\n\ntype FieldAnswer =\n { issue: ElicitationIssue } | { value: string | number | boolean | string[] } | { empty: true }\n\n// One field: its value as the server gets it, why it does not fit, or \"left empty\".\nconst answerOf = (field: ElicitationField, raw: ElicitationDraftValue | undefined): FieldAnswer => {\n const { schema } = field\n switch (field.control) {\n case 'checkbox':\n // A tick box always has a value: unticked is `false`, which is an answer.\n return { value: raw === true }\n case 'multiselect': {\n const picked = Array.isArray(raw) ? raw : []\n // Nothing ticked in an optional list is \"not answered\", as an empty text is.\n if (picked.length === 0 && !field.required) return { empty: true }\n const allowed = new Set((field.options ?? []).map((o) => o.value))\n if (!picked.every((item) => allowed.has(item))) return { issue: { kind: 'notAnOption' } }\n if (schema.minItems !== undefined && picked.length < schema.minItems) {\n return { issue: { kind: 'tooFew', limit: schema.minItems } }\n }\n const max = Math.min(schema.maxItems ?? ELICITATION_MAX_OPTIONS, ELICITATION_MAX_OPTIONS)\n if (picked.length > max) return { issue: { kind: 'tooMany', limit: max } }\n return { value: [...picked] }\n }\n case 'number': {\n const text = typeof raw === 'string' ? raw.trim() : ''\n if (!text) return { empty: true }\n const n = numberOf(text)\n if (n === undefined) return { issue: { kind: 'notNumber' } }\n if (schema.type === 'integer' && !Number.isInteger(n)) {\n return { issue: { kind: 'notInteger' } }\n }\n if (schema.minimum !== undefined && n < schema.minimum) {\n return { issue: { kind: 'belowMinimum', limit: schema.minimum } }\n }\n if (schema.maximum !== undefined && n > schema.maximum) {\n return { issue: { kind: 'aboveMaximum', limit: schema.maximum } }\n }\n return { value: n }\n }\n case 'select': {\n const text = typeof raw === 'string' ? raw : ''\n if (!text) return { empty: true }\n return (field.options ?? []).some((o) => o.value === text)\n ? { value: text }\n : { issue: { kind: 'notAnOption' } }\n }\n default: {\n const typed = typeof raw === 'string' ? raw : ''\n if (!typed) return { empty: true }\n const text = field.control === 'datetime' ? dateTimeOf(typed) : typed\n const max = schema.maxLength ?? ELICITATION_VALUE_MAX_CHARS\n if (text.length > max) return { issue: { kind: 'tooLong', limit: max } }\n if (schema.minLength !== undefined && text.length < schema.minLength) {\n return { issue: { kind: 'tooShort', limit: schema.minLength } }\n }\n const format = formatIssue(schema.format, text)\n return format ? { issue: { kind: format } } : { value: text }\n }\n }\n}\n\nexport type ElicitationFormOutcome =\n | { ok: true; content: Record<string, string | number | boolean | string[]> }\n | { ok: false; issues: Record<string, ElicitationIssue> }\n\n/**\n * A filled-in form as the answer the core will accept, or what is wrong with it, per field. The\n * rules are the core's (`validateMcpElicitationContent`): a required field is there, every\n * value is of its field's type and within its limits, and nothing the form did not ask for is\n * sent. A field left empty is left out, not sent as an empty text.\n */\nexport const elicitationFormAnswer = (\n schema: McpElicitationSchema | undefined,\n draft: ElicitationDraft,\n): ElicitationFormOutcome => {\n const content: Record<string, string | number | boolean | string[]> = {}\n const issues: Record<string, ElicitationIssue> = {}\n for (const field of elicitationFields(schema)) {\n const answer = answerOf(field, Object.hasOwn(draft, field.name) ? draft[field.name] : undefined)\n if ('issue' in answer) {\n issues[field.name] = answer.issue\n } else if ('empty' in answer) {\n if (field.required) issues[field.name] = { kind: 'required' }\n } else {\n content[field.name] = answer.value\n }\n }\n return Object.keys(issues).length > 0 ? { ok: false, issues } : { ok: true, content }\n}\n\n// ── a link ───────────────────────────────────────────────────────────────\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\nexport interface ElicitationLink {\n /** The host the link leads to (with its port), as the browser will resolve it; '' if unparseable. */\n host: string\n /** The whole link as text: the parsed form when it parses, what the server sent otherwise. */\n href: string\n /** Whether an \"Open\" action may exist for it: https, or http on a loopback host, no credentials. */\n openable: boolean\n}\n\n/**\n * A link a server wants the user to open, as the prompt may show it. The core already refuses\n * anything but https (http on loopback); this is the same rule applied again where the link is\n * about to be opened, because a host may hand the prompt a request the core never checked.\n */\nexport const elicitationLink = (raw: unknown): ElicitationLink => {\n const text = typeof raw === 'string' ? raw : ''\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return { host: '', href: text, openable: false }\n }\n const secure =\n url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n return {\n host: url.host,\n href: url.href,\n openable: secure && !url.username && !url.password && !/\\s/.test(text),\n }\n}\n\n// ── an answer nobody gave ────────────────────────────────────────────────\n\n/**\n * Why a question was answered without anybody deciding: the core's reasons\n * (`mcp.elicitation-answered` with `automatic: true`), and `stopped`, which the reducer sets on\n * whatever was still waiting when the run stopped.\n */\nexport type ElicitationOutcomeReason =\n | 'timeout'\n | 'step-timeout'\n | 'aborted'\n | 'stopped'\n | 'cap-per-call'\n | 'cap-per-run'\n | 'unsupported-schema'\n | 'unsupported-mode'\n | 'insecure-url'\n | 'invalid-request'\n | 'subagent'\n | 'handler-error'\n | 'invalid-answer'\n | 'after-failure'\n | 'no-tool-call'\n\n/** \"4:05\" - what is left of a question's time. */\nexport const formatCountdown = (ms: number): string => {\n const total = Math.max(0, Math.ceil(ms / 1000))\n return `${Math.floor(total / 60)}:${pad(total % 60)}`\n}\n","/**\n * Input protection for the buttons that SAY YES to an MCP App (its tool call's \"Allow once\" /\n * \"Always allow\", a link's \"Open\", a file's \"Save\", sampling's \"Allow\"): the way a browser's own\n * permission prompts guard theirs. A prompt an app causes appears when the APP chooses - while\n * the person types, holds a key or double-clicks something in the app - and where its layout\n * puts it, so an input aimed at something else must not land on \"yes\".\n *\n * A button is ARMED only once it has been on screen, in one place, for `PROMPT_ARM_MS`; it is\n * disarmed again the moment it moves, is covered, leaves the screen or the page is hidden. A\n * click counts only when it is armed now AND began while it was armed: its pointerdown (a\n * pointer's click) or its Enter / Space keydown (a key's) came after the arming. A key repeat\n * never counts, and a keydown that does not count is swallowed. A click with no key and no\n * pointer behind it (assistive technology activating the button) counts when it is armed.\n *\n * Pure: the clock and the button's place are passed in (`ArmedButton` reads them from the DOM).\n */\n\n/** How long a button must have been shown, still, before it takes a click. */\nexport const PROMPT_ARM_MS = 500\n\nexport interface PromptArming {\n /** Armed now. */\n readonly armed: boolean\n /**\n * One look at the button: where it is on screen (any string that changes when it moves), or\n * `undefined` when it is not shown (off screen, covered, the page hidden). Returns `armed`.\n */\n sample: (where: string | undefined, now: number) => boolean\n /** A pointer went down on the button. */\n pointerDown: (at: number) => void\n /** A key went down on the button. False: swallow it (`preventDefault`) - it must not act. */\n keyDown: (key: { key: string; repeat: boolean }, at: number) => boolean\n /** A click reached the button (`detail` > 0 for a pointer's). True: it may act. */\n click: (detail: number, now: number) => boolean\n}\n\nconst ACTIVATING_KEYS = new Set(['Enter', ' ', 'Spacebar'])\n\nexport const createPromptArming = (delayMs: number = PROMPT_ARM_MS): PromptArming => {\n const delay = Number.isFinite(delayMs) && delayMs >= 0 ? delayMs : PROMPT_ARM_MS\n let where: string | undefined\n // When it came to where it is; when it was armed (Infinity: it is not).\n let since = 0\n let armedAt = Number.POSITIVE_INFINITY\n // The press behind the next click: a pointer's, a key's.\n let downAt = Number.NEGATIVE_INFINITY\n let key: 'none' | 'counts' | 'blocked' = 'none'\n let keyAt = Number.NEGATIVE_INFINITY\n return {\n get armed() {\n return armedAt !== Number.POSITIVE_INFINITY\n },\n sample(next, now) {\n if (next === undefined || next !== where) {\n where = next\n since = now\n armedAt = Number.POSITIVE_INFINITY\n return false\n }\n if (armedAt === Number.POSITIVE_INFINITY && now - since >= delay) armedAt = now\n return armedAt !== Number.POSITIVE_INFINITY\n },\n pointerDown(at) {\n downAt = at\n },\n keyDown(k, at) {\n if (!ACTIVATING_KEYS.has(k.key)) return true\n if (k.repeat || at < armedAt) {\n key = 'blocked'\n keyAt = at\n return false\n }\n key = 'counts'\n keyAt = at\n return true\n },\n click(detail, now) {\n const armedNow = armedAt <= now\n const ok =\n detail > 0\n ? armedNow && downAt >= armedAt\n : armedNow && (key === 'none' || (key === 'counts' && keyAt >= armedAt))\n downAt = Number.NEGATIVE_INFINITY\n key = 'none'\n return ok\n },\n }\n}\n","import * as core from '@dudko.dev/agent-web'\nimport type { IUsage } from '@dudko.dev/agent-web'\nimport type { ChatAttachment, ChatMessage } from './types.js'\n\n/**\n * Saved conversations — the transcript a chat UI shows (messages with their\n * tool calls, usage and image attachments), one record per conversation. The\n * agent's own memory (what the MODEL sees) lives in the core's ContextStore\n * under the same id; keep both and a reloaded chat continues where it was.\n */\nexport interface ChatRecord {\n /** Also the agent's memory session id. */\n id: string\n title: string\n createdAt: number\n updatedAt: number\n messages: ChatMessage[]\n totalUsage?: IUsage\n}\n\n/** A list entry (no messages). */\nexport type ChatSummary = Omit<ChatRecord, 'messages'> & { messageCount: number }\n\nexport interface ChatHistoryStoreOptions {\n /** IndexedDB database (default 'agent-web-react'). */\n dbName?: string\n /** Object store (default 'chats'). */\n storeName?: string\n /** Keep chats in memory only (tests, private mode; also the fallback without IndexedDB). */\n memory?: boolean\n}\n\nconst DB_VERSION = 1\n\nconst req = <T>(r: IDBRequest<T>): Promise<T> =>\n new Promise((resolve, reject) => {\n r.onsuccess = () => resolve(r.result)\n r.onerror = () => reject(r.error)\n })\n\n/**\n * A write, settled when its transaction COMMITTED (a request's success comes before that: the\n * transaction can still abort). Only then may the other tabs be told.\n */\nconst committed = (tx: IDBTransaction, r: IDBRequest): Promise<void> =>\n new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve()\n tx.onabort = () => reject(tx.error ?? r.error ?? new Error('the transaction was aborted'))\n tx.onerror = () => reject(tx.error ?? r.error)\n })\n\n/**\n * IndexedDB-backed chat history (raw IndexedDB — no extra dependency). Every tab of the origin\n * shares it: once a write has committed the other tabs hear which chat changed (a `chats`\n * notice from the core's `postStorageChange` - the id, never a message), and `useChatHistory`\n * there refreshes.\n */\nexport class ChatHistoryStore {\n /** The IndexedDB database (undefined in memory): the name its `chats` notices go out under. */\n readonly dbName: string | undefined\n private readonly name: string\n private readonly storeName: string\n private readonly memory?: Map<string, ChatRecord>\n private db?: Promise<IDBDatabase>\n\n constructor(opts: ChatHistoryStoreOptions = {}) {\n this.name = opts.dbName ?? 'agent-web-react'\n this.storeName = opts.storeName ?? 'chats'\n if (opts.memory || typeof indexedDB === 'undefined') this.memory = new Map()\n this.dbName = this.memory ? undefined : this.name\n }\n\n /**\n * The store's connection, opened on first use. Never in another tab's way: when another\n * connection asks to delete or upgrade the database (`versionchange` - another tab's\n * `indexedDB.deleteDatabase`, a newer copy of this package), it is closed at once, so that\n * request goes ahead instead of waiting for this tab to close; one the browser closed by itself\n * (site data cleared) is let go too. The next use opens the database again - after a deletion a\n * new, empty one (no chats: `list()` is empty, a save starts it again); after an upgrade by a\n * newer copy, the open fails until the page is reloaded with that copy.\n */\n private open(): Promise<IDBDatabase> {\n if (this.db) return this.db\n const opening: Promise<IDBDatabase> = new Promise<IDBDatabase>((resolve, reject) => {\n const r = indexedDB.open(this.name, DB_VERSION)\n r.onupgradeneeded = () => {\n if (!r.result.objectStoreNames.contains(this.storeName)) {\n r.result.createObjectStore(this.storeName, { keyPath: 'id' })\n }\n }\n r.onsuccess = () => {\n const db = r.result\n const forget = () => {\n if (this.db === opening) this.db = undefined\n }\n // Listeners, not `onversionchange` / `onclose`: a host's own handler on the connection\n // is not replaced, and cannot replace these.\n db.addEventListener('versionchange', () => {\n forget()\n db.close()\n })\n db.addEventListener('close', forget)\n resolve(db)\n }\n r.onerror = () => reject(r.error)\n }).catch((err: unknown) => {\n if (this.db === opening) this.db = undefined\n throw err\n })\n this.db = opening\n return opening\n }\n\n private async tx(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open()\n return db.transaction(this.storeName, mode).objectStore(this.storeName)\n }\n\n /** One write in its own transaction, resolved once it committed - then the notice. */\n private async write(\n op: (store: IDBObjectStore) => IDBRequest,\n notice: { op: 'put' | 'delete' | 'clear'; key?: string },\n ): Promise<void> {\n const db = await this.open()\n const tx = db.transaction(this.storeName, 'readwrite')\n await committed(tx, op(tx.objectStore(this.storeName)))\n this.announce(notice)\n }\n\n private announce(notice: { op: 'put' | 'delete' | 'clear'; key?: string }): void {\n if (typeof core.postStorageChange === 'function') {\n core.postStorageChange(this.dbName, { kind: 'chats', ...notice })\n }\n }\n\n /**\n * Read the stored record and write what `merge` makes of it in ONE readwrite transaction: no\n * other tab's save can land between the read and the write. `merge` is synchronous (a\n * transaction does not survive an await). Resolves with what was written, once committed.\n */\n async putMerged(\n id: string,\n merge: (stored: ChatRecord | undefined) => ChatRecord,\n ): Promise<ChatRecord> {\n if (this.memory) {\n const record = merge(this.memory.get(id))\n this.memory.set(record.id, structuredClone(record))\n return record\n }\n const db = await this.open()\n const tx = db.transaction(this.storeName, 'readwrite')\n const store = tx.objectStore(this.storeName)\n let written: ChatRecord | undefined\n let failed: unknown\n const read = store.get(id) as IDBRequest<ChatRecord | undefined>\n const done = committed(tx, read)\n read.onsuccess = () => {\n try {\n written = merge(read.result)\n store.put(written)\n } catch (err) {\n failed = err\n tx.abort()\n }\n }\n try {\n await done\n } catch (err) {\n throw failed ?? err\n }\n if (!written) throw new Error('the chat could not be saved')\n this.announce({ op: 'put', key: id })\n return written\n }\n\n async list(): Promise<ChatSummary[]> {\n const all = this.memory\n ? [...this.memory.values()]\n : await req((await this.tx('readonly')).getAll() as IDBRequest<ChatRecord[]>)\n return all\n .map(({ messages, ...rest }) => ({ ...rest, messageCount: messages.length }))\n .sort((a, b) => b.updatedAt - a.updatedAt)\n }\n\n async get(id: string): Promise<ChatRecord | undefined> {\n if (this.memory) return this.memory.get(id)\n return req((await this.tx('readonly')).get(id) as IDBRequest<ChatRecord | undefined>)\n }\n\n async put(record: ChatRecord): Promise<void> {\n if (this.memory) {\n this.memory.set(record.id, structuredClone(record))\n return\n }\n await this.write((store) => store.put(record), { op: 'put', key: record.id })\n }\n\n async delete(id: string): Promise<void> {\n if (this.memory) {\n this.memory.delete(id)\n return\n }\n await this.write((store) => store.delete(id), { op: 'delete', key: id })\n }\n\n async clear(): Promise<void> {\n if (this.memory) {\n this.memory.clear()\n return\n }\n await this.write((store) => store.clear(), { op: 'clear' })\n }\n}\n\n/** The words a chat's title and a message of attachments only are said with (`AgentLabels`'). */\nexport interface AttachmentTexts {\n /** A recording - audio attachments only (default \"Voice message\"). */\n voiceMessage?: string\n}\n\n/**\n * A message of attachments only, in words - where a text is needed (a chat's title, the name a\n * screen reader gives the message): `voiceMessage` when every attachment is audio (a voice\n * message), else the files' names.\n */\nexport const attachmentsText = (\n attachments: readonly ChatAttachment[],\n texts: AttachmentTexts = {},\n): string =>\n attachments.length > 0 && attachments.every((a) => a.mediaType.toLowerCase().startsWith('audio/'))\n ? (texts.voiceMessage ?? 'Voice message')\n : attachments.map((a) => a.name).join(', ')\n\nconst oneLine = (text: string | undefined): string => (text ?? '').replace(/\\s+/g, ' ').trim()\n\n/**\n * A chat's title: its first user message, trimmed. A first message of attachments only is named\n * by what was said in it once the run has transcribed it (the next answer's transcript of an\n * attachment), else by `attachmentsText` - \"Voice message\", or the files' names.\n */\nexport const chatTitle = (messages: ChatMessage[], texts: AttachmentTexts = {}): string => {\n const at = messages.findIndex((m) => m.role === 'user')\n const user = at >= 0 ? messages[at] : undefined\n let first = oneLine(user?.content)\n if (!first && user?.attachments?.length) {\n const answer = messages.slice(at + 1).find((m) => m.role === 'assistant')\n const heard = answer?.transcripts?.find((t) => t.source === 'attachment')?.text\n first = oneLine(heard) || oneLine(attachmentsText(user.attachments, texts))\n }\n if (!first) return 'New chat'\n return first.length > 60 ? `${first.slice(0, 59)}…` : first\n}\n\n/** A fresh, sortable conversation id (also a valid memory session id). */\nexport const newChatId = (): string =>\n `chat-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n\n// ── Two tabs, one chat: the merge of a save ─────────────────────────────────\n\nconst USAGE_KEYS = [\n 'inputTokens',\n 'outputTokens',\n 'totalTokens',\n 'reasoningTokens',\n 'cachedInputTokens',\n 'cacheWriteTokens',\n] as const\n\nconst sumUsage = (base: IUsage | undefined, more: (IUsage | undefined)[]): IUsage => {\n const out = { ...(base ?? {}) } as Record<string, number>\n for (const u of more) {\n if (!u) continue\n for (const k of USAGE_KEYS) out[k] = (out[k] ?? 0) + (u[k] ?? 0)\n }\n for (const k of USAGE_KEYS) out[k] ??= 0\n return out as unknown as IUsage\n}\n\n/** Ids for messages appended after `after`'s: past its highest `msg-<n>`, so none collide. */\nconst renumber = (own: ChatMessage[], after: ChatMessage[]): ChatMessage[] => {\n let next = after.reduce(\n (max, m) => Math.max(max, Number(/^msg-(\\d+)$/.exec(m.id)?.[1] ?? -1)),\n -1,\n )\n return own.map((m) => ({ ...m, id: `msg-${(next += 1)}` }))\n}\n\n/** When a message's turn began, if it says (a finite number: a record from elsewhere may not). */\nconst turnAt = (m: ChatMessage): number | undefined =>\n typeof m.startedAt === 'number' && Number.isFinite(m.startedAt) ? m.startedAt : undefined\n\n/**\n * The stored messages with this tab's own new ones (in their order) among them, each where its\n * turn belongs: after every stored message, except a stored turn that began LATER - another tab's,\n * run once this tab's had given the session back and saved first (this tab was frozen before its\n * save) - which it goes before. Only what the times tell: a stored message without one is never\n * passed (a chat saved before turns had times merges as it always did: this tab's own after it),\n * nor is one of the same time, and an own message without one goes after all that is stored. It\n * only inserts: nothing is dropped, doubled or moved among the stored ones.\n */\nconst placeByTurn = (stored: ChatMessage[], own: ChatMessage[]): ChatMessage[] => {\n // The stored messages that may be passed: those after the last one without a time.\n let i = stored.length\n while (i > 0 && turnAt(stored[i - 1]) !== undefined) i -= 1\n const out = stored.slice(0, i)\n for (const m of own) {\n const at = turnAt(m)\n // Every stored message up to the first whose turn began after this one's (all of them when\n // this one has no time). Past the last untimed one, each stored message has a time.\n while (i < stored.length && (at === undefined || turnAt(stored[i])! <= at)) {\n out.push(stored[i])\n i += 1\n }\n out.push(m)\n }\n return [...out, ...stored.slice(i)]\n}\n\n/** What this tab last read or wrote of a chat: the very message objects, and when. */\nexport interface ChatBase {\n /** The messages as read or written (by identity: an edit, a reset or a trim is not \"known\"). */\n known: ReadonlySet<ChatMessage>\n updatedAt: number\n}\n\n/** This tab's view holds a message of its own (not another tab's, relayed) it never read or wrote. */\nexport const ownUnsaved = (messages: ChatMessage[], base: ChatBase | undefined): boolean =>\n messages.some((m) => !m.remote && !base?.known.has(m))\n\n/** This tab's view says nothing new (every message is one it read or wrote). */\nexport const unchangedSince = (messages: ChatMessage[], base: ChatBase | undefined): boolean =>\n base !== undefined &&\n messages.length === base.known.size &&\n messages.every((m) => base.known.has(m))\n\n/**\n * The record to save. A turn this tab only followed from another tab (`remote`) is never saved\n * from here - that tab saves its own, unclipped copy. When another tab saved the chat after this\n * tab last read or wrote it (or saved a chat this tab never read), THAT record is the truth for\n * everything that is not this tab's own: this tab's own new messages - by identity, not by count,\n * so a reset or a trim here drops nothing there - go after it, each before a stored turn that\n * began after its own (`ChatMessage.startedAt`: this tab saved its turn late, after another tab\n * ran the next one and saved first). Without times, after it all.\n */\nexport const mergeChatRecord = (\n view: ChatRecord,\n stored: ChatRecord | undefined,\n base: ChatBase | undefined,\n /** The words of a title of attachments only (`chatTitle`). */\n texts?: AttachmentTexts,\n): { record: ChatRecord; merged: boolean } => {\n const local = view.messages.filter((m) => !m.remote)\n if (!stored || (base && stored.updatedAt <= base.updatedAt)) {\n return { record: { ...view, messages: local }, merged: false }\n }\n const own = local.filter((m) => !base?.known.has(m))\n const messages = placeByTurn(stored.messages, renumber(own, stored.messages))\n return {\n record: {\n ...view,\n createdAt: stored.createdAt,\n title: chatTitle(messages, texts),\n messages,\n totalUsage: sumUsage(\n stored.totalUsage,\n own.map((m) => (m.role === 'assistant' ? m.usage : undefined)),\n ),\n },\n merged: true,\n }\n}\n\n/**\n * What `useChatHistory` does to save the open chat: the stored record is read and the merged one\n * written in ONE readwrite transaction (`ChatHistoryStore.putMerged`), so another tab's save\n * cannot land between the two.\n */\nexport const saveChat = async (\n store: ChatHistoryStore,\n view: ChatRecord,\n base: ChatBase | undefined,\n texts?: AttachmentTexts,\n): Promise<{ record: ChatRecord; merged: boolean }> => {\n let merged = false\n const record = await store.putMerged(view.id, (stored) => {\n const out = mergeChatRecord(view, stored, base, texts)\n merged = out.merged\n return out.record\n })\n return { record, merged }\n}\n","/**\n * Recording from the microphone, for dictation through a model and for voice messages. No React:\n * a hook and the composer are built on it. The browser's `getUserMedia` and `MediaRecorder` can\n * be handed in (`RecordingDeps`), which is how the tests drive it.\n *\n * The rules it keeps:\n * - the permission is asked only by `startRecording` - call it from the person's tap;\n * - every track of the stream is stopped when the recording ends: stopped, cancelled, cut at its\n * longest, or failed - the browser's \"recording\" indicator goes away;\n * - nothing is kept here: the audio is handed to the caller once, as a `Blob`.\n */\n\n/** Why the microphone could not be used, as the composer says it (`micProblemLabel`). */\nexport type MicProblem =\n /** The person (or the browser, for this site) refused the permission. */\n | 'not-allowed'\n /** No microphone on the device (or none that fits). */\n | 'audio-capture'\n /** The microphone is held by another app (or the system refused to start it). */\n | 'busy'\n /** No recording here at all: no `mediaDevices` (an insecure page) or no `MediaRecorder`. */\n | 'unsupported'\n | 'failed'\n\n/** An error of the microphone, with its `MicProblem`. */\nexport class MicError extends Error {\n readonly code: MicProblem\n constructor(code: MicProblem, message: string = code) {\n super(message)\n this.name = 'MicError'\n this.code = code\n }\n}\n\n/** What a recording gave: the bytes, their media type (no codec parameters) and how long it ran. */\nexport interface RecordedAudio {\n blob: Blob\n /** `audio/webm`, `audio/mp4` (Safari, iOS), `audio/ogg`... - the container, without `;codecs=`. */\n mediaType: string\n durationMs: number\n}\n\n/** The slice of `MediaRecorder` this module drives. */\nexport interface MediaRecorderLike {\n readonly mimeType: string\n readonly state: 'inactive' | 'recording' | 'paused'\n start(timeslice?: number): void\n stop(): void\n ondataavailable: ((event: { data: Blob }) => void) | null\n onstop: (() => void) | null\n onerror: ((event: unknown) => void) | null\n}\n\nexport interface MediaRecorderConstructorLike {\n new (stream: MediaStream, options?: { mimeType?: string }): MediaRecorderLike\n isTypeSupported?(type: string): boolean\n}\n\nexport interface RecordingDeps {\n /** Default: `navigator.mediaDevices.getUserMedia`. */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>\n /** Default: the page's `MediaRecorder`. */\n MediaRecorder?: MediaRecorderConstructorLike\n /** Default: `Date.now`. */\n now?: () => number\n}\n\n/** The longest recording unless the caller says otherwise: five minutes. */\nexport const RECORDING_DEFAULT_MAX_MS = 5 * 60 * 1000\n\n/**\n * The containers asked for, in order: Opus in WebM (Chrome, Edge, Firefox), AAC in MP4 (Safari -\n * iOS records nothing else), Opus in Ogg. Every one is a type the core transcribes and plays.\n */\nexport const RECORDING_TYPES = [\n 'audio/webm;codecs=opus',\n 'audio/webm',\n 'audio/mp4',\n 'audio/ogg;codecs=opus',\n 'audio/ogg',\n] as const\n\n/** The first type the recorder takes, or undefined (the browser then picks its own). */\nexport const pickRecordingType = (\n isTypeSupported: ((type: string) => boolean) | undefined,\n): string | undefined => {\n if (!isTypeSupported) return undefined\n for (const type of RECORDING_TYPES) {\n try {\n if (isTypeSupported(type)) return type\n } catch {\n /* a browser that throws for a type it does not know */\n }\n }\n return undefined\n}\n\n/**\n * A recorder's media type as a file's: the container without parameters, and the names browsers\n * use for the same thing brought to one (`audio/x-m4a`, `audio/m4a`, `video/mp4` from Safari →\n * `audio/mp4`; `video/webm` → `audio/webm`). Unknown or empty: `audio/webm`.\n */\nexport const audioTypeOf = (type: string | undefined): string => {\n const base = (type ?? '').toLowerCase().split(';')[0].trim()\n if (/^(audio|video)\\/(mp4|x-m4a|m4a|aac-mp4)$/.test(base)) return 'audio/mp4'\n if (/^(audio|video)\\/webm$/.test(base)) return 'audio/webm'\n if (base === 'audio/ogg' || base === 'application/ogg') return 'audio/ogg'\n if (base === 'audio/wav' || base === 'audio/x-wav' || base === 'audio/wave') return 'audio/wav'\n if (base === 'audio/mpeg' || base === 'audio/mp3') return 'audio/mpeg'\n if (base === 'audio/aac') return 'audio/aac'\n return 'audio/webm'\n}\n\n/** The file extension of an audio type (`audioTypeOf`'s): `webm`, `m4a`, `ogg`, `wav`, `mp3`, `aac`. */\nexport const audioExtensionOf = (type: string): string =>\n (\n ({\n 'audio/mp4': 'm4a',\n 'audio/ogg': 'ogg',\n 'audio/wav': 'wav',\n 'audio/mpeg': 'mp3',\n 'audio/aac': 'aac',\n }) as Record<string, string>\n )[audioTypeOf(type)] ?? 'webm'\n\n/** What a failed `getUserMedia` (or recorder) means, by the DOMException's name. */\nexport const micProblemOf = (err: unknown): MicProblem => {\n if (err instanceof MicError) return err.code\n const name = err && typeof err === 'object' ? String((err as { name?: unknown }).name) : ''\n if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError')\n return 'not-allowed'\n if (\n name === 'NotFoundError' ||\n name === 'OverconstrainedError' ||\n name === 'DevicesNotFoundError'\n )\n return 'audio-capture'\n if (name === 'NotReadableError' || name === 'TrackStartError' || name === 'AbortError')\n return 'busy'\n if (name === 'NotSupportedError' || name === 'TypeError') return 'unsupported'\n return 'failed'\n}\n\nconst defaults = (deps: RecordingDeps) => {\n const g = globalThis as unknown as {\n navigator?: { mediaDevices?: { getUserMedia?: RecordingDeps['getUserMedia'] } }\n MediaRecorder?: MediaRecorderConstructorLike\n }\n const devices = g.navigator?.mediaDevices\n return {\n getUserMedia:\n deps.getUserMedia ?? (devices?.getUserMedia ? devices.getUserMedia.bind(devices) : undefined),\n MediaRecorder: deps.MediaRecorder ?? g.MediaRecorder,\n now: deps.now ?? Date.now,\n }\n}\n\n/** Whether this browser can record at all (it does not ask for anything). */\nexport const recordingSupported = (deps: RecordingDeps = {}): boolean => {\n const d = defaults(deps)\n return Boolean(d.getUserMedia && d.MediaRecorder)\n}\n\n/** Stop every track of a stream: the microphone is let go. */\nexport const stopTracks = (stream: MediaStream | undefined): void => {\n for (const track of stream?.getTracks() ?? []) {\n try {\n track.stop()\n } catch {\n /* already stopped */\n }\n }\n}\n\n/** A recording under way. */\nexport interface Recording {\n /** When it started (the clock of `RecordingDeps.now`). */\n readonly startedAt: number\n /** Stop it and get the audio. The microphone is let go first. */\n stop(): Promise<RecordedAudio>\n /** Throw it away. The microphone is let go; `stop` then rejects. */\n cancel(): void\n /** Settles when the recording has ended, whichever way (the tracks are stopped by then). */\n readonly ended: Promise<void>\n}\n\nexport interface StartRecordingOptions extends RecordingDeps {\n /** Cut it here (default `RECORDING_DEFAULT_MAX_MS`); `onLimit` is told, `stop` still gives the audio. */\n maxMs?: number\n onLimit?: () => void\n}\n\n/**\n * Ask for the microphone and start recording. Rejects with a `MicError` when the microphone\n * cannot be had (the permission refused, no device, held elsewhere, no recorder) - and then no\n * track is left running.\n */\nexport const startRecording = async (options: StartRecordingOptions = {}): Promise<Recording> => {\n const d = defaults(options)\n if (!d.getUserMedia || !d.MediaRecorder) throw new MicError('unsupported')\n let stream: MediaStream\n try {\n stream = await d.getUserMedia({ audio: true })\n } catch (err) {\n throw new MicError(micProblemOf(err))\n }\n let recorder: MediaRecorderLike\n try {\n const type = pickRecordingType(d.MediaRecorder.isTypeSupported?.bind(d.MediaRecorder))\n recorder = new d.MediaRecorder(stream, type ? { mimeType: type } : undefined)\n } catch (err) {\n stopTracks(stream)\n throw new MicError(micProblemOf(err) === 'failed' ? 'unsupported' : micProblemOf(err))\n }\n const startedAt = d.now()\n const chunks: Blob[] = []\n let cancelled = false\n let failure: MicError | undefined\n let settle: () => void = () => {}\n const ended = new Promise<void>((resolve) => (settle = resolve))\n let finish: ((audio: RecordedAudio) => void) | undefined\n let fail: ((err: Error) => void) | undefined\n const result = new Promise<RecordedAudio>((resolve, reject) => {\n finish = resolve\n fail = reject\n })\n // The promise is awaited only by `stop`; a cancelled recording rejects it unseen.\n result.catch(() => {})\n let limit: ReturnType<typeof setTimeout> | undefined\n const end = () => {\n stopTracks(stream)\n clearTimeout(limit)\n settle()\n }\n recorder.ondataavailable = (event) => {\n if (event.data && event.data.size > 0) chunks.push(event.data)\n }\n recorder.onerror = () => {\n failure = new MicError('failed')\n end()\n fail?.(failure)\n }\n recorder.onstop = () => {\n end()\n if (cancelled) return fail?.(new MicError('failed', 'cancelled'))\n if (failure) return fail?.(failure)\n const mediaType = audioTypeOf(recorder.mimeType || chunks[0]?.type)\n finish?.({\n blob: new Blob(chunks, { type: mediaType }),\n mediaType,\n durationMs: Math.max(0, d.now() - startedAt),\n })\n }\n const stopRecorder = () => {\n try {\n if (recorder.state !== 'inactive') recorder.stop()\n else recorder.onstop?.()\n } catch {\n recorder.onstop?.()\n }\n }\n const maxMs = options.maxMs ?? RECORDING_DEFAULT_MAX_MS\n limit = setTimeout(() => {\n stopRecorder()\n options.onLimit?.()\n }, maxMs)\n try {\n // Chunks every second: a recording cut short (a tab closed) has most of its audio.\n recorder.start(1000)\n } catch (err) {\n end()\n throw new MicError(micProblemOf(err) === 'failed' ? 'unsupported' : micProblemOf(err))\n }\n return {\n startedAt,\n ended,\n stop: () => {\n stopRecorder()\n return result\n },\n cancel: () => {\n cancelled = true\n chunks.length = 0\n stopRecorder()\n // Some recorders never fire `stop` after an error: the tracks go now in any case.\n end()\n },\n }\n}\n","import {\n micProblemOf,\n startRecording,\n type RecordedAudio,\n type Recording,\n type RecordingDeps,\n} from './record.js'\n\n/** The slice of the Web Speech API recognizer `useSpeechToText` (and any other front end) drives. */\nexport interface SpeechRecognizerLike {\n lang: string\n continuous: boolean\n interimResults: boolean\n start(): void\n stop(): void\n abort?(): void\n onresult: ((ev: SpeechResultEventLike) => void) | null\n /**\n * `error` is the Web Speech API's code (`not-allowed`, `audio-capture`, `network`, ...) or a\n * recognizer's own; `message`, when given, is what to say - in the host's words.\n */\n onerror: ((ev: { error?: string; message?: string }) => void) | null\n onend: (() => void) | null\n}\n\ninterface SpeechResultEventLike {\n resultIndex: number\n results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>\n}\n\n/** Turn a recording into text: the host's call to a speech-to-text model. */\nexport type TranscribeAudio = (\n audio: RecordedAudio,\n context: {\n /** The recognizer's language (BCP-47), a hint for the model. */\n lang: string\n /** Aborted when the person cancels (or the composer goes away). */\n signal: AbortSignal\n },\n) => Promise<string>\n\nexport interface RecordingRecognizerOptions extends RecordingDeps {\n /** The speech-to-text call - a provider's transcription model, an on-device engine. */\n transcribe: TranscribeAudio\n /** The longest dictation (default: the recorder's five minutes). */\n maxMs?: number\n}\n\n/**\n * A recognizer for `useSpeechToText` / the composer's mic (`speech.createRecognizer`) that\n * RECORDS and then hands the audio to `transcribe`: tap to start (the microphone is asked for\n * then), tap again to stop - the words arrive once, as one final result, after the model has\n * answered (`useSpeechToText().finishing` meanwhile). The microphone is let go as soon as the\n * recording stops; the audio is given to `transcribe` and kept nowhere.\n *\n * Errors come as the Web Speech API's codes where there is one (`not-allowed`, `audio-capture`),\n * the recorder's otherwise (`busy`, `unsupported`), and `transcription` with the thrown error's\n * `message` - say it in the host's words: the composer shows the message as given.\n */\nexport const createRecordingRecognizer =\n (options: RecordingRecognizerOptions): (() => SpeechRecognizerLike) =>\n () => {\n let recording: Recording | undefined\n let starting: Promise<void> | undefined\n let stopAsked = false\n let aborted = false\n let ended = false\n const controller = new AbortController()\n const rec: SpeechRecognizerLike = {\n lang: '',\n continuous: true,\n interimResults: false,\n onresult: null,\n onerror: null,\n onend: null,\n start() {\n if (starting) return\n starting = (async () => {\n try {\n recording = await startRecording({\n ...options,\n maxMs: options.maxMs,\n onLimit: () => rec.stop(),\n })\n } catch (err) {\n if (!aborted) rec.onerror?.({ error: micProblemOf(err) })\n return finish()\n }\n // Stopped (or aborted) while the permission was being asked: nothing is kept.\n if (aborted) {\n recording.cancel()\n return finish()\n }\n if (stopAsked) void transcribeNow()\n })()\n },\n stop() {\n if (stopAsked || ended) return\n stopAsked = true\n if (recording) void transcribeNow()\n },\n abort() {\n if (ended) return\n aborted = true\n controller.abort()\n recording?.cancel()\n if (!starting || recording) finish()\n },\n }\n const finish = () => {\n if (ended) return\n ended = true\n rec.onend?.()\n }\n let transcribing = false\n const transcribeNow = async () => {\n if (transcribing || !recording) return\n transcribing = true\n let audio: RecordedAudio\n try {\n audio = await recording.stop()\n } catch (err) {\n if (!aborted) rec.onerror?.({ error: micProblemOf(err) })\n return finish()\n }\n if (aborted) return finish()\n if (audio.blob.size === 0) return finish()\n try {\n const text = (\n await options.transcribe(audio, { lang: rec.lang, signal: controller.signal })\n )\n .replace(/\\s+/g, ' ')\n .trim()\n if (!aborted && text)\n rec.onresult?.({\n resultIndex: 0,\n results: [{ isFinal: true, 0: { transcript: text } }],\n })\n } catch (err) {\n if (!aborted)\n rec.onerror?.({\n error: 'transcription',\n message: err instanceof Error ? err.message : String(err),\n })\n }\n finish()\n }\n return rec\n }\n","/**\n * Reading answers aloud: the text an answer is read as (`speakableText`), and two engines behind\n * one shape (`SpeakText`) - the browser's own `speechSynthesis` (on the device, free, offline\n * where the voice is local) and any engine that makes audio (`createAudioSpeaker`: a provider's\n * text-to-speech model, played from a `blob:` URL). No React; `useReadAloud` and the message\n * list's Listen button are built on it.\n */\n\n/** Where a reading is: making its audio, playing, paused. */\nexport type ReadAloudState = 'loading' | 'playing' | 'paused'\n\n/** A reading under way. */\nexport interface SpeechPlayback {\n pause(): void\n resume(): void\n /** End it now; `done` then resolves. */\n stop(): void\n /** Resolves when the reading ends - read to the end, or stopped; rejects when it failed. */\n readonly done: Promise<void>\n}\n\n/** Start reading a text. `onState` hears every change of state until `done` settles. */\nexport type SpeakText = (\n text: string,\n options: { lang?: string; onState: (state: ReadAloudState) => void },\n) => SpeechPlayback\n\n/**\n * A reading that failed in the engine itself (the browser's voice, the audio element) - a code,\n * not words for the person: the Listen button says its own label. An error a host's\n * `synthesize` throws is shown with its message.\n */\nexport class SpeechOutputError extends Error {\n readonly code: string\n constructor(code: string) {\n super(code)\n this.name = 'SpeechOutputError'\n this.code = code\n }\n}\n\nconst asOutputError = (err: unknown): SpeechOutputError =>\n err instanceof SpeechOutputError\n ? err\n : new SpeechOutputError(\n err && typeof err === 'object' && 'name' in err ? String(err.name) : 'playback-failed',\n )\n\n// ── the text that is read ───────────────────────────────────────────────────\n\nexport interface SpeakableOptions {\n /** Said in place of a code block (default: nothing - the block is skipped). */\n code?: string\n}\n\n/**\n * An answer's Markdown as the words to say: no markers (`#`, `*`, `_`, backticks, `>`, list\n * bullets, table rules), a link as its text, a picture as its alt text, a bare URL as its host, a\n * code block NOT read symbol by symbol (left out, or said as `options.code`), inline code as its\n * text, a table's cells one after another. Blocks end in a stop so the voice pauses between them.\n */\nexport const speakableText = (markdown: string, options: SpeakableOptions = {}): string => {\n const out: string[] = []\n const lines = markdown.replace(/\\r\\n?/g, '\\n').split('\\n')\n let fence: string | undefined\n let fenceSaid = false\n for (const raw of lines) {\n const line = raw.trimEnd()\n const opener = /^\\s*(`{3,}|~{3,})/.exec(line)\n if (fence !== undefined) {\n if (opener && opener[1][0] === fence[0] && opener[1].length >= fence.length) fence = undefined\n continue\n }\n if (opener) {\n fence = opener[1]\n if (options.code && !fenceSaid) out.push(options.code)\n fenceSaid = true\n continue\n }\n fenceSaid = false\n // A table's rule line, a thematic break: nothing to say.\n if (/^\\s*\\|?\\s*:?-{2,}:?\\s*(\\|\\s*:?-{2,}:?\\s*)*\\|?\\s*$/.test(line)) continue\n if (/^\\s*([-*_])\\s*(\\1\\s*){2,}$/.test(line)) continue\n let text = line\n .replace(/^\\s{0,3}#{1,6}\\s+/, '')\n .replace(/^\\s*>\\s?/, '')\n .replace(/^\\s*(?:[-*+]|\\d+[.)])\\s+(\\[[ xX]\\]\\s+)?/, '')\n // A table row: its cells, one after another.\n if (/^\\s*\\|.*\\|\\s*$/.test(text))\n text = text\n .replace(/^\\s*\\||\\|\\s*$/g, '')\n .split('|')\n .map((c) => c.trim())\n .filter(Boolean)\n .join(', ')\n text = text\n .replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/<(https?:\\/\\/[^>\\s]+)>/g, (_m, url: string) => hostOf(url))\n .replace(/\\bhttps?:\\/\\/[^\\s)]+/g, (url) => hostOf(url))\n .replace(/`+([^`]*)`+/g, '$1')\n .replace(/(\\*\\*|__)(.+?)\\1/g, '$2')\n .replace(/(^|[^\\w*])[*_]([^*_\\s][^*_]*?)[*_](?=[^\\w*]|$)/g, '$1$2')\n .replace(/~~(.+?)~~/g, '$1')\n .replace(/<\\/?[a-z][^>]*>/gi, '')\n .replace(/[*_#`~>|]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n if (!text) continue\n out.push(/[.!?…:;。!?]$/.test(text) ? text : `${text}.`)\n }\n return out.join(' ').trim()\n}\n\nconst hostOf = (url: string): string => {\n try {\n return new URL(url).hostname.replace(/^www\\./, '')\n } catch {\n return ''\n }\n}\n\n/**\n * A text in pieces of at most `max` characters, cut after a sentence where one ends in time,\n * else after a word: engines read long text badly in one go (Chrome's voices stop after some\n * seconds; a provider takes a few thousand characters per call).\n */\nexport const splitForSpeech = (text: string, max = 220): string[] => {\n const pieces: string[] = []\n let rest = text.trim()\n while (rest.length > max) {\n const window = rest.slice(0, max + 1)\n let cut = -1\n for (const m of window.matchAll(/[.!?…。!?;:](\\s|$)/g))\n if (m.index !== undefined && m.index + 1 <= max) cut = m.index + 1\n if (cut < max / 3) cut = window.lastIndexOf(' ')\n if (cut <= 0) cut = max\n pieces.push(rest.slice(0, cut).trim())\n rest = rest.slice(cut).trim()\n }\n if (rest) pieces.push(rest)\n return pieces\n}\n\n// ── the language of a text ──────────────────────────────────────────────────\n\n/** A writing system, as far as a voice needs to know: the letters it can read. */\nexport type SpeechScript =\n | 'latin'\n | 'cyrillic'\n | 'greek'\n | 'arabic'\n | 'hebrew'\n | 'han'\n | 'kana'\n | 'hangul'\n | 'devanagari'\n | 'thai'\n | 'georgian'\n | 'armenian'\n\nconst SCRIPT_RANGES: readonly (readonly [SpeechScript, RegExp])[] = [\n ['latin', /\\p{Script=Latin}/u],\n ['cyrillic', /\\p{Script=Cyrillic}/u],\n ['greek', /\\p{Script=Greek}/u],\n ['arabic', /\\p{Script=Arabic}/u],\n ['hebrew', /\\p{Script=Hebrew}/u],\n ['kana', /[\\p{Script=Hiragana}\\p{Script=Katakana}]/u],\n ['han', /\\p{Script=Han}/u],\n ['hangul', /\\p{Script=Hangul}/u],\n ['devanagari', /\\p{Script=Devanagari}/u],\n ['thai', /\\p{Script=Thai}/u],\n ['georgian', /\\p{Script=Georgian}/u],\n ['armenian', /\\p{Script=Armenian}/u],\n]\n\n/** The languages (BCP-47 base) written in a script other than Latin; any other is Latin. */\nconst LANGUAGE_SCRIPT: Readonly<Record<string, SpeechScript>> = {\n ru: 'cyrillic',\n uk: 'cyrillic',\n be: 'cyrillic',\n bg: 'cyrillic',\n sr: 'cyrillic',\n mk: 'cyrillic',\n kk: 'cyrillic',\n ky: 'cyrillic',\n tg: 'cyrillic',\n mn: 'cyrillic',\n el: 'greek',\n ar: 'arabic',\n fa: 'arabic',\n ur: 'arabic',\n he: 'hebrew',\n yi: 'hebrew',\n zh: 'han',\n ja: 'kana',\n ko: 'hangul',\n hi: 'devanagari',\n mr: 'devanagari',\n ne: 'devanagari',\n th: 'thai',\n ka: 'georgian',\n hy: 'armenian',\n}\n\n/** The language a script is read in when none of the person's languages is written in it. */\nconst SCRIPT_DEFAULT: Readonly<Record<SpeechScript, string>> = {\n latin: 'en',\n cyrillic: 'ru',\n greek: 'el',\n arabic: 'ar',\n hebrew: 'he',\n han: 'zh',\n kana: 'ja',\n hangul: 'ko',\n devanagari: 'hi',\n thai: 'th',\n georgian: 'ka',\n armenian: 'hy',\n}\n\n/** The script a language (BCP-47) is written in: `sr-Latn` is Latin, `zh-*` Han, `ja` kana. */\nexport const scriptOfLanguage = (lang: string): SpeechScript => {\n const parts = lang.toLowerCase().replace(/_/g, '-').split('-')\n if (parts.includes('latn')) return 'latin'\n if (parts.includes('cyrl')) return 'cyrillic'\n return LANGUAGE_SCRIPT[parts[0]] ?? 'latin'\n}\n\n/**\n * The script most of a text's letters are written in (digits, signs and spaces do not count);\n * a text with any kana is Japanese (it is mostly Han letters too). Undefined: no letters.\n */\nexport const scriptOfText = (text: string): SpeechScript | undefined => {\n const counts = new Map<SpeechScript, number>()\n for (const ch of text) {\n if (!/\\p{L}/u.test(ch)) continue\n const found = SCRIPT_RANGES.find(([, re]) => re.test(ch))\n if (!found) continue\n counts.set(found[0], (counts.get(found[0]) ?? 0) + 1)\n }\n if (counts.has('kana')) {\n counts.set('kana', (counts.get('kana') ?? 0) + (counts.get('han') ?? 0))\n counts.delete('han')\n }\n let best: SpeechScript | undefined\n let most = 0\n for (const [script, n] of counts)\n if (n > most) {\n best = script\n most = n\n }\n return best\n}\n\n/**\n * The language to read a text in: the first of `preferred` (the UI's language, then the\n * browser's, `navigator.languages`) written in the text's script - so a Russian answer in an\n * English interface is read in Russian, not spelled by an English voice -, else the script's\n * usual language. A text without letters: the first preferred. Which of the languages of ONE\n * script (English or French) cannot be told from the letters: the person's order decides.\n */\nexport const languageOfText = (\n text: string,\n preferred: readonly (string | undefined)[] = [],\n): string | undefined => {\n const mine = preferred.filter((l): l is string => Boolean(l))\n const script = scriptOfText(text)\n if (!script) return mine[0]\n return mine.find((l) => scriptOfLanguage(l) === script) ?? SCRIPT_DEFAULT[script]\n}\n\n// ── the browser's voices ────────────────────────────────────────────────────\n\n/** The slice of a `SpeechSynthesisVoice` used here. */\nexport interface SpeechVoiceLike {\n voiceURI: string\n name: string\n lang: string\n localService?: boolean\n default?: boolean\n}\n\n/**\n * The voice to read a language with: the person's (by `voiceURI`) while the browser has it and it\n * reads that language's script; else\n * one of exactly that language (`pt-BR`), then of its base (`pt`) - a voice on the device before a\n * network one, the browser's default of the language first. Undefined: none for the language (the\n * browser then reads with its own default).\n */\nexport const voiceFor = <V extends SpeechVoiceLike>(\n voices: readonly V[],\n lang: string | undefined,\n preferred?: string,\n): V | undefined => {\n if (preferred) {\n // The person's voice - for a text it can read: a voice of another script spells it.\n const chosen = voices.find((v) => v.voiceURI === preferred)\n if (chosen && (!lang || scriptOfLanguage(chosen.lang) === scriptOfLanguage(lang))) return chosen\n }\n if (!lang) return undefined\n const norm = (l: string) => l.toLowerCase().replace(/_/g, '-')\n const want = norm(lang)\n const base = want.split('-')[0]\n const rank = (v: V) => [v.localService ? 1 : 0, v.default ? 1 : 0]\n const best = (list: V[]) =>\n [...list].sort((a, b) => {\n const ra = rank(a)\n const rb = rank(b)\n return rb[0] - ra[0] || rb[1] - ra[1] || a.name.localeCompare(b.name)\n })[0]\n const exact = voices.filter((v) => norm(v.lang) === want)\n if (exact.length) return best(exact)\n const same = voices.filter((v) => norm(v.lang).split('-')[0] === base)\n return same.length ? best(same) : undefined\n}\n\n/** The voices of a language (`voiceFor`'s matching), for a picker. */\nexport const voicesOf = <V extends SpeechVoiceLike>(\n voices: readonly V[],\n lang: string | undefined,\n): V[] => {\n if (!lang) return [...voices]\n const base = lang.toLowerCase().split(/[-_]/)[0]\n return voices.filter((v) => v.lang.toLowerCase().split(/[-_]/)[0] === base)\n}\n\n/** The slice of `speechSynthesis` this module drives. */\nexport interface SpeechSynthesisLike {\n speak(utterance: SpeechUtteranceLike): void\n cancel(): void\n pause(): void\n resume(): void\n getVoices(): SpeechVoiceLike[]\n readonly speaking?: boolean\n}\n\nexport interface SpeechUtteranceLike {\n text: string\n lang: string\n voice: SpeechVoiceLike | null\n rate: number\n onstart: (() => void) | null\n onend: (() => void) | null\n onerror: ((event: { error?: string }) => void) | null\n}\n\n/** Whether the browser can read aloud (it has `speechSynthesis`). */\nexport const speechSynthesisSupported = (): boolean =>\n typeof globalThis !== 'undefined' &&\n 'speechSynthesis' in globalThis &&\n typeof (globalThis as { SpeechSynthesisUtterance?: unknown }).SpeechSynthesisUtterance ===\n 'function'\n\nexport interface BrowserSpeakerOptions {\n /** The person's voice (`voiceURI`); else one of the text's language (`voiceFor`). */\n voice?: string\n /** 0.1-10, default 1. */\n rate?: number\n /** Default: the page's `speechSynthesis` and `SpeechSynthesisUtterance` (tests hand in their own). */\n synth?: SpeechSynthesisLike\n createUtterance?: (text: string) => SpeechUtteranceLike\n}\n\n/**\n * Read with the browser's `speechSynthesis`: on the device (a local voice works offline), free.\n * The text goes in pieces (`splitForSpeech`); one reading at a time in the whole page - starting\n * one cancels any other.\n */\nexport const createBrowserSpeaker =\n (options: BrowserSpeakerOptions = {}): SpeakText =>\n (text, { lang, onState }) => {\n const synth =\n options.synth ??\n (globalThis as unknown as { speechSynthesis: SpeechSynthesisLike }).speechSynthesis\n const make =\n options.createUtterance ??\n ((t: string) =>\n new (\n globalThis as unknown as {\n SpeechSynthesisUtterance: new (t: string) => SpeechUtteranceLike\n }\n ).SpeechSynthesisUtterance(t))\n const voice = voiceFor(synth.getVoices(), lang, options.voice)\n let settle!: () => void\n let fail!: (err: Error) => void\n const done = new Promise<void>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n done.catch(() => {})\n let over = false\n const end = (err?: Error) => {\n if (over) return\n over = true\n if (err) fail(err)\n else settle()\n }\n const pieces = splitForSpeech(text)\n synth.cancel()\n if (pieces.length === 0) {\n end()\n return { pause() {}, resume() {}, stop() {}, done }\n }\n let started = false\n pieces.forEach((piece, i) => {\n const u = make(piece)\n u.lang = voice?.lang ?? lang ?? ''\n try {\n u.voice = voice ?? null\n } catch {\n // Not one of this browser's voice objects: the language picks one.\n }\n u.rate = options.rate ?? 1\n u.onstart = () => {\n if (!started && !over) onState('playing')\n started = true\n }\n u.onend = () => {\n if (i === pieces.length - 1) end()\n }\n u.onerror = (event) => {\n // `interrupted` / `canceled`: this reading was stopped (by us, or by another one).\n if (event.error === 'interrupted' || event.error === 'canceled') end()\n else end(new SpeechOutputError(event.error || 'synthesis-failed'))\n }\n synth.speak(u)\n })\n onState('loading')\n return {\n pause: () => {\n if (over) return\n synth.pause()\n onState('paused')\n },\n resume: () => {\n if (over) return\n synth.resume()\n onState('playing')\n },\n stop: () => {\n if (over) return\n synth.cancel()\n end()\n },\n done,\n }\n }\n\n// ── an engine that makes audio ───────────────────────────────────────────────\n\n/** Make the audio of a text: the host's call to a text-to-speech model. */\nexport type SynthesizeSpeech = (\n text: string,\n context: { lang?: string; signal: AbortSignal },\n) => Promise<Blob>\n\n/** The slice of an `HTMLAudioElement` this module drives. */\nexport interface AudioLike {\n src: string\n paused: boolean\n play(): Promise<void>\n pause(): void\n onended: (() => void) | null\n onerror: (() => void) | null\n}\n\nexport interface AudioSpeakerOptions {\n synthesize: SynthesizeSpeech\n /** Characters per call (default 2000): a long answer is several calls, the next made while one plays. */\n maxChars?: number\n /** Default: `new Audio()`. */\n createAudio?: () => AudioLike\n /** Default: `URL.createObjectURL` / `URL.revokeObjectURL`. */\n objectUrl?: { create: (blob: Blob) => string; revoke: (url: string) => void }\n /**\n * Play a moment of silence on the element at once, inside the person's tap (default true): iOS\n * Safari plays an element later - after the audio was made - only if it was played inside the\n * gesture. Call `speak` from the click handler for it to count.\n */\n unlock?: boolean\n}\n\n/** A WAV of a few samples of silence: what unlocks an audio element inside a tap. */\nconst silence = (): Blob => {\n const samples = 16\n const view = new DataView(new ArrayBuffer(44 + samples * 2))\n const text = (at: number, s: string) => {\n for (let i = 0; i < s.length; i++) view.setUint8(at + i, s.charCodeAt(i))\n }\n text(0, 'RIFF')\n view.setUint32(4, 36 + samples * 2, true)\n text(8, 'WAVEfmt ')\n view.setUint32(16, 16, true)\n view.setUint16(20, 1, true)\n view.setUint16(22, 1, true)\n view.setUint32(24, 8000, true)\n view.setUint32(28, 16000, true)\n view.setUint16(32, 2, true)\n view.setUint16(34, 16, true)\n text(36, 'data')\n view.setUint32(40, samples * 2, true)\n return new Blob([view.buffer], { type: 'audio/wav' })\n}\n\n/**\n * Read with an engine that makes audio - a provider's text-to-speech model: each piece of the text\n * (`maxChars`) is made by `synthesize` and played from a `blob:` URL, revoked when it has played\n * or the reading stops. Stopping aborts a call in flight (`signal`). Nothing is stored.\n */\nexport const createAudioSpeaker =\n (options: AudioSpeakerOptions): SpeakText =>\n (text, { lang, onState }) => {\n const urls = options.objectUrl ?? {\n create: (b: Blob) => URL.createObjectURL(b),\n revoke: (u: string) => URL.revokeObjectURL(u),\n }\n const audio = options.createAudio?.() ?? (new Audio() as unknown as AudioLike)\n const controller = new AbortController()\n const pieces = splitForSpeech(text, options.maxChars ?? 2000)\n let settle!: () => void\n let fail!: (err: Error) => void\n const done = new Promise<void>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n done.catch(() => {})\n let over = false\n let paused = false\n let current: string | undefined\n const made = new Map<number, Promise<Blob>>()\n const make = (i: number) => {\n if (!made.has(i)) {\n const p = options.synthesize(pieces[i], { lang, signal: controller.signal })\n p.catch(() => {})\n made.set(i, p)\n }\n return made.get(i)!\n }\n const release = () => {\n if (current) urls.revoke(current)\n current = undefined\n }\n const end = (err?: Error) => {\n if (over) return\n over = true\n controller.abort()\n audio.pause()\n audio.onended = null\n audio.onerror = null\n release()\n if (err) fail(err)\n else settle()\n }\n const playFrom = async (i: number) => {\n if (over) return\n if (i >= pieces.length) return end()\n onState(i === 0 || !current ? 'loading' : 'playing')\n let blob: Blob\n try {\n blob = await make(i)\n } catch (err) {\n return end(err instanceof Error ? err : new Error(String(err)))\n }\n if (over) return\n // The next piece is made while this one plays.\n if (i + 1 < pieces.length) make(i + 1)\n release()\n current = urls.create(blob)\n audio.src = current\n audio.onended = () => void playFrom(i + 1)\n audio.onerror = () => end(new SpeechOutputError('playback-failed'))\n if (paused) return onState('paused')\n try {\n await audio.play()\n if (!over) onState('playing')\n } catch (err) {\n end(asOutputError(err))\n }\n }\n if (pieces.length === 0) end()\n else {\n if (options.unlock !== false) {\n // Inside the tap: a moment of silence, so that the element may play once the audio is made.\n current = urls.create(silence())\n audio.src = current\n audio.play().catch(() => {})\n }\n void playFrom(0)\n }\n return {\n pause: () => {\n if (over) return\n paused = true\n audio.pause()\n onState('paused')\n },\n resume: () => {\n if (over || !paused) return\n paused = false\n if (current)\n audio.play().then(\n () => !over && onState('playing'),\n (err) => end(asOutputError(err)),\n )\n else onState('loading')\n },\n stop: () => end(),\n done,\n }\n }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,IAAM,aAAa,CAACA,UAA6D;AACtF,QAAM,IAAI,gCAAgC,KAAKA,MAAK,UAAU,CAAC;AAC/D,SAAO,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,YAAY,GAAG,OAAO,EAAE,CAAC,KAAK,IAAI,KAAK,EAAE,IAAI;AACvE;AAkBO,IAAM,cAAc,CAAC,UAMT;AACjB,MAAI,CAAC,MAAM,KAAM,QAAO;AACxB,MAAI,CAAC,MAAM,SAAU,QAAO;AAC5B,MAAI,CAAC,MAAM,OAAO,CAAC,MAAM,eAAgB,QAAO;AAChD,MAAI,WAAW,MAAM,GAAG,EAAG,QAAO;AAClC,SAAO,MAAM,iBAAiB,gBAAgB;AAChD;AAsCO,IAAM,iBAAiB,CAAC,UAAmE;AAChG,MAAI,CAAC,MAAM,WAAY,QAAO;AAC9B,MAAI,MAAM,SAAU,QAAO;AAC3B,MAAI,MAAM,MAAO,QAAO;AACxB,MAAI,MAAM,WAAW,eAAgB,QAAO;AAC5C,SAAO;AACT;AAGO,IAAM,iBAAiB,CAC5B,UAEA,MAAM,WAAW,aAAa,MAAM,WAAW,UAAU,WAAW;AAc/D,IAAM,kBAAkB,CAAC,UAA0C;AACxE,MAAI,MAAM,SAAU,QAAO;AAC3B,MAAI,MAAM,MAAO,QAAO;AACxB,MAAI,MAAM,WAAW,kBAAkB,MAAM,WAAW,UAAW,QAAO;A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