@dudko.dev/agent-web-react 0.0.20 → 0.0.22

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-agent.ts","../src/state.ts","../src/util.ts","../src/hooks/use-chat-history.ts","../src/chat-history.ts","../src/hooks/use-virtual-files.ts","../src/hooks/use-speech-to-text.ts","../src/hooks/use-credentials.ts","../src/hooks/use-webllm-model.ts","../src/hooks/use-local-model.ts","../src/labels.tsx","../src/composer.ts","../src/image-resize.ts","../src/context.tsx","../src/components/AgentChat.tsx","../src/components/AgentComposer.tsx","../src/components/icons.tsx","../src/components/ChatHistoryList.tsx","../src/components/format.ts","../src/components/ContextMeter.tsx","../src/components/FilesPanel.tsx","../src/components/StepList.tsx","../src/components/MessageList.tsx","../src/components/ModelLoadBar.tsx","../src/components/ToolApprovalPrompt.tsx","../src/components/UsageBadge.tsx","../src/components/Composer.tsx","../src/components/PlanView.tsx","../src/components/ApprovalModeSwitch.tsx","../src/components/ApiKeyForm.tsx","../src/index.ts"],"sourcesContent":["import { useCallback, useEffect, useReducer, useRef, useState } from 'react'\nimport type { DependencyList } from 'react'\nimport {\n createAgent,\n createRunControl,\n type IUsage,\n type Agent,\n type AgentEventHandler,\n type BrowserAgentConfig,\n type CompactResult,\n type RunControl,\n type RunFile,\n type RunResult,\n type ToolApprovalDecision,\n type ToolApprovalMode,\n type ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\nimport { agentStateReducer, createInitialAgentState } from '../state.js'\nimport type { AgentUiState, ApprovalView, ChatAttachment, ChatMessage } from '../types.js'\nimport { errMessage } from '../util.js'\n\nexport interface UseAgentOptions {\n /**\n * Rebuild the agent when any of these values change — compared like a\n * `useEffect` dependency array (so it must keep a stable length across\n * renders). Default: build once on mount. Bump this when you switch\n * model/provider so a fresh agent is constructed with the new config.\n *\n * Keep dynamic config (`tools`, `describeState`) referentially stable across\n * renders (e.g. via `useRef`/`useCallback`) so it survives without a rebuild.\n */\n deps?: DependencyList\n /** Invoked for every raw agent event, after the internal reducer folds it. */\n onEvent?: AgentEventHandler\n /** Build the agent immediately on mount (default `true`). */\n autoStart?: boolean\n /** Cap the retained raw event log length (default 200; 0 = unbounded). */\n maxEvents?: number\n /**\n * Route tool-consent requests into the hook (`pendingApprovals`, `approve`,\n * `deny`) when the config has no `toolApproval.onRequest` of its own\n * (default true). Render them with `<ToolApprovalPrompt>`, or your own UI.\n */\n approvals?: boolean\n /**\n * What the run never showed the agent — a message sent while the answer was being\n * written — is sent as the next message, once the run has ended (default true).\n * A run the user stopped never does this: those messages stay in `undelivered`\n * for the UI to offer (`sendUndelivered` / `discardUndelivered`).\n */\n followUp?: boolean\n}\n\nexport interface ApproveOptions {\n /** Also allow this tool for the rest of the agent's life (\"always allow\"). */\n remember?: boolean\n}\n\nexport interface RunGoalOptions {\n /**\n * What the transcript shows for this turn when it differs from what the\n * agent receives — e.g. the typed text without the attached files' contents.\n */\n label?: string\n /** Images sent to the model with the goal (vision models; see `agent.capabilities`). */\n images?: RunFile[]\n /** PDFs / files / URLs sent to the model with the goal. */\n files?: RunFile[]\n /** What the transcript shows as attached to this turn (thumbnails, chips). */\n attachments?: ChatAttachment[]\n}\n\nexport interface UseAgentReturn extends AgentUiState {\n /** Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. */\n run: (goal: string, options?: RunGoalOptions) => Promise<RunResult | undefined>\n /** Abort the in-flight run (observed between phases and mid-stream). */\n stop: () => void\n /**\n * Say something to the agent while it works. It is shown to the model at the next\n * boundary (between tool calls, or when the step ends — where the replanner then\n * re-checks the plan), never cutting a tool call short. `false` when no run is in\n * flight or the text is empty — then use `run`. Watch `queued` / `notes`.\n */\n send: (text: string) => boolean\n /** Stop ONE running subagent (`SubagentView.id`); the run and its siblings go on. */\n stopSubagent: (id: string) => boolean\n /** Send the `undelivered` messages (a stopped run's leftovers) as a new message. */\n sendUndelivered: () => void\n /** Drop the `undelivered` messages. */\n discardUndelivered: () => void\n /** Clear the whole conversation — transcript, current run, and the agent's memory. */\n reset: () => void\n /** Rebuild the agent now (e.g. after the user stores a new API key). */\n reload: () => void\n /** The built agent, once ready. */\n agent: Agent | undefined\n isRunning: boolean\n isReady: boolean\n /** Tool calls waiting for the user's consent. */\n pendingApprovals: ApprovalView[]\n /** Let a pending call run (`remember` → never ask for this tool again). */\n approve: (id: string, options?: ApproveOptions) => void\n /** Refuse a pending call; the model is told and works around it. */\n deny: (id: string, reason?: string) => void\n /** The consent policy in effect. */\n approvalMode: ToolApprovalMode\n /** Switch the consent policy live — the \"autopilot\" toggle. */\n setApprovalMode: (mode: ToolApprovalMode) => void\n /** Summarise the stored transcript now (needs `config.memory`). */\n compact: () => Promise<CompactResult | undefined>\n /** The memory session runs use (config.sessionId until switched). */\n sessionId: string\n /**\n * Switch to another conversation: its id becomes the memory session of the\n * next runs, and its saved transcript (chat history) is shown.\n */\n loadChat: (chat: { sessionId: string; messages?: ChatMessage[]; totalUsage?: IUsage }) => void\n}\n\n/**\n * The primary React binding for `@dudko.dev/agent-web`. Builds the agent from a\n * {@link BrowserAgentConfig}, streams its typed events into a renderable\n * {@link AgentUiState} (plan, steps, tool calls, thoughts, consent requests,\n * subagents, streamed final answer, token usage, model-load progress and a chat\n * transcript), and exposes `run` / `stop` / `reset` / `reload` plus consent\n * (`approve` / `deny` / `setApprovalMode`) and `compact`.\n *\n * ```tsx\n * const agent = useAgent({\n * model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },\n * credentials,\n * tools,\n * toolApproval: { mode: 'ask-writes' }, // requests land in agent.pendingApprovals\n * })\n * // <button disabled={!agent.isReady} onClick={() => agent.run(text)}>Run</button>\n * ```\n */\nexport const useAgent = (\n config: BrowserAgentConfig,\n options: UseAgentOptions = {},\n): UseAgentReturn => {\n const [state, dispatch] = useReducer(agentStateReducer, undefined, createInitialAgentState)\n const agentRef = useRef<Agent | undefined>(undefined)\n const abortRef = useRef<AbortController | undefined>(undefined)\n // The in-flight run's control: how `send` and `stopSubagent` reach it.\n const controlRef = useRef<RunControl | undefined>(undefined)\n const stateRef = useRef(state)\n stateRef.current = state\n const [generation, setGeneration] = useState(0)\n\n // Keep the latest callbacks/config without forcing an agent rebuild.\n const configRef = useRef(config)\n configRef.current = config\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n // Consent requests waiting for approve()/deny(), by request id.\n const resolversRef = useRef(new Map<string, (d: ToolApprovalDecision) => void>())\n const settleAll = useCallback((decision: ToolApprovalDecision) => {\n for (const resolve of resolversRef.current.values()) resolve(decision)\n resolversRef.current.clear()\n }, [])\n const uiOnRequest = useCallback(\n (req: ToolApprovalRequest) =>\n new Promise<ToolApprovalDecision>((resolve) => {\n resolversRef.current.set(req.id, resolve)\n }),\n [],\n )\n\n // The memory session runs go to; a chat-history switch changes it.\n const [sessionId, setSessionId] = useState(config.sessionId ?? 'default')\n const sessionRef = useRef(sessionId)\n sessionRef.current = sessionId\n\n const configMode = config.toolApproval?.mode ?? 'autopilot'\n const [approvalMode, setApprovalModeState] = useState<ToolApprovalMode>(configMode)\n const modeRef = useRef<ToolApprovalMode>(configMode)\n\n const setApprovalMode = useCallback((mode: ToolApprovalMode) => {\n modeRef.current = mode\n agentRef.current?.setToolApprovalMode(mode)\n setApprovalModeState(mode)\n }, [])\n\n // The config's mode is the source of truth when IT changes; applied live.\n useEffect(() => {\n if (configMode !== modeRef.current) setApprovalMode(configMode)\n }, [configMode, setApprovalMode])\n\n const reload = useCallback(() => setGeneration((g) => g + 1), [])\n\n // The build's own status. A rebuild while a run is in flight (a setting\n // changed mid-run) must not flip the UI out of 'running': the run keeps the\n // agent it started with, and the new one takes the next run.\n type BuildStatus = { status: 'idle' | 'initializing' | 'ready' | 'error'; error?: string }\n const buildStatusRef = useRef<BuildStatus>({ status: 'idle' })\n const setBuildStatus = useCallback((next: BuildStatus) => {\n buildStatusRef.current = next\n if (!abortRef.current) dispatch({ type: 'status', ...next })\n }, [])\n\n // Build (and rebuild) the agent. Model resolution is async (dynamic provider\n // imports, vault key fetch, WebLLM weight download), so this lives in effect.\n const { autoStart, deps } = options\n useEffect(() => {\n // Any dep change invalidates the current agent first.\n agentRef.current = undefined\n const cfg = configRef.current\n // Skip building until we're asked to (autoStart / reload) and actually have\n // a model — a local WebGPU model may still be downloading (config.model\n // undefined), in which case we sit idle rather than build a broken agent.\n const shouldBuild = (autoStart !== false || generation > 0) && Boolean(cfg.model)\n if (!shouldBuild) {\n setBuildStatus({ status: 'idle' })\n return\n }\n // Consent requests come to the hook unless the host handles them itself.\n const routeApprovals = optionsRef.current.approvals !== false && !cfg.toolApproval?.onRequest\n const built: BrowserAgentConfig = routeApprovals\n ? {\n ...cfg,\n toolApproval: { ...cfg.toolApproval, mode: modeRef.current, onRequest: uiOnRequest },\n }\n : cfg\n let cancelled = false\n setBuildStatus({ status: 'initializing' })\n createAgent(built)\n .then((agent) => {\n if (cancelled) return\n agent.setToolApprovalMode(modeRef.current)\n agentRef.current = agent\n setBuildStatus({ status: 'ready' })\n })\n .catch((err) => {\n if (cancelled) return\n setBuildStatus({ status: 'error', error: errMessage(err) })\n })\n return () => {\n cancelled = true\n }\n // `config` is intentionally excluded: rebuilds are driven only by `deps` /\n // reload(), so a new config object every render doesn't churn the agent.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [generation, autoStart, ...(deps ?? [])])\n\n // Abort any in-flight run (and release waiting consent requests) on unmount.\n useEffect(\n () => () => {\n abortRef.current?.abort()\n settleAll({ approved: false, reason: 'the view was closed' })\n },\n [settleAll],\n )\n\n // `run` calls itself (the follow-up of a run), so it is reached through a ref.\n const runRef = useRef<\n ((goal: string, runOptions?: RunGoalOptions) => Promise<RunResult | undefined>) | undefined\n >(undefined)\n\n const run = useCallback(\n async (goal: string, runOptions?: RunGoalOptions): Promise<RunResult | undefined> => {\n const agent = agentRef.current\n if (!agent || abortRef.current) return undefined // not ready, or already running\n const controller = new AbortController()\n abortRef.current = controller\n const control = createRunControl()\n controlRef.current = control\n // What the run never showed the agent; read once it is over.\n let left: string[] = []\n dispatch({ type: 'status', status: 'running' })\n try {\n const result = await agent.run(goal, {\n signal: controller.signal,\n control,\n sessionId: sessionRef.current,\n ...(runOptions?.images?.length ? { images: runOptions.images } : {}),\n ...(runOptions?.files?.length ? { files: runOptions.files } : {}),\n onEvent: (event) => {\n const start = event.type === 'run.start'\n const shown = start && runOptions?.label ? { ...event, goal: runOptions.label } : event\n dispatch({\n type: 'event',\n event: shown,\n maxEvents: optionsRef.current.maxEvents,\n at: Date.now(),\n ...(start && runOptions?.attachments?.length\n ? { attachments: runOptions.attachments }\n : {}),\n })\n try {\n optionsRef.current.onEvent?.(event)\n } catch {\n /* a bad host handler must not break the run */\n }\n },\n })\n left = result.undelivered ?? []\n return result\n } catch (err) {\n left = control.pending()\n dispatch({\n type: 'event',\n event: { type: 'error', phase: 'run', error: errMessage(err) },\n maxEvents: optionsRef.current.maxEvents,\n })\n return undefined\n } finally {\n abortRef.current = undefined\n controlRef.current = undefined\n settleAll({ approved: false, reason: 'the run ended' })\n // Whatever the agent did meanwhile: rebuilt, still building, or gone.\n dispatch({ type: 'status', ...buildStatusRef.current })\n if (left.length > 0) {\n if (!controller.signal.aborted && optionsRef.current.followUp !== false) {\n // Said too late for this run: just send it next.\n dispatch({ type: 'undelivered', texts: [] })\n void runRef.current?.(left.join('\\n\\n'))\n } else {\n dispatch({ type: 'undelivered', texts: left })\n }\n } else {\n dispatch({ type: 'undelivered', texts: [] })\n }\n }\n },\n [settleAll],\n )\n runRef.current = run\n\n const send = useCallback((text: string): boolean => controlRef.current?.send(text) ?? false, [])\n const stopSubagent = useCallback(\n (id: string): boolean => controlRef.current?.stopSubagent(id) ?? false,\n [],\n )\n const sendUndelivered = useCallback(() => {\n const texts = stateRef.current.undelivered\n if (texts.length === 0) return\n dispatch({ type: 'undelivered', texts: [] })\n void runRef.current?.(texts.join('\\n\\n'))\n }, [])\n const discardUndelivered = useCallback(() => dispatch({ type: 'undelivered', texts: [] }), [])\n\n const stop = useCallback(() => {\n abortRef.current?.abort()\n settleAll({ approved: false, reason: 'stopped by the user' })\n }, [settleAll])\n\n const reset = useCallback(() => {\n dispatch({ type: 'reset' })\n // \"New conversation\" means the agent forgets it too, not just the view.\n void configRef.current.memory?.clear(sessionRef.current).catch(() => {})\n }, [])\n\n const loadChat = useCallback(\n (chat: { sessionId: string; messages?: ChatMessage[]; totalUsage?: IUsage }) => {\n abortRef.current?.abort()\n sessionRef.current = chat.sessionId\n setSessionId(chat.sessionId)\n dispatch({ type: 'load', messages: chat.messages ?? [], totalUsage: chat.totalUsage })\n },\n [],\n )\n\n const approve = useCallback((id: string, opts?: ApproveOptions) => {\n const resolve = resolversRef.current.get(id)\n if (!resolve) return\n resolversRef.current.delete(id)\n resolve({ approved: true, remember: opts?.remember })\n }, [])\n\n const deny = useCallback((id: string, reason?: string) => {\n const resolve = resolversRef.current.get(id)\n if (!resolve) return\n resolversRef.current.delete(id)\n resolve({ approved: false, reason })\n }, [])\n\n const compact = useCallback(async (): Promise<CompactResult | undefined> => {\n const agent = agentRef.current\n if (!agent) return undefined\n const result = await agent.compact({ sessionId: sessionRef.current })\n if (result.compacted) {\n dispatch({\n type: 'event',\n event: {\n type: 'context.compacted',\n scope: 'history',\n beforeTokens: result.beforeTokens,\n afterTokens: result.afterTokens,\n },\n maxEvents: optionsRef.current.maxEvents,\n at: Date.now(),\n })\n }\n return result\n }, [])\n\n return {\n ...state,\n run,\n stop,\n send,\n stopSubagent,\n sendUndelivered,\n discardUndelivered,\n reset,\n reload,\n agent: agentRef.current,\n isRunning: state.status === 'running',\n isReady: state.status === 'ready',\n pendingApprovals: state.approvals.filter((a) => a.status === 'pending'),\n approve,\n deny,\n approvalMode,\n setApprovalMode,\n compact,\n sessionId,\n loadChat,\n }\n}\n","import type { AgentEvent, IUsage } from '@dudko.dev/agent-web'\nimport type {\n AgentUiState,\n ApprovalView,\n ChatAttachment,\n ChatMessage,\n StepView,\n SubagentView,\n ToolCallView,\n} from './types.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 }\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[] }\n\ninterface EventContext {\n at?: number\n attachments?: ChatAttachment[]\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\nconst addUsage = (a: IUsage, b: IUsage): 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\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 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. */\nconst resetRun = (state: AgentUiState): AgentUiState => ({\n ...createInitialAgentState(),\n status: state.status,\n messages: state.messages,\n totalUsage: state.totalUsage,\n seq: state.seq,\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\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 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 }\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/** 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\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.\n const base = resetRun(state)\n const userId = `msg-${base.seq}`\n const assistantId = `msg-${base.seq + 1}`\n return {\n ...base,\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.attachments?.length ? { attachments: ctx.attachments } : {}),\n },\n { id: assistantId, role: 'assistant', content: '', pending: true },\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 }\n return { ...state, steps: [...state.steps, view] }\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 steps: patchStep(state.steps, event.step.id, (s) => ({ ...s, text: s.text + event.delta })),\n }\n\n case 'step.tool-call': {\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 }\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 ...(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 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 }\n })\n })(),\n })),\n }\n\n case 'replan.decision':\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n },\n }\n\n case 'message.queued':\n return state.queued.some((q) => q.id === event.id)\n ? state\n : { ...state, queued: [...state.queued, { id: event.id, text: event.text }] }\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 { id: event.id, text: event.text, at: event.at, ...(anchor ? { stepId: anchor } : {}) },\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 return {\n ...state,\n usage: addUsage(state.usage, event.usage),\n totalUsage: addUsage(state.totalUsage, event.usage),\n }\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 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 ...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 return {\n ...state,\n subagents: [\n ...state.subagents,\n {\n id: event.id,\n name: event.name,\n task: event.task,\n status: 'running',\n ...(event.profile ? { profile: event.profile } : {}),\n stepId: runningStepId(state.steps),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n },\n ],\n }\n\n case 'subagent.event':\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) =>\n applySubagentEvent(s, event.event),\n ),\n }\n\n case 'subagent.complete':\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({\n ...s,\n status: 'done',\n activity: 'done',\n text: event.text,\n usage: event.usage,\n })),\n }\n\n case 'subagent.error':\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({\n ...s,\n status: event.stopped ? 'stopped' : 'error',\n activity: event.stopped ? 'stopped' : 'failed',\n error: event.error,\n })),\n }\n\n case 'skill.activated':\n return state.skills.includes(event.name)\n ? state\n : { ...state, skills: [...state.skills, event.name] }\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 'stopped':\n return {\n ...state,\n stopped: true,\n // Nothing is waiting any more once the run has stopped.\n approvals: state.approvals.map((a) =>\n a.status === 'pending' ? { ...a, status: 'denied' as const, reason: 'stopped' } : a,\n ),\n messages: finalizeAssistant(\n state.messages,\n state.finalText || 'Stopped.',\n runDuration(state, ctx.at),\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 return event.phase === 'run'\n ? {\n ...state,\n error: event.error,\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 const decided = state.approvals.filter((a) => a.status !== 'pending')\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 (\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\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 { ...createInitialAgentState(), status: state.status, seq: state.seq }\n case 'status':\n return {\n ...state,\n status: action.status,\n error: action.status === 'error' ? action.error : undefined,\n }\n case 'event': {\n const next = syncRunMessage(\n applyEvent(state, action.event, { at: action.at, attachments: action.attachments }),\n )\n const cap = action.maxEvents ?? 200\n const events =\n cap > 0 ? [...state.events, action.event].slice(-cap) : [...state.events, action.event]\n return { ...next, events }\n }\n case 'undelivered':\n return { ...state, queued: [], undelivered: action.texts }\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 }\n }\n default:\n return state\n }\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","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n ChatHistoryStore,\n chatTitle,\n newChatId,\n type ChatRecord,\n type ChatSummary,\n} from '../chat-history.js'\nimport type { UseAgentReturn } from './use-agent.js'\n\nexport interface UseChatHistoryOptions {\n /** Where chats are saved (default: a ChatHistoryStore on IndexedDB). */\n store?: ChatHistoryStore\n /** Switch the hook off (keeps hook order stable in components). Default true. */\n enabled?: boolean\n /** Open the most recent chat on mount (default true). */\n resumeLatest?: boolean\n}\n\nexport interface UseChatHistoryReturn {\n chats: ChatSummary[]\n /** The open conversation (the agent's memory session). */\n currentId: string\n loading: boolean\n /** Open a saved conversation. */\n select: (id: string) => Promise<void>\n /** Start an empty conversation. */\n newChat: () => void\n /** Delete a conversation (and start a new one if it was open). */\n remove: (id: string) => Promise<void>\n}\n\n/**\n * Persist an agent's conversations — the transcript with its tool calls, usage\n * and image attachments — and switch between them. Each chat id is also the\n * agent's memory session, so with a persistent `memory` (IndexedDBStore) a\n * reopened chat continues with the model's context intact.\n */\nexport const useChatHistory = (\n agent: UseAgentReturn,\n options: UseChatHistoryOptions = {},\n): UseChatHistoryReturn => {\n const enabled = options.enabled !== false\n const store = useMemo(() => options.store ?? new ChatHistoryStore(), [options.store])\n const [chats, setChats] = useState<ChatSummary[]>([])\n const [loading, setLoading] = useState(enabled)\n const createdRef = useRef(new Map<string, number>())\n const agentRef = useRef(agent)\n agentRef.current = agent\n\n const refresh = useCallback(async () => {\n try {\n setChats(await store.list())\n } catch {\n /* storage unavailable: history simply stays empty */\n }\n }, [store])\n\n const newChat = useCallback(() => {\n agentRef.current.loadChat({ sessionId: newChatId(), messages: [] })\n }, [])\n\n const select = useCallback(\n async (id: string) => {\n const record = await store.get(id).catch(() => undefined)\n if (!record) return\n createdRef.current.set(id, record.createdAt)\n agentRef.current.loadChat({\n sessionId: record.id,\n messages: record.messages,\n totalUsage: record.totalUsage,\n })\n },\n [store],\n )\n\n const remove = useCallback(\n async (id: string) => {\n await store.delete(id).catch(() => {})\n if (id === agentRef.current.sessionId) newChat()\n await refresh()\n },\n [store, newChat, refresh],\n )\n\n // On mount: open the latest chat, or start a fresh one.\n useEffect(() => {\n if (!enabled) return\n let active = true\n void (async () => {\n const list = await store.list().catch(() => [] as ChatSummary[])\n if (!active) return\n setChats(list)\n if (options.resumeLatest !== false && list[0]) await select(list[0].id)\n else newChat()\n setLoading(false)\n })()\n return () => {\n active = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [enabled, store])\n\n // Save the open chat whenever its transcript settles (not on every streamed token).\n const { messages, totalUsage, sessionId, isRunning } = agent\n useEffect(() => {\n if (!enabled || loading || isRunning || messages.length === 0) return\n const now = Date.now()\n const createdAt = createdRef.current.get(sessionId) ?? now\n createdRef.current.set(sessionId, createdAt)\n const record: ChatRecord = {\n id: sessionId,\n title: chatTitle(messages),\n createdAt,\n updatedAt: now,\n messages,\n totalUsage,\n }\n void store\n .put(record)\n .then(refresh)\n .catch(() => {})\n }, [enabled, loading, isRunning, messages, totalUsage, sessionId, store, refresh])\n\n return { chats, currentId: sessionId, loading, select, newChat, remove }\n}\n","import type { IUsage } from '@dudko.dev/agent-web'\nimport type { 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/** IndexedDB-backed chat history (raw IndexedDB — no extra dependency). */\nexport class ChatHistoryStore {\n private readonly dbName: 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.dbName = opts.dbName ?? 'agent-web-react'\n this.storeName = opts.storeName ?? 'chats'\n if (opts.memory || typeof indexedDB === 'undefined') this.memory = new Map()\n }\n\n private open(): Promise<IDBDatabase> {\n this.db ??= new Promise<IDBDatabase>((resolve, reject) => {\n const r = indexedDB.open(this.dbName, 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 = () => resolve(r.result)\n r.onerror = () => reject(r.error)\n }).catch((err: unknown) => {\n this.db = undefined\n throw err\n })\n return this.db\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 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 req((await this.tx('readwrite')).put(record))\n }\n\n async delete(id: string): Promise<void> {\n if (this.memory) {\n this.memory.delete(id)\n return\n }\n await req((await this.tx('readwrite')).delete(id))\n }\n\n async clear(): Promise<void> {\n if (this.memory) {\n this.memory.clear()\n return\n }\n await req((await this.tx('readwrite')).clear())\n }\n}\n\n/** A chat's title: its first user message, trimmed. */\nexport const chatTitle = (messages: ChatMessage[]): string => {\n const first = messages\n .find((m) => m.role === 'user')\n ?.content.replace(/\\s+/g, ' ')\n .trim()\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","import { useCallback, useEffect, useState } from 'react'\nimport type { VirtualFileInfo, VirtualFileSystem } from '@dudko.dev/agent-web'\n\nexport interface UseVirtualFilesReturn {\n files: VirtualFileInfo[]\n loading: boolean\n error?: string\n refresh: () => Promise<void>\n /** Save a browser File (text as text, anything else as base64). */\n upload: (file: File, dir?: string) => Promise<void>\n remove: (path: string) => Promise<void>\n /** A data URL of a file (for previews and downloads). */\n dataUrl: (path: string) => Promise<string | undefined>\n /** A text file's content. */\n text: (path: string) => Promise<string | undefined>\n}\n\nconst readDataUrl = (file: Blob): Promise<string> =>\n new Promise((resolve, reject) => {\n const r = new FileReader()\n r.onload = () => resolve(String(r.result))\n r.onerror = () => reject(r.error ?? new Error('could not read the file'))\n r.readAsDataURL(file)\n })\n\n/**\n * A live listing of a {@link VirtualFileSystem} (the core's browser\n * workspace): re-reads on every write / delete — by the user or by the agent's\n * `fs_*` tools — and offers upload / remove / read helpers. Headless: render\n * it with `<FilesPanel>` or your own UI.\n */\nexport const useVirtualFiles = (\n vfs: VirtualFileSystem | undefined,\n prefix = '/',\n): UseVirtualFilesReturn => {\n const [files, setFiles] = useState<VirtualFileInfo[]>([])\n const [loading, setLoading] = useState(Boolean(vfs))\n const [error, setError] = useState<string | undefined>()\n\n const refresh = useCallback(async () => {\n if (!vfs) return\n try {\n setFiles(await vfs.list(prefix))\n setError(undefined)\n } catch (err) {\n setError(err instanceof Error ? err.message : String(err))\n } finally {\n setLoading(false)\n }\n }, [vfs, prefix])\n\n useEffect(() => {\n if (!vfs) return\n void refresh()\n return vfs.onChange(() => void refresh())\n }, [vfs, refresh])\n\n const upload = useCallback(\n async (file: File, dir = '/uploads') => {\n if (!vfs) return\n const path = `${dir.replace(/\\/$/, '')}/${file.name.replace(/[^\\w.-]+/g, '_') || 'file'}`\n const type = file.type || 'application/octet-stream'\n if (type.startsWith('text/') || /json|xml|yaml|markdown|csv/.test(type)) {\n await vfs.write(path, await file.text(), { mimeType: type })\n } else {\n await vfs.writeDataUrl(path, await readDataUrl(file))\n }\n },\n [vfs],\n )\n\n const remove = useCallback(\n async (path: string) => {\n await vfs?.delete(path)\n },\n [vfs],\n )\n\n const dataUrl = useCallback(async (path: string) => vfs?.readDataUrl(path), [vfs])\n const text = useCallback(\n async (path: string) => {\n const f = await vfs?.read(path)\n return f && f.encoding === 'utf8' ? f.content : undefined\n },\n [vfs],\n )\n\n return { files, loading, error, refresh, upload, remove, dataUrl, text }\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\n\n/** The slice of the Web Speech API recognizer this hook 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 onerror: ((ev: { error?: string }) => void) | null\n onend: (() => void) | null\n}\n\ninterface SpeechResultEventLike {\n resultIndex: number\n results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>\n}\n\nexport interface UseSpeechToTextOptions {\n /** BCP-47 language (default: the page's `navigator.language`). */\n lang?: string\n /** Keep listening across pauses until stopped (default true). */\n continuous?: boolean\n /**\n * Build your own recognizer (e.g. a fully local Whisper/WebGPU one) instead\n * of the browser's `SpeechRecognition`.\n */\n createRecognizer?: () => SpeechRecognizerLike\n /** Final text chunks, as they are recognized. */\n onFinal?: (text: string) => void\n}\n\nexport interface UseSpeechToTextReturn {\n /** The browser (or your `createRecognizer`) can do speech-to-text. */\n supported: boolean\n listening: boolean\n /** Words heard but not final yet (for a live preview). */\n interim: string\n error?: string\n start: () => void\n stop: () => void\n toggle: () => void\n}\n\nconst browserRecognizer = (): (() => SpeechRecognizerLike) | undefined => {\n const g = globalThis as unknown as {\n SpeechRecognition?: new () => SpeechRecognizerLike\n webkitSpeechRecognition?: new () => SpeechRecognizerLike\n }\n const Ctor = g.SpeechRecognition ?? g.webkitSpeechRecognition\n return Ctor ? () => new Ctor() : undefined\n}\n\n/**\n * Speech-to-text in the browser via the Web Speech API (`SpeechRecognition`,\n * prefixed in Chrome/Safari). Note that Chrome sends the audio to its own\n * recognition service; pass `createRecognizer` for an on-device engine.\n */\nexport const useSpeechToText = (options: UseSpeechToTextOptions = {}): UseSpeechToTextReturn => {\n const optionsRef = useRef(options)\n optionsRef.current = options\n const factory = options.createRecognizer ?? browserRecognizer()\n const [listening, setListening] = useState(false)\n const [interim, setInterim] = useState('')\n const [error, setError] = useState<string | undefined>()\n const recRef = useRef<SpeechRecognizerLike | undefined>(undefined)\n\n const stop = useCallback(() => {\n recRef.current?.stop()\n }, [])\n\n const start = useCallback(() => {\n if (!factory || recRef.current) return\n const rec = factory()\n rec.lang =\n optionsRef.current.lang ??\n (typeof navigator !== 'undefined' ? navigator.language : undefined) ??\n 'en-US'\n rec.continuous = optionsRef.current.continuous !== false\n rec.interimResults = true\n rec.onresult = (ev) => {\n let pending = ''\n for (let i = ev.resultIndex; i < ev.results.length; i += 1) {\n const r = ev.results[i]\n if (r.isFinal) optionsRef.current.onFinal?.(r[0].transcript.trim())\n else pending += r[0].transcript\n }\n setInterim(pending)\n }\n rec.onerror = (ev) => {\n // \"no-speech\" / \"aborted\" are routine; anything else is worth showing.\n if (ev.error && ev.error !== 'no-speech' && ev.error !== 'aborted') setError(ev.error)\n }\n rec.onend = () => {\n recRef.current = undefined\n setListening(false)\n setInterim('')\n }\n recRef.current = rec\n setError(undefined)\n try {\n rec.start()\n setListening(true)\n } catch (err) {\n recRef.current = undefined\n setError(err instanceof Error ? err.message : String(err))\n }\n }, [factory])\n\n useEffect(() => () => recRef.current?.abort?.(), [])\n\n return {\n supported: Boolean(factory),\n listening,\n interim,\n error,\n start,\n stop,\n toggle: () => (recRef.current ? stop() : start()),\n }\n}\n","import { useCallback, useMemo, useState } from 'react'\nimport { VaultCredentialStore, type CredentialStore } from '@dudko.dev/agent-web'\n\nexport interface UseCredentialsReturn {\n /** The underlying store — pass this straight to `createAgent({ credentials })`. */\n store: CredentialStore\n /** Store (encrypted at rest) an API key under a ref id. */\n setKey: (ref: string, key: string) => Promise<void>\n /** Remove a stored key. */\n removeKey: (ref: string) => Promise<void>\n /** Resolve whether a key is currently present for a ref. */\n hasKey: (ref: string) => Promise<boolean>\n /**\n * Bumped whenever a key is written or removed — depend on it in an effect to\n * re-query `hasKey` and reflect the change in your UI.\n */\n version: number\n}\n\n/**\n * Manage BYOK API keys in the agent's encrypted vault (WebCrypto AES-GCM key in\n * IndexedDB). Defaults to a fresh {@link VaultCredentialStore}; pass your own\n * {@link CredentialStore} (e.g. a short-lived-token fetcher) to override.\n *\n * ```tsx\n * const creds = useCredentials()\n * // await creds.setKey('openai', userInput)\n * // <AgentProvider config={{ model, credentials: creds.store }}>…\n * ```\n */\nexport const useCredentials = (store?: CredentialStore): UseCredentialsReturn => {\n const resolved = useMemo<CredentialStore>(() => store ?? new VaultCredentialStore(), [store])\n const [version, setVersion] = useState(0)\n\n const setKey = useCallback(\n async (ref: string, key: string) => {\n await resolved.setApiKey(ref, key)\n setVersion((v) => v + 1)\n },\n [resolved],\n )\n\n const removeKey = useCallback(\n async (ref: string) => {\n await resolved.deleteApiKey(ref)\n setVersion((v) => v + 1)\n },\n [resolved],\n )\n\n const hasKey = useCallback(\n async (ref: string) => (await resolved.getApiKey(ref)) !== undefined,\n [resolved],\n )\n\n return { store: resolved, setKey, removeKey, hasKey, version }\n}\n","import {\n createWebLLMModel,\n isWebGPUAvailable,\n preloadWebLLMModel,\n unloadWebLLMModel,\n webLLMContextWindow,\n type WebLLMModelOptions,\n} from '@dudko.dev/agent-web'\nimport {\n useLocalModel,\n type LocalModelEngine,\n type UseLocalModelReturn,\n} from './use-local-model.js'\n\n/** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */\ntype WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>\n\n/**\n * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's\n * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.\n */\nexport type WebLLMModelFactory = (\n modelId: string,\n options?: WebLLMModelOptions,\n) => Promise<WebLLMModel>\n\nexport interface UseWebLLMModelOptions extends WebLLMModelOptions {\n /**\n * Override how the model is built. **Bundled browser apps (Vite, Next, …)\n * usually need this**: the core builds WebLLM via `await import('@browser-ai/\n * web-llm')`, and a bundler frequently stubs that dynamic import to an empty\n * module — the failure surfaces as `webLLM is not a function`. Pass a factory\n * that imports `webLLM` statically so the bundler includes it:\n *\n * ```ts\n * import { webLLM } from '@browser-ai/web-llm'\n * const create = (id, opts) => Promise.resolve(webLLM(id, opts))\n * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })\n * ```\n *\n * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.\n */\n create?: WebLLMModelFactory\n}\n\n/** What {@link useWebLLMModel} returns — {@link UseLocalModelReturn} for a WebLLM model. */\nexport type UseWebLLMModelReturn = UseLocalModelReturn<WebLLMModel>\n\n/**\n * Load a local WebGPU model with WebLLM and track its download progress —\n * {@link useLocalModel} with the WebLLM engine. Nothing downloads until you\n * call `load()` (models are large), so you can gate it behind a user action.\n * `load()` eagerly initializes the engine (via the core's\n * `preloadWebLLMModel`), so `ready` means \"ready to chat\" and progress fills\n * during the load rather than silently on the first message.\n *\n * Everything it reports is about the **current** `modelId`: switch the id and\n * `model` / `ready` / `progress` / `error` describe the new one (not loaded\n * yet), while the previous model stays in memory — switching back is instant.\n * Loading the new id frees the previous one first, so two models never hold\n * GPU memory at once; `unload()` frees it on demand.\n *\n * WebLLM loads its models with a 4096-token window; pass `contextWindowTokens`\n * to load with more (Qwen3, Llama 3.x take far more — it costs KV-cache VRAM,\n * not a new download). A different window is a different load.\n *\n * ```tsx\n * import { webLLM } from '@browser-ai/web-llm' // your app's optional peer\n * const create = (id: string, opts?: WebLLMModelOptions) => Promise.resolve(webLLM(id, opts))\n * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })\n * // <button disabled={!local.supported || local.loading} onClick={local.load}>Load</button>\n * // {local.loading && <ModelLoadBar load={{ progress: local.progress, text: local.text }} />}\n * // local.ready && <AgentProvider config={{ model: local.model! }}>…\n * ```\n */\nexport const useWebLLMModel = (\n modelId: string,\n options?: UseWebLLMModelOptions,\n): UseWebLLMModelReturn =>\n useLocalModel(modelId, createWebLLMEngine(options), {\n contextWindowTokens: options?.contextWindowTokens,\n })\n\n/**\n * The WebLLM {@link LocalModelEngine}: what {@link useWebLLMModel} runs, for\n * hosts that switch between local runtimes with one {@link useLocalModel}\n * (pass the window to that hook's `contextWindowTokens`).\n */\nexport const createWebLLMEngine = (\n options?: UseWebLLMModelOptions,\n): LocalModelEngine<WebLLMModel> => {\n // The window comes per load (useLocalModel's option), not from here.\n const {\n create = createWebLLMModel,\n contextWindowTokens: _perLoad,\n ...modelOptions\n } = options ?? {}\n return {\n create: (id, ctx) =>\n create(id, {\n ...modelOptions,\n ...(ctx.contextWindowTokens ? { contextWindowTokens: ctx.contextWindowTokens } : {}),\n // Drive preload in warmUp (below) so download progress is reported the\n // same way whether `create` is the core's `createWebLLMModel` or an\n // injected factory (e.g. a statically-imported `webLLM`, needed under\n // bundlers).\n preload: false,\n initProgressCallback: (report) => {\n ctx.onProgress({ progress: report.progress, text: report.text })\n modelOptions.initProgressCallback?.(report)\n },\n }),\n // Download the weights + init the engine now via the core's helper (a\n // 1-token warm-up). WebLLM builds are otherwise lazy — the ~GB download\n // would only start on the first `run()`, long after we told the UI the\n // model is \"ready\". Fast + idempotent once the weights are cached.\n warmUp: (model) => preloadWebLLMModel(model),\n unload: unloadWebLLMModel,\n supported: isWebGPUAvailable,\n unsupportedMessage: 'WebGPU is not available in this browser.',\n contextWindowOf: webLLMContextWindow,\n }\n}\n","import { useCallback, useRef, useState } from 'react'\nimport type { createWebLLMModel } from '@dudko.dev/agent-web'\nimport { errMessage } from '../util.js'\n\n/** An AI SDK `LanguageModel` (the type, via the core — no `ai` import here). */\ntype LanguageModel = Awaited<ReturnType<typeof createWebLLMModel>>\n\n/** Download / initialisation progress of a local model. */\nexport interface LocalModelProgress {\n /** 0..1. */\n progress: number\n /** Human-readable status from the runtime. */\n text: string\n}\n\n/** What `create` and `warmUp` are given. */\nexport interface LocalModelLoadContext {\n /** Report progress; the hook shows it for the load in flight only. */\n onProgress: (report: LocalModelProgress) => void\n /** The window to load the model with, when the host asked for one. */\n contextWindowTokens?: number\n}\n\n/**\n * How to run one kind of on-device model — WebLLM, the browser's built-in\n * model (`@browser-ai/core`), transformers.js (`@browser-ai/transformers-js`),\n * or your own. Only `create` is required.\n */\nexport interface LocalModelEngine<M extends LanguageModel = LanguageModel> {\n /** Build the model (cheap: the download starts in `warmUp`). */\n create: (modelId: string, ctx: LocalModelLoadContext) => Promise<M>\n /**\n * Download the weights and initialise now, so `ready` means \"ready to chat\"\n * and the progress shows during the load (default: nothing — the runtime\n * then loads on the first message).\n */\n warmUp?: (model: M, ctx: LocalModelLoadContext) => Promise<void>\n /** Free the model's memory (default: nothing). */\n unload?: (model: M) => Promise<void>\n /** Whether this browser can run it at all (default true). */\n supported?: () => boolean\n /** The error a load reports when `supported()` is false. */\n unsupportedMessage?: string\n /** The model's context window once loaded, when the runtime says. */\n contextWindowOf?: (model: M) => number | undefined\n}\n\nexport interface UseLocalModelOptions {\n /**\n * The window to load the model with (WebLLM loads with 4096 unless told\n * otherwise). A different window is a different load.\n */\n contextWindowTokens?: number\n}\n\nexport interface UseLocalModelReturn<M extends LanguageModel = LanguageModel> {\n /**\n * The built model, once **this** `modelId` is loaded — pass to\n * `createAgent({ model })`. Undefined right after the id changes, until the\n * new one is loaded.\n */\n model: M | undefined\n /**\n * Download and initialize the current `modelId`. Resolves with the model\n * already loaded for it, if any. Loading another id first frees the previous\n * model's memory (one model per hook); call again after an error to retry.\n */\n load: () => Promise<M | undefined>\n /** Free the loaded model's memory (and drop a load in flight). */\n unload: () => Promise<void>\n /** The id of the model held in memory, whichever id is current. */\n loadedModelId: string | undefined\n /** True while the current `modelId` is downloading / initializing. */\n loading: boolean\n /** Load progress of the current `modelId`, 0..1. */\n progress: number\n /** Human-readable progress text from the runtime. */\n text: string\n /** Why the current `modelId` failed to load. */\n error: string | undefined\n /** Whether this browser can run the engine. */\n supported: boolean\n /** True once the current `modelId` is ready. */\n ready: boolean\n /** The loaded model's context window, in tokens, when the runtime says. */\n contextWindow: number | undefined\n}\n\ninterface Loaded<M> {\n id: string\n /** The id and the window it was loaded with: another window is another load. */\n key: string\n model: M\n /** Frees it with the engine that built it (the engine may change since). */\n free: () => Promise<void>\n}\n\nconst keyOf = (id: string, tokens: number | undefined) => (tokens ? `${id}@${tokens}` : id)\n\n/**\n * Load an on-device model and track its download — for any local runtime,\n * described by an {@link LocalModelEngine}. Nothing downloads until you call\n * `load()` (models are large), so you can gate it behind a user action.\n *\n * Everything it reports is about the **current** `modelId`: switch the id and\n * `model` / `ready` / `progress` / `error` describe the new one (not loaded\n * yet), while the previous model stays in memory — switching back is instant.\n * Loading the new id frees the previous one first, so two models never hold\n * memory at once; `unload()` frees it on demand. A load superseded by another\n * frees its model; a second `load()` of the same id shares the download.\n *\n * ```tsx\n * import { browserAI, doesBrowserSupportBrowserAI } from '@browser-ai/core'\n * const nano: LocalModelEngine = {\n * create: async () => browserAI('text', { expectedInputs: [{ type: 'image' }] }),\n * warmUp: async (m, { onProgress }) => {\n * await m.createSessionWithProgress((p) => onProgress({ progress: p, text: 'Downloading' }))\n * },\n * supported: doesBrowserSupportBrowserAI,\n * contextWindowOf: (m) => m.getContextWindow(),\n * }\n * const local = useLocalModel('gemini-nano', nano)\n * ```\n *\n * {@link useWebLLMModel} is this hook with the WebLLM engine.\n */\nexport const useLocalModel = <M extends LanguageModel = LanguageModel>(\n modelId: string,\n engine: LocalModelEngine<M>,\n options?: UseLocalModelOptions,\n): UseLocalModelReturn<M> => {\n const [loaded, setLoaded] = useState<Loaded<M> | undefined>(undefined)\n const [pending, setPending] = useState<{ key: string; progress: number; text: string }>()\n const [failure, setFailure] = useState<{ key: string; message: string }>()\n // The engine is read at load time: a new object every render is fine.\n const engineRef = useRef(engine)\n engineRef.current = engine\n // The source of truth for async code (state lags a render behind).\n const loadedRef = useRef<Loaded<M> | undefined>(undefined)\n const inflightRef = useRef<{ key: string; promise: Promise<M | undefined> } | undefined>(\n undefined,\n )\n const windowTokens = options?.contextWindowTokens\n const key = keyOf(modelId, windowTokens)\n // Bumped by every load()/unload(): an older load that finishes late is stale.\n const seqRef = useRef(0)\n\n const setHeld = (next: Loaded<M> | undefined) => {\n loadedRef.current = next\n setLoaded(next)\n }\n const freeWith = (eng: LocalModelEngine<M>, model: M) => async () => {\n try {\n await eng.unload?.(model)\n } catch {\n /* best-effort */\n }\n }\n\n const load = useCallback((): Promise<M | undefined> => {\n const id = modelId\n if (loadedRef.current?.key === key) return Promise.resolve(loadedRef.current.model)\n if (inflightRef.current?.key === key) return inflightRef.current.promise\n const eng = engineRef.current\n if (eng.supported && !eng.supported()) {\n setFailure({\n key,\n message: eng.unsupportedMessage ?? 'This browser cannot run this model.',\n })\n return Promise.resolve(undefined)\n }\n const seq = ++seqRef.current\n const current = () => seq === seqRef.current\n const ctx: LocalModelLoadContext = {\n onProgress: (report) => {\n if (current()) setPending({ key, progress: report.progress, text: report.text })\n },\n ...(windowTokens ? { contextWindowTokens: windowTokens } : {}),\n }\n const promise = (async (): Promise<M | undefined> => {\n setPending({ key, progress: 0, text: '' })\n setFailure(undefined)\n let built: M | undefined\n try {\n // One model per hook: free the previous one before the next download.\n const previous = loadedRef.current\n if (previous) {\n setHeld(undefined)\n await previous.free()\n }\n built = await eng.create(id, ctx)\n await eng.warmUp?.(built, ctx)\n if (!current()) {\n // Superseded by another load() or an unload(): don't leak its memory.\n await freeWith(eng, built)()\n return undefined\n }\n setHeld({ id, key, model: built, free: freeWith(eng, built) })\n return built\n } catch (err) {\n if (built) await freeWith(eng, built)()\n if (current()) setFailure({ key, message: errMessage(err) })\n return undefined\n } finally {\n if (current()) {\n inflightRef.current = undefined\n setPending(undefined)\n }\n }\n })()\n inflightRef.current = { key, promise }\n return promise\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [modelId, key])\n\n const unload = useCallback(async (): Promise<void> => {\n seqRef.current++ // a load in flight becomes stale and frees itself\n inflightRef.current = undefined\n setPending(undefined)\n const previous = loadedRef.current\n setHeld(undefined)\n if (previous) await previous.free()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const model = loaded?.key === key ? loaded.model : undefined\n const progressing = pending?.key === key ? pending : undefined\n return {\n model,\n load,\n unload,\n loadedModelId: loaded?.id,\n loading: progressing !== undefined,\n progress: progressing?.progress ?? 0,\n text: progressing?.text ?? '',\n error: failure?.key === key ? failure.message : undefined,\n supported: engine.supported ? engine.supported() : true,\n ready: model !== undefined,\n contextWindow: model ? engine.contextWindowOf?.(model) : undefined,\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { ToolApprovalMode } from '@dudko.dev/agent-web'\nimport { defaultNoticeTexts, type NoticeTexts } from './composer.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 answerThoughts: string\n stepThoughts: string\n usageTitle: string\n attachments: string\n planned: string\n replanned: (mode: string, reason: string) => 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 microphone: 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 attachmentsOnly: string\n seeAttachments: string\n tooLarge: (name: string, mb: number) => string\n binaryText: (name: 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 /** 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 // ── steps / tool calls ─────────────────────────────────────────────────────\n failed: string\n toolCostTitle: string\n}\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`\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 answerThoughts: 'Thinking about the answer',\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 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 microphone: 'Microphone',\n model: 'Model',\n thinking: 'Thinking',\n toolConsent: 'Tool consent',\n modes: {\n autopilot: { label: 'Auto', hint: 'Autopilot — run every tool without asking' },\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 binaryText: (name) => `${name} looks binary — it can't be attached as text.`,\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 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 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\n/** Overrides: any label, with the nested groups merged key by key. */\nexport type AgentLabelsOverride = Partial<\n Omit<\n AgentLabels,\n 'status' | 'modes' | 'commandGroups' | 'commandDescriptions' | 'thinkingLevels' | 'notices'\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}\n\nconst NESTED = [\n 'status',\n 'modes',\n 'commandGroups',\n 'commandDescriptions',\n 'thinkingLevels',\n 'noteAt',\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\nconst LabelsContext = createContext<AgentLabels>(defaultLabels)\n\nexport interface AgentLabelsProviderProps {\n labels: AgentLabelsOverride\n children?: ReactNode\n}\n\n/** Override labels for every component below (nests: inner providers win). */\nexport const AgentLabelsProvider = ({ labels, children }: AgentLabelsProviderProps) => {\n const parent = useContext(LabelsContext)\n const value = useMemo(() => mergeLabels(parent, labels), [parent, labels])\n return <LabelsContext.Provider value={value}>{children}</LabelsContext.Provider>\n}\n\n/** The labels in effect: the provider's, with a component's own `labels` prop on top. */\nexport const useLabels = (over?: AgentLabelsOverride): AgentLabels => {\n const ctx = useContext(LabelsContext)\n return useMemo(() => mergeLabels(ctx, over), [ctx, over])\n}\n","import 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}\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/**\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.\n */\nexport const withAttachments = (text: string, files: ComposerAttachment[]): string => {\n const texts = files.filter((f) => f.kind === 'text' && f.text !== undefined)\n if (texts.length === 0) return text\n const blocks = texts.map((f) => {\n const body = f.text as string\n const fence = body.includes('```') ? '~~~' : '```'\n const where = f.path ? ` (also saved as ${f.path})` : ''\n return `### ${f.name}${where}\\n${fence}\\n${body}\\n${fence}`\n })\n return `${text}\\n\\nAttached file(s):\\n${blocks.join('\\n\\n')}`\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/** 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 * 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/** 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","import { createContext, useContext } from 'react'\nimport type { ReactNode } from 'react'\nimport type { BrowserAgentConfig } from '@dudko.dev/agent-web'\nimport { useAgent, type UseAgentOptions, type UseAgentReturn } from './hooks/use-agent.js'\n\nconst AgentContext = createContext<UseAgentReturn | null>(null)\n\nexport interface AgentProviderProps extends UseAgentOptions {\n /** The agent configuration (see `@dudko.dev/agent-web`). */\n config: BrowserAgentConfig\n children: ReactNode\n}\n\n/**\n * Build one agent with {@link useAgent} and share it with the subtree, so a\n * chat panel, a plan view and a usage badge can all read the same live run.\n *\n * ```tsx\n * <AgentProvider config={{ model, tools, credentials }}>\n * <AgentChat />\n * </AgentProvider>\n * ```\n */\nexport const AgentProvider = ({ config, children, ...options }: AgentProviderProps) => {\n const agent = useAgent(config, options)\n return <AgentContext.Provider value={agent}>{children}</AgentContext.Provider>\n}\n\n/** Read the shared agent. Throws if used outside an {@link AgentProvider}. */\nexport const useAgentContext = (): UseAgentReturn => {\n const ctx = useContext(AgentContext)\n if (!ctx) throw new Error('useAgentContext must be used within an <AgentProvider>')\n return ctx\n}\n\n/** Non-throwing variant: returns `null` when outside a provider. */\nexport const useOptionalAgentContext = (): UseAgentReturn | null => useContext(AgentContext)\n","import { useEffect, useRef, useState } from 'react'\nimport type { ComponentType, CSSProperties, ReactNode } from 'react'\nimport type { VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { ChatHistoryStore } from '../chat-history.js'\nimport { useOptionalAgentContext } from '../context.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { useChatHistory, type UseChatHistoryReturn } from '../hooks/use-chat-history.js'\nimport { AgentLabelsProvider, useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { AgentComposer, type AgentComposerProps } from './AgentComposer.js'\nimport { ChatHistoryList, type ChatHistoryListProps } from './ChatHistoryList.js'\nimport { ContextMeter } from './ContextMeter.js'\nimport { FilesPanel, type FilesPanelProps } from './FilesPanel.js'\nimport { AlertIcon, FileIcon, HistoryIcon } from './icons.js'\nimport { MessageList, type MessageListProps } from './MessageList.js'\nimport { ModelLoadBar } from './ModelLoadBar.js'\nimport type { RenderToolCall } from './StepList.js'\nimport { ToolApprovalPrompt, type ToolApprovalPromptProps } from './ToolApprovalPrompt.js'\nimport { UsageBadge } from './UsageBadge.js'\n\n/** Places to put your own content in the panel. */\nexport interface AgentChatSlots {\n /** Replaces the whole header; `false` hides it. */\n header?: ReactNode | false\n /** In the header, before the title. */\n headerStart?: ReactNode\n /** In the header, after the usage badge. */\n headerEnd?: ReactNode\n /** In the body, above / below the transcript. */\n beforeMessages?: ReactNode\n afterMessages?: ReactNode\n /** Above the composer. */\n footerStart?: ReactNode\n /** Under the chat list in the history sidebar. */\n sidebar?: ReactNode\n}\n\n/** Swap any built-in part for your own component (same props). */\nexport interface AgentChatComponents {\n Composer?: ComponentType<AgentComposerProps>\n MessageList?: ComponentType<MessageListProps>\n HistoryList?: ComponentType<ChatHistoryListProps>\n FilesPanel?: ComponentType<FilesPanelProps>\n ApprovalPrompt?: ComponentType<ToolApprovalPromptProps>\n}\n\n/** Extra class names per part (added to the built-in `awr-` ones). */\nexport interface AgentChatClassNames {\n root?: string\n main?: string\n header?: string\n body?: string\n footer?: string\n sidebar?: string\n files?: string\n}\n\nexport interface AgentChatProps {\n /**\n * An explicit controller from {@link useAgent}. If omitted, the component\n * reads the shared controller from an enclosing `<AgentProvider>`.\n */\n controller?: UseAgentReturn\n title?: ReactNode\n /** Content shown before the first message. */\n emptyState?: ReactNode\n /** @deprecated use `composer={{ placeholder }}` */\n placeholder?: string\n\n // ── what is shown ──────────────────────────────────────────────────────────\n /** Each answer's steps, thoughts, subagents, consent decisions (default true). */\n showActivity?: boolean\n /** Each tool call inside the activity (default true). */\n showToolCalls?: boolean\n /** Tokens per answer and per tool call (default true). */\n showUsage?: boolean\n /** Thoughts, when the model thinks (default true). */\n showThoughts?: boolean\n /** What you said while the agent worked, under the step it reached (default true). */\n showNotes?: boolean\n /** A stop button on each running subagent (default true). */\n stoppableSubagents?: boolean\n /** Conversation total in the header (default true). */\n showTotalUsage?: boolean\n /** Status dot in the header (default true). */\n showStatus?: boolean\n /** Consent-mode chip in the composer — \"⚡ Auto\" (default true). */\n showApprovalMode?: boolean\n /**\n * Context meter (tokens by kind, budget bar, Compact) above the composer\n * (default false). A number draws the bar against that budget.\n */\n showContext?: boolean | number\n /** Keep finished answers' activity expanded (default false). */\n activityOpen?: boolean\n\n // ── features ───────────────────────────────────────────────────────────────\n /**\n * Saved conversations in IndexedDB with a sidebar to switch between them:\n * `true` (default store), your own `ChatHistoryStore`, or the result of your\n * own `useChatHistory()` (e.g. to render the list elsewhere).\n */\n history?: boolean | ChatHistoryStore | UseChatHistoryReturn\n /**\n * Sidebar open at first (default: on a wide panel yes; on a narrow one —\n * under `narrowWidth` — it starts closed and opens over the chat).\n */\n defaultHistoryOpen?: boolean\n /**\n * The workspace: attachments are saved here, and a Files panel shows it\n * (add `createFileTools(files)` to the agent's tools so it can use it too).\n */\n files?: VirtualFileSystem\n /** Files panel open at first (default false). */\n defaultFilesOpen?: boolean\n /** Below this width (px) side panels overlay the chat instead of sitting beside it (default 760). */\n narrowWidth?: number\n /** Composer options (model / thinking chips, commands, convertFile, speech…), or `false` to hide it. */\n composer?: Partial<Omit<AgentComposerProps, 'controller'>> | false\n\n // ── how it is rendered ─────────────────────────────────────────────────────\n /** A message's text — plug in your markdown renderer here. */\n renderContent?: MessageListProps['renderContent']\n renderMessage?: MessageListProps['renderMessage']\n renderAttachment?: MessageListProps['renderAttachment']\n renderToolCall?: RenderToolCall\n renderApproval?: ToolApprovalPromptProps['renderApproval']\n slots?: AgentChatSlots\n components?: AgentChatComponents\n /** Override any text (i18n); applies to every part inside. */\n labels?: AgentLabelsOverride\n /** Force a colour scheme (default 'auto' = follow the OS). */\n theme?: 'auto' | 'light' | 'dark'\n classNames?: AgentChatClassNames\n className?: string\n /** Inline styles on the root — handy for sizing (e.g. `{ height: 520 }`). */\n style?: CSSProperties\n}\n\nconst isHistoryHook = (h: AgentChatProps['history']): h is UseChatHistoryReturn =>\n typeof h === 'object' && h !== null && 'select' in h && 'chats' in h\n\nconst cx = (...names: (string | false | undefined)[]) => names.filter(Boolean).join(' ')\n\n/**\n * A drop-in chat panel: transcript with every answer's activity (steps, tool\n * calls with their cost, thoughts, subagents, consent decisions) and tokens by\n * kind, live consent prompts, model-load progress, and the full composer\n * (attachments by \"+\", Ctrl+V and drag & drop; slash commands; timer; agents;\n * model + thinking; consent mode; dictation). Optional: saved chats in\n * IndexedDB (`history`) and a workspace panel (`files`).\n *\n * Everything is switchable (`show*`), relabelable (`labels`), replaceable\n * (`render*`, `slots`, `components`) and themable (`theme`, `--awr-*`\n * variables, `classNames`). Give it a `controller` from {@link useAgent}, or\n * wrap it in an {@link AgentProvider}.\n *\n * ```tsx\n * <AgentChat controller={agent} history files={vfs} composer={{ model: { label: 'Gemini' } }} />\n * ```\n */\nexport const AgentChat = (props: AgentChatProps) => (\n <AgentLabelsProvider labels={props.labels ?? NO_LABELS}>\n <AgentChatInner {...props} />\n </AgentLabelsProvider>\n)\n\nconst NO_LABELS: AgentLabelsOverride = {}\n\nconst AgentChatInner = ({\n controller,\n title,\n emptyState,\n placeholder,\n showActivity = true,\n showToolCalls = true,\n showUsage = true,\n showThoughts = true,\n showNotes = true,\n stoppableSubagents = true,\n showTotalUsage = true,\n showStatus = true,\n showApprovalMode = true,\n showContext = false,\n activityOpen = false,\n history,\n defaultHistoryOpen,\n files,\n defaultFilesOpen = false,\n narrowWidth = 760,\n composer,\n renderContent,\n renderMessage,\n renderAttachment,\n renderToolCall,\n renderApproval,\n slots = {},\n components = {},\n theme = 'auto',\n classNames = {},\n className,\n style,\n}: AgentChatProps) => {\n const ctx = useOptionalAgentContext()\n const agent = controller ?? ctx\n if (!agent) {\n throw new Error(\n '<AgentChat> needs a `controller` prop from useAgent(), or an enclosing <AgentProvider>.',\n )\n }\n const L = useLabels()\n\n // History: an external hook result, or our own over the given / default store.\n const external = isHistoryHook(history) ? history : undefined\n const [ownStore] = useState(() =>\n history instanceof ChatHistoryStore ? history : new ChatHistoryStore(),\n )\n const own = useChatHistory(agent, {\n store: ownStore,\n enabled: Boolean(history) && !external,\n })\n const chats = history ? (external ?? own) : undefined\n\n // Narrow panel → the side panels overlay the chat (and start closed).\n const rootRef = useRef<HTMLDivElement>(null)\n const [narrow, setNarrow] = useState<boolean | undefined>(undefined)\n useEffect(() => {\n const el = rootRef.current\n if (!el || typeof ResizeObserver === 'undefined') return setNarrow(false)\n const measure = () => setNarrow(el.getBoundingClientRect().width < narrowWidth)\n measure()\n const ro = new ResizeObserver(measure)\n ro.observe(el)\n return () => ro.disconnect()\n }, [narrowWidth])\n const [historyChoice, setHistoryOpen] = useState<boolean | undefined>(defaultHistoryOpen)\n const historyOpen = historyChoice ?? narrow === false\n const [filesOpen, setFilesOpen] = useState(defaultFilesOpen)\n // On a narrow panel one overlay at a time.\n const toggleHistory = () => {\n setHistoryOpen(!historyOpen)\n if (narrow && !historyOpen) setFilesOpen(false)\n }\n const toggleFiles = () => {\n setFilesOpen((o) => !o)\n if (narrow && !filesOpen) setHistoryOpen(false)\n }\n\n // Follow the transcript while the user is at the bottom; leave them be when\n // they scrolled up to read.\n const bodyRef = useRef<HTMLDivElement>(null)\n const stickRef = useRef(true)\n useEffect(() => {\n const el = bodyRef.current\n if (el && stickRef.current) el.scrollTop = el.scrollHeight\n }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad, agent.pendingApprovals])\n\n const [compacting, setCompacting] = useState(false)\n const compact = () => {\n setCompacting(true)\n void agent.compact().finally(() => setCompacting(false))\n }\n\n const Composer = components.Composer ?? AgentComposer\n const Messages = components.MessageList ?? MessageList\n const HistoryList = components.HistoryList ?? ChatHistoryList\n const Files = components.FilesPanel ?? FilesPanel\n const Approvals = components.ApprovalPrompt ?? ToolApprovalPrompt\n\n const loading = agent.modelLoad && agent.modelLoad.progress < 1\n const showReplan = agent.replan && agent.replan.mode !== 'continue'\n const liveExtra =\n agent.planThought.trim() || showReplan ? (\n <>\n {agent.planThought.trim() && (\n <details className=\"awr-activity__plan\">\n <summary>{L.planned}</summary>\n <p className=\"awr-activity__thought\">{agent.planThought}</p>\n </details>\n )}\n {showReplan && (\n <div className=\"awr-activity__replan\">\n {L.replanned(agent.replan!.mode, agent.replan!.reason)}\n </div>\n )}\n </>\n ) : undefined\n\n const header =\n slots.header === false ? null : slots.header !== undefined ? (\n slots.header\n ) : (\n <div className={cx('awr-chat__header', classNames.header)}>\n {chats && (\n <button\n type=\"button\"\n className={cx('awr-iconbtn', historyOpen && 'is-on')}\n aria-label={L.showHistory}\n title={L.showHistory}\n aria-pressed={historyOpen}\n onClick={toggleHistory}\n >\n <HistoryIcon size={16} />\n </button>\n )}\n {slots.headerStart}\n <div className=\"awr-chat__title\">{title}</div>\n {showStatus && (\n <span className={`awr-status awr-status--${agent.status}`} title={L.status[agent.status]}>\n <span className=\"awr-status__dot\" />\n <span className=\"awr-status__text\">{L.status[agent.status]}</span>\n </span>\n )}\n {showTotalUsage && (\n <span title={L.totalUsage}>\n <UsageBadge usage={agent.totalUsage} compact={narrow !== false} />\n </span>\n )}\n {files && (\n <button\n type=\"button\"\n className={cx('awr-iconbtn', filesOpen && 'is-on')}\n aria-label={L.showFiles}\n title={L.showFiles}\n aria-pressed={filesOpen}\n onClick={toggleFiles}\n >\n <FileIcon size={16} />\n </button>\n )}\n {slots.headerEnd}\n </div>\n )\n\n return (\n <div\n ref={rootRef}\n className={cx('awr-chat', narrow && 'awr-chat--narrow', className, classNames.root)}\n style={style}\n data-awr-theme={theme === 'auto' ? undefined : theme}\n >\n {chats && historyOpen && (\n <aside className={cx('awr-chat__sidebar', classNames.sidebar)}>\n <HistoryList\n history={{\n ...chats,\n // Picking a chat on a narrow panel closes the overlay.\n select: async (id) => {\n await chats.select(id)\n if (narrow) setHistoryOpen(false)\n },\n newChat: () => {\n chats.newChat()\n if (narrow) setHistoryOpen(false)\n },\n }}\n disabled={agent.isRunning}\n />\n {slots.sidebar}\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-chat__closeside\"\n aria-label={L.close}\n onClick={() => setHistoryOpen(false)}\n >\n ×\n </button>\n </aside>\n )}\n\n <div className={cx('awr-chat__main', classNames.main)}>\n {header}\n\n <div\n className={cx('awr-chat__body', classNames.body)}\n ref={bodyRef}\n onScroll={(e) => {\n const el = e.currentTarget\n stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80\n }}\n >\n {slots.beforeMessages}\n <Messages\n messages={agent.messages}\n empty={emptyState ?? L.emptyState}\n showActivity={showActivity}\n showToolCalls={showToolCalls}\n showUsage={showUsage}\n showThoughts={showThoughts}\n showNotes={showNotes}\n onStopSubagent={stoppableSubagents ? agent.stopSubagent : undefined}\n activityOpen={activityOpen}\n liveExtra={liveExtra}\n renderContent={renderContent}\n renderMessage={renderMessage}\n renderAttachment={renderAttachment}\n renderToolCall={renderToolCall}\n />\n <Approvals\n approvals={agent.pendingApprovals}\n onApprove={agent.approve}\n onDeny={agent.deny}\n renderApproval={renderApproval}\n />\n {agent.modelLoad && loading && <ModelLoadBar load={agent.modelLoad} />}\n {slots.afterMessages}\n </div>\n\n <div className={cx('awr-chat__footer', classNames.footer)}>\n {slots.footerStart}\n {showContext !== false && (\n <ContextMeter\n usage={agent.usage}\n budgetTokens={typeof showContext === 'number' ? showContext : undefined}\n budget={agent.budget}\n compactions={agent.compactions}\n onCompact={agent.isRunning ? undefined : compact}\n compacting={compacting}\n />\n )}\n {composer === false ? (\n agent.error &&\n agent.status === 'error' && (\n <div className=\"awr-chat__error\">\n <AlertIcon size={14} /> {agent.error}\n </div>\n )\n ) : (\n <Composer\n controller={agent}\n showApprovalMode={showApprovalMode}\n files={files}\n dropZone={rootRef}\n {...(placeholder ? { placeholder } : {})}\n {...composer}\n />\n )}\n </div>\n </div>\n\n {files && filesOpen && (\n <aside className={cx('awr-chat__files', classNames.files)}>\n <Files files={files} />\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-chat__closeside\"\n aria-label={L.close}\n onClick={() => setFilesOpen(false)}\n >\n ×\n </button>\n </aside>\n )}\n </div>\n )\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport type { ClipboardEvent, CSSProperties, KeyboardEvent, ReactNode, RefObject } from 'react'\nimport type { RunFile, ToolApprovalMode, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport {\n attachmentKindOf,\n attachmentRefusal,\n filterCommands,\n formatElapsed,\n noticesOf,\n parseSlash,\n steerIntent,\n withAttachments,\n type ComposerAttachment,\n type SlashCommand,\n} from '../composer.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { useSpeechToText } from '../hooks/use-speech-to-text.js'\nimport { downscaleImage } from '../image-resize.js'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ChatAttachment } from '../types.js'\nimport {\n AlertIcon,\n BoltIcon,\n BotIcon,\n ClockIcon,\n EyeIcon,\n FileIcon,\n MicIcon,\n PlusIcon,\n SendIcon,\n ShieldIcon,\n SlashIcon,\n SpinnerIcon,\n StopIcon,\n XIcon,\n} from './icons.js'\n\nexport interface ComposerModelChip {\n /** What the chip says, e.g. \"Gemini 3.5 Flash\". */\n label: string\n /** Models to switch to from the chip's menu (omit for a read-only label). */\n options?: { id: string; label: string; group?: string }[]\n value?: string\n onSelect?: (id: string) => void\n}\n\nexport interface ComposerThinkingChip {\n /** Current level, e.g. 'off' | 'low' | 'medium' | 'high'. */\n value: string\n /** Offered levels (default: default / low / medium / high). */\n options?: { id: string; label: string }[]\n onChange: (value: string) => void\n}\n\n/** A file turned into text by the host (e.g. a PDF converted to Markdown). */\nexport interface ConvertedFile {\n text: string\n /** Name of the text attachment (default: the file's name + \".md\"). */\n name?: string\n}\n\nexport interface AgentComposerProps {\n /** The agent from `useAgent()` (or `useAgentContext()`). */\n controller: UseAgentReturn\n placeholder?: string\n /** Model chip (and switcher). */\n model?: ComposerModelChip\n /** Thinking level, shown next to the model and switchable from its menu. */\n thinking?: ComposerThinkingChip\n /** Override any text the composer renders (see `AgentLabels`). */\n labels?: AgentLabelsOverride\n /** Extra slash commands (merged after the built-ins and the agent's skills). */\n commands?: SlashCommand[]\n /** Built-in commands: /compact /new /stop /autopilot /ask /ask-all /read-only /think (default true). */\n builtinCommands?: boolean\n /** Offer the agent's skills as \"/skill-name …\" commands (default true). */\n skillCommands?: boolean\n /**\n * \"+\" button, paste (Ctrl+V) and drag & drop of files and images (default\n * true). Text files are inlined into the message; images, PDFs and other\n * files go to the model as attachments — when the model can take them.\n */\n attachments?:\n | boolean\n | {\n /** The file picker's `accept`. */\n accept?: string\n /** Refuse larger files (default 20 MB). */\n maxBytes?: number\n /**\n * Downscale images to this longest edge before sending (default 1568 —\n * what providers bill for; larger only costs upload). false = as is.\n */\n imageMaxDimension?: number | false\n /** …and to this many pixels (default 1 150 000). */\n imageMaxPixels?: number\n }\n /**\n * Turn a file into text — e.g. PDF → Markdown with `@dudko.dev/pdf-to-md-core`.\n * Used for PDFs the model can't read (or every PDF with `convert: 'always'`)\n * and for files of a kind the model refuses. Return undefined to skip.\n */\n convertFile?: (file: File) => Promise<ConvertedFile | undefined>\n /** When to use `convertFile` for PDFs (default 'when-needed'). */\n convert?: 'when-needed' | 'always'\n /** Save attachments into this virtual file system (under `/attachments/`). */\n files?: VirtualFileSystem\n /**\n * Where dropping files attaches them: the composer itself ('self', default),\n * the whole window ('window'), or any element (a ref — `<AgentChat>` passes\n * its own panel).\n */\n dropZone?: 'self' | 'window' | RefObject<HTMLElement | null>\n /** Speech-to-text mic — the browser's Web Speech API (default: on when supported). */\n speech?: boolean | { lang?: string }\n /** Run timer chip (default true). */\n showTimer?: boolean\n /** Running-subagents chip (default true). */\n showAgents?: boolean\n /** Consent-mode chip — \"⚡ Auto\" for autopilot (default true). */\n showApprovalMode?: boolean\n /** Banners for limits, compaction and errors above the input (default true). */\n showNotices?: boolean\n /**\n * Let the user type to the agent while it works (default true): Enter sends the text\n * to the running agent, which sees it at its next boundary (see `useAgent().send`).\n * Off: the input does nothing while a run is going, as before.\n */\n steering?: boolean\n /** Messages waiting for the agent, and the ones a stopped run left undelivered (default true). */\n showQueued?: boolean\n /** Below this width (px) the toolbar chips show icons and numbers only (default 460). */\n compactWidth?: number\n /** Extra content in the toolbar, after the \"/\" button. */\n toolbarExtra?: ReactNode\n /** Extra content at the end of the toolbar, before the consent chip. */\n toolbarEnd?: ReactNode\n /** Render an attachment chip yourself (`remove` drops it). */\n renderAttachment?: (attachment: ComposerAttachment, remove: () => void) => ReactNode\n disabled?: boolean\n className?: string\n}\n\nconst thinkingDefaults = (l: AgentLabels) => [\n { id: 'off', label: l.thinkingLevels.off },\n { id: 'none', label: l.thinkingLevels.none },\n { id: 'low', label: l.thinkingLevels.low },\n { id: 'medium', label: l.thinkingLevels.medium },\n { id: 'high', label: l.thinkingLevels.high },\n]\n\nconst MODES: ToolApprovalMode[] = ['autopilot', 'ask-writes', 'ask-all', 'read-only']\n\nconst ModeIcon = ({ mode }: { mode: ToolApprovalMode }) =>\n mode === 'autopilot' ? (\n <BoltIcon size={14} />\n ) : mode === 'read-only' ? (\n <EyeIcon size={14} />\n ) : (\n <ShieldIcon size={14} />\n )\n\ntype Menu = 'commands' | 'model' | 'mode' | undefined\n\nlet attachSeq = 0\n\n// useLayoutEffect warns during SSR; menus only exist in the browser anyway.\nconst useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect\n\n/**\n * Where an open menu goes: fixed, next to its anchor — above it when there is\n * room (the composer sits at the bottom of a panel), below otherwise — so the\n * panel's `overflow` never clips it and it never leaves the viewport.\n */\nconst useMenuPlacement = (\n open: boolean,\n anchor: RefObject<HTMLElement | null>,\n align: 'left' | 'right' | 'stretch',\n): CSSProperties | undefined => {\n const [style, setStyle] = useState<CSSProperties>()\n useIsoLayoutEffect(() => {\n if (!open) return\n const place = () => {\n const el = anchor.current\n if (!el) return\n const r = el.getBoundingClientRect()\n const vw = window.innerWidth\n const vh = window.innerHeight\n const above = r.top - 8\n const below = vh - r.bottom - 8\n const up = above >= 240 || above >= below\n const s: CSSProperties = {\n maxHeight: Math.max(120, (up ? above : below) - 6),\n top: up ? 'auto' : r.bottom + 6,\n bottom: up ? vh - r.top + 6 : 'auto',\n maxWidth: vw - 16,\n }\n if (align === 'stretch') {\n s.left = Math.max(8, r.left)\n s.width = Math.min(r.width, vw - 16)\n } else if (align === 'right') {\n s.left = 'auto'\n s.right = Math.max(8, vw - r.right)\n } else {\n s.left = Math.max(8, Math.min(r.left, vw - 248))\n }\n setStyle(s)\n }\n place()\n window.addEventListener('resize', place)\n window.addEventListener('scroll', place, true)\n return () => {\n window.removeEventListener('resize', place)\n window.removeEventListener('scroll', place, true)\n }\n }, [open, anchor, align])\n return open ? style : undefined\n}\n\nconst readDataUrl = (file: Blob): Promise<string> =>\n new Promise((resolve, reject) => {\n const r = new FileReader()\n r.onload = () => resolve(String(r.result))\n r.onerror = () => reject(r.error ?? new Error('could not read the file'))\n r.readAsDataURL(file)\n })\n\nconst safeName = (name: string): string => name.replace(/[^\\w.-]+/g, '_').slice(0, 80) || 'file'\n\n/**\n * A full chat composer for the agent — the input plus everything around it:\n *\n * - banners for a limit that stopped the run, a compaction, a start failure,\n * or an attachment the model can't take;\n * - the \"+\" button, Ctrl+V and drag & drop: images (thumbnails), PDFs and text\n * files — checked against the model's capabilities, optionally converted\n * (PDF → Markdown) and saved to a virtual file system;\n * - slash commands: `/compact`, `/new`, `/stop`, the consent modes, `/think`,\n * and the agent's skills as `/skill-name …`;\n * - a run timer, the number of running subagents, the model + thinking chip,\n * the consent-mode chip (\"⚡ Auto\" = autopilot), a speech-to-text mic, and\n * send / stop.\n *\n * Every piece can be switched off; `<AgentChat>` uses it as its footer.\n */\nexport const AgentComposer = ({\n controller: agent,\n placeholder,\n model,\n thinking,\n labels: labelsOverride,\n commands = [],\n builtinCommands = true,\n skillCommands = true,\n attachments = true,\n convertFile,\n convert = 'when-needed',\n files: vfs,\n dropZone = 'self',\n speech = true,\n showTimer = true,\n showAgents = true,\n showApprovalMode = true,\n showNotices = true,\n steering = true,\n showQueued = true,\n compactWidth = 460,\n toolbarExtra,\n toolbarEnd,\n renderAttachment,\n disabled = false,\n className,\n}: AgentComposerProps) => {\n const L = useLabels(labelsOverride)\n const MODE_CHIP = L.modes\n const DEFAULT_THINKING = thinkingDefaults(L)\n const [text, setText] = useState('')\n const [pending, setPending] = useState<ComposerAttachment[]>([])\n const [menu, setMenu] = useState<Menu>(undefined)\n const [active, setActive] = useState(0)\n const [dismissed, setDismissed] = useState<Set<string>>(() => new Set())\n const [attachError, setAttachError] = useState<string | undefined>()\n const [dragging, setDragging] = useState(false)\n const rootRef = useRef<HTMLDivElement>(null)\n const modelRef = useRef<HTMLSpanElement>(null)\n const modeRef = useRef<HTMLSpanElement>(null)\n // Where the drop overlay goes: over the whole drop zone, not just the input.\n const [dropRect, setDropRect] = useState<CSSProperties>()\n // A narrow composer (a phone, a side panel) keeps one toolbar row by\n // dropping the chips' words — icons and numbers stay, words go to tooltips.\n const [compactBar, setCompactBar] = useState(false)\n useEffect(() => {\n const el = rootRef.current\n if (!el || typeof ResizeObserver === 'undefined') return\n const ro = new ResizeObserver(() =>\n setCompactBar(el.getBoundingClientRect().width < compactWidth),\n )\n ro.observe(el)\n return () => ro.disconnect()\n }, [compactWidth])\n const fileRef = useRef<HTMLInputElement>(null)\n const inputRef = useRef<HTMLTextAreaElement>(null)\n\n const busy = agent.isRunning\n const ready = agent.isReady && !disabled\n const caps = agent.agent?.capabilities\n\n // ── speech-to-text ──────────────────────────────────────────────────────────\n const stt = useSpeechToText({\n lang: typeof speech === 'object' ? speech.lang : undefined,\n onFinal: (heard) => setText((t) => (t.trim() ? `${t.trimEnd()} ${heard}` : heard)),\n })\n const showMic = speech !== false && stt.supported\n\n // ── run timer ───────────────────────────────────────────────────────────────\n const [startedAt, setStartedAt] = useState<number | undefined>()\n const [now, setNow] = useState(() => Date.now())\n const [lastElapsed, setLastElapsed] = useState<number | undefined>()\n useEffect(() => {\n if (!busy) {\n if (startedAt !== undefined) setLastElapsed(Date.now() - startedAt)\n setStartedAt(undefined)\n return\n }\n const t0 = Date.now()\n setStartedAt(t0)\n setNow(t0)\n const id = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(id)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [busy])\n const elapsed = startedAt !== undefined ? now - startedAt : lastElapsed\n\n // ── commands ────────────────────────────────────────────────────────────────\n const allCommands = useMemo<SlashCommand[]>(() => {\n const out: SlashCommand[] = []\n if (builtinCommands) {\n out.push(\n {\n name: 'compact',\n description: L.commandDescriptions.compact,\n group: L.commandGroups.commands,\n run: () => void agent.compact(),\n },\n {\n name: 'new',\n description: L.commandDescriptions.new,\n group: L.commandGroups.commands,\n run: agent.reset,\n },\n {\n name: 'stop',\n description: L.commandDescriptions.stop,\n group: L.commandGroups.commands,\n run: agent.stop,\n },\n {\n name: 'autopilot',\n description: L.commandDescriptions.autopilot,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('autopilot'),\n },\n {\n name: 'ask',\n description: L.commandDescriptions.ask,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('ask-writes'),\n },\n {\n name: 'ask-all',\n description: L.commandDescriptions.askAll,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('ask-all'),\n },\n {\n name: 'read-only',\n description: L.commandDescriptions.readOnly,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('read-only'),\n },\n )\n if (thinking) {\n const levels = (thinking.options ?? DEFAULT_THINKING).map((o) => o.id)\n out.push({\n name: 'think',\n description: L.commandDescriptions.think(levels.join(' | ')),\n group: L.commandGroups.commands,\n run: (args) => {\n const level = args.trim().toLowerCase()\n if (levels.includes(level)) thinking.onChange(level)\n },\n })\n }\n }\n if (skillCommands) {\n for (const s of agent.agent?.skills ?? []) {\n out.push({\n name: s.name,\n description: s.description,\n group: L.commandGroups.skills,\n kind: 'prefix',\n transform: (args) => `Use the \"${s.name}\" skill. ${args}`.trim(),\n })\n }\n }\n return [...out, ...commands]\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, builtinCommands, skillCommands, commands, thinking, L])\n\n const slash = parseSlash(text)\n const matches =\n slash && !/\\s/.test(text.trimStart()) ? filterCommands(allCommands, slash.name) : []\n const palette = menu === 'commands' && !slash ? allCommands : matches\n const paletteOpen = palette.length > 0 && (menu === 'commands' || matches.length > 0)\n const commandsStyle = useMenuPlacement(paletteOpen, rootRef, 'stretch')\n const modelStyle = useMenuPlacement(menu === 'model', modelRef, 'left')\n const modeStyle = useMenuPlacement(menu === 'mode', modeRef, 'right')\n\n useEffect(() => setActive(0), [text, menu])\n\n // Close popovers on an outside click.\n useEffect(() => {\n if (!menu) return\n const onDown = (e: MouseEvent) => {\n if (!rootRef.current?.contains(e.target as Node)) setMenu(undefined)\n }\n document.addEventListener('mousedown', onDown)\n return () => document.removeEventListener('mousedown', onDown)\n }, [menu])\n\n const pick = (cmd: SlashCommand) => {\n setMenu(undefined)\n if (cmd.kind === 'prefix') {\n setText(`/${cmd.name} `)\n inputRef.current?.focus()\n return\n }\n const args = parseSlash(text)?.args ?? ''\n setText('')\n void cmd.run?.(args)\n }\n\n // ── attachments ─────────────────────────────────────────────────────────────\n const attachCfg = typeof attachments === 'object' ? attachments : {}\n const maxBytes = attachCfg.maxBytes ?? 20 * 1024 * 1024\n const imageMax = attachCfg.imageMaxDimension ?? 1568\n\n const addFiles = async (list: File[]) => {\n const added: ComposerAttachment[] = []\n let problem: string | undefined\n for (const f of list) {\n const mediaType = f.type || 'application/octet-stream'\n const name = f.name || `pasted-${Date.now()}.${mediaType.split('/')[1] ?? 'bin'}`\n const kind = attachmentKindOf(mediaType, name)\n if (f.size > maxBytes) {\n problem = L.tooLarge(name, Math.round(maxBytes / 1024 / 1024))\n continue\n }\n try {\n const id = `att-${(attachSeq += 1)}`\n if (kind === 'text') {\n const content = await f.text()\n if (content.includes('\\u0000')) {\n problem = L.binaryText(name)\n continue\n }\n added.push({ id, name, kind, mediaType, text: content, bytes: f.size })\n continue\n }\n // A kind the model can't take: convert it to text when the host can,\n // otherwise refuse with a sentence the user can act on.\n const refusal = attachmentRefusal(kind, caps)\n const wantConvert = convertFile && (refusal || (kind === 'pdf' && convert === 'always'))\n if (wantConvert && convertFile) {\n const converted = await convertFile(f)\n if (converted) {\n added.push({\n id,\n name: converted.name ?? `${name}.md`,\n kind: 'text',\n mediaType: 'text/markdown',\n text: converted.text,\n bytes: converted.text.length,\n note: `converted from ${name}`,\n })\n continue\n }\n }\n if (refusal) {\n problem = refusal\n continue\n }\n // Images go at the size providers bill for, not the camera's.\n const blob =\n kind === 'image' && imageMax !== false\n ? await downscaleImage(f, {\n maxDimension: imageMax,\n maxPixels: attachCfg.imageMaxPixels,\n })\n : f\n added.push({\n id,\n name,\n kind,\n mediaType: blob.type || mediaType,\n dataUrl: await readDataUrl(blob),\n bytes: blob.size,\n ...(blob !== f ? { note: `downscaled from ${L.bytes(f.size)}` } : {}),\n })\n } catch (err) {\n problem = `${name}: ${err instanceof Error ? err.message : String(err)}`\n }\n }\n setAttachError(problem)\n if (added.length) setPending((cur) => [...cur, ...added])\n if (fileRef.current) fileRef.current.value = ''\n }\n\n const onPaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {\n if (attachments === false) return\n const pasted = Array.from(e.clipboardData?.files ?? [])\n if (pasted.length === 0) return // plain text: let the textarea take it\n e.preventDefault()\n void addFiles(pasted)\n }\n\n // Drag & drop onto the drop zone (the composer, a panel, or the window).\n const addFilesRef = useRef(addFiles)\n addFilesRef.current = addFiles\n useEffect(() => {\n if (attachments === false) return\n const target: EventTarget | null | undefined =\n dropZone === 'window'\n ? globalThis.window\n : dropZone === 'self'\n ? rootRef.current\n : dropZone.current\n if (!target) return\n let depth = 0\n const hasFiles = (e: Event) =>\n Array.from((e as globalThis.DragEvent).dataTransfer?.types ?? []).includes('Files')\n const onEnter = (e: Event) => {\n if (!hasFiles(e)) return\n depth += 1\n if (target === globalThis.window) setDropRect({ inset: 0 })\n else {\n const r = (target as HTMLElement).getBoundingClientRect()\n setDropRect({ left: r.left, top: r.top, width: r.width, height: r.height })\n }\n setDragging(true)\n }\n const onOver = (e: Event) => {\n if (hasFiles(e)) e.preventDefault() // allow the drop\n }\n const onLeave = () => {\n depth = Math.max(0, depth - 1)\n if (depth === 0) setDragging(false)\n }\n const onDropFiles = (e: Event) => {\n const dropped = (e as globalThis.DragEvent).dataTransfer?.files\n depth = 0\n setDragging(false)\n if (!dropped?.length) return\n e.preventDefault()\n void addFilesRef.current(Array.from(dropped))\n }\n target.addEventListener('dragenter', onEnter)\n target.addEventListener('dragover', onOver)\n target.addEventListener('dragleave', onLeave)\n target.addEventListener('drop', onDropFiles)\n return () => {\n target.removeEventListener('dragenter', onEnter)\n target.removeEventListener('dragover', onOver)\n target.removeEventListener('dragleave', onLeave)\n target.removeEventListener('drop', onDropFiles)\n }\n }, [attachments, dropZone])\n\n // ── submit ──────────────────────────────────────────────────────────────────\n const submit = () => {\n const raw = text.trim()\n // While the agent works, text is said TO it; everything else waits for the next message.\n const intent = steerIntent({ raw, busy, steering, hasAttachments: pending.length > 0 })\n if (intent === 'steer') {\n // If the run ended a moment ago `send` refuses: the text stays, nothing is lost.\n if (agent.send(raw)) setText('')\n return\n }\n if (intent === 'attachments') {\n setAttachError(L.noAttachmentsWhileBusy)\n return\n }\n if (intent === 'ignore') return\n if (!ready) return\n const parsed = parseSlash(raw)\n if (parsed) {\n const cmd = allCommands.find((c) => c.name === parsed.name)\n if (cmd?.kind !== 'prefix') {\n if (cmd) {\n setText('')\n void cmd.run?.(parsed.args)\n }\n return\n }\n if (!parsed.args && pending.length === 0) return\n void send(cmd.transform ? cmd.transform(parsed.args) : parsed.args, raw)\n return\n }\n if (!raw && pending.length === 0) return\n void send(raw, raw)\n }\n\n const send = async (goal: string, shown: string) => {\n if (stt.listening) stt.stop()\n const items = pending\n setText('')\n setPending([])\n // Keep a copy in the workspace, so the agent's fs_* tools can reach it later.\n if (vfs) {\n for (const a of items) {\n const path = `/attachments/${safeName(a.name)}`\n try {\n if (a.dataUrl) await vfs.writeDataUrl(path, a.dataUrl)\n else if (a.text !== undefined) await vfs.write(path, a.text, { mimeType: a.mediaType })\n a.path = path\n } catch {\n /* the message still goes out without the copy */\n }\n }\n }\n const toModel = (a: ComposerAttachment): RunFile => ({\n data: a.dataUrl as string,\n mediaType: a.mediaType,\n name: a.name,\n })\n const shownAttachments: ChatAttachment[] = items.map((a) => ({\n name: a.name,\n mediaType: a.mediaType,\n size: a.bytes,\n ...(a.kind === 'image' && a.dataUrl ? { dataUrl: a.dataUrl } : {}),\n ...(a.path ? { path: a.path } : {}),\n }))\n const full = withAttachments(goal || L.seeAttachments, items)\n // The transcript shows the attachments as chips/thumbnails, not in the text.\n const label = shown || (items.length ? L.attachmentsOnly : '')\n void agent.run(full, {\n ...(full !== label ? { label } : {}),\n images: items.filter((a) => a.kind === 'image' && a.dataUrl).map(toModel),\n files: items.filter((a) => (a.kind === 'pdf' || a.kind === 'file') && a.dataUrl).map(toModel),\n attachments: shownAttachments,\n })\n }\n\n const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (paletteOpen) {\n if (e.key === 'ArrowDown') {\n e.preventDefault()\n setActive((i) => (i + 1) % palette.length)\n return\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault()\n setActive((i) => (i - 1 + palette.length) % palette.length)\n return\n }\n if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey && matches.length > 0)) {\n e.preventDefault()\n pick(palette[active] ?? palette[0])\n return\n }\n if (e.key === 'Escape') {\n setMenu(undefined)\n setText('')\n return\n }\n }\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault()\n submit()\n }\n }\n\n // ── notices ────────────────────────────────────────────────────────────────\n const notices = showNotices\n ? [\n ...noticesOf(agent, L.notices),\n ...(attachError\n ? [{ id: `attach:${attachError}`, tone: 'warn' as const, text: attachError }]\n : []),\n ...(stt.error\n ? [\n {\n id: `stt:${stt.error}`,\n tone: 'warn' as const,\n text: `${L.microphone}: ${stt.error}`,\n },\n ]\n : []),\n ].filter((n) => !dismissed.has(n.id))\n : []\n\n const runningAgents = agent.subagents.filter((s) => s.status === 'running')\n const thinkingOptions = thinking?.options ?? DEFAULT_THINKING\n const thinkingLabel = thinking\n ? (thinkingOptions.find((o) => o.id === thinking.value)?.label ?? thinking.value)\n : undefined\n const canSend = ready && (text.trim().length > 0 || pending.length > 0)\n const canSteer = busy && steering && text.trim().length > 0\n const queuedStrip =\n showQueued && (agent.queued.length > 0 || agent.undelivered.length > 0) ? (\n <div className=\"awr-queued\">\n {agent.queued.map((q) => (\n <div key={q.id} className=\"awr-queued__item\" role=\"status\">\n <ClockIcon size={13} className=\"awr-queued__icon\" />\n <span className=\"awr-queued__text\" title={q.text}>\n {q.text}\n </span>\n <span className=\"awr-queued__state\">{L.queuedWaiting}</span>\n </div>\n ))}\n {agent.undelivered.length > 0 && (\n <div className=\"awr-queued__item awr-queued__item--undelivered\" role=\"status\">\n <AlertIcon size={13} className=\"awr-queued__icon\" />\n <span className=\"awr-queued__text\" title={agent.undelivered.join('\\n\\n')}>\n {L.undelivered(agent.undelivered.length)}: {agent.undelivered.join(' · ')}\n </span>\n <button type=\"button\" className=\"awr-linkbtn\" onClick={agent.sendUndelivered}>\n {L.sendUndelivered}\n </button>\n <button type=\"button\" className=\"awr-linkbtn\" onClick={agent.discardUndelivered}>\n {L.discardUndelivered}\n </button>\n </div>\n )}\n </div>\n ) : null\n\n return (\n <div\n className={[\n 'awr-composer2',\n dragging ? 'is-dragging' : '',\n compactBar ? 'awr-composer2--compact' : '',\n className,\n ]\n .filter(Boolean)\n .join(' ')}\n ref={rootRef}\n >\n {dragging && (\n <div className=\"awr-dropnote\" style={dropRect} aria-hidden=\"true\">\n {L.dropHint}\n </div>\n )}\n {queuedStrip}\n {notices.length > 0 && (\n <div className=\"awr-notices\">\n {notices.map((n) => (\n <div key={n.id} className={`awr-notice awr-notice--${n.tone}`} role=\"status\">\n <span>{n.text}</span>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.dismiss}\n onClick={() => {\n setDismissed((d) => new Set(d).add(n.id))\n if (n.id.startsWith('attach:')) setAttachError(undefined)\n }}\n >\n <XIcon size={14} />\n </button>\n </div>\n ))}\n </div>\n )}\n\n {paletteOpen && (\n <ul\n className=\"awr-menu awr-menu--commands\"\n style={commandsStyle}\n role=\"listbox\"\n aria-label={L.commands}\n >\n {palette.map((c, i) => (\n <li key={`${c.group}:${c.name}`}>\n <button\n type=\"button\"\n role=\"option\"\n aria-selected={i === active}\n className={`awr-menu__item${i === active ? ' is-active' : ''}`}\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => pick(c)}\n >\n <code>/{c.name}</code>\n <span className=\"awr-menu__desc\">{c.description}</span>\n {c.group && <span className=\"awr-menu__group\">{c.group}</span>}\n </button>\n </li>\n ))}\n </ul>\n )}\n\n {pending.length > 0 && (\n <div className=\"awr-files\">\n {pending.map((a) => {\n const remove = () => setPending((cur) => cur.filter((x) => x.id !== a.id))\n if (renderAttachment) return <span key={a.id}>{renderAttachment(a, remove)}</span>\n return (\n <span key={a.id} className=\"awr-chip awr-file\" title={a.note ?? a.mediaType}>\n {a.kind === 'image' && a.dataUrl ? (\n <img className=\"awr-file__thumb\" src={a.dataUrl} alt={a.name} />\n ) : (\n <FileIcon size={14} />\n )}\n <span className=\"awr-file__name\">{a.name}</span>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.remove(a.name)}\n onClick={remove}\n >\n <XIcon size={12} />\n </button>\n </span>\n )\n })}\n </div>\n )}\n\n <div className=\"awr-composer2__inputrow\">\n <textarea\n ref={inputRef}\n className=\"awr-composer2__input\"\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={onKeyDown}\n onPaste={onPaste}\n placeholder={\n stt.listening\n ? L.listening\n : busy && steering\n ? L.placeholderBusy\n : (placeholder ?? L.placeholder)\n }\n disabled={disabled}\n rows={2}\n aria-label={L.message}\n />\n {showMic && (\n <button\n type=\"button\"\n className={`awr-iconbtn awr-mic${stt.listening ? ' is-on' : ''}`}\n aria-label={stt.listening ? L.stopDictation : L.dictate}\n title={stt.listening ? L.stopDictation : L.dictateTitle}\n onClick={stt.toggle}\n disabled={disabled}\n >\n <MicIcon size={18} />\n </button>\n )}\n </div>\n {stt.listening && stt.interim && <div className=\"awr-composer2__interim\">{stt.interim}</div>}\n\n <div className=\"awr-toolbar\">\n {attachments !== false && (\n <>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.attach}\n title={L.attachTitle}\n onClick={() => fileRef.current?.click()}\n disabled={disabled}\n >\n <PlusIcon size={18} />\n </button>\n <input\n ref={fileRef}\n type=\"file\"\n multiple\n hidden\n accept={attachCfg.accept}\n onChange={(e) => void addFiles(Array.from(e.target.files ?? []))}\n />\n </>\n )}\n <button\n type=\"button\"\n className={`awr-iconbtn${menu === 'commands' ? ' is-on' : ''}`}\n aria-label={L.commands}\n title={L.commandsTitle}\n onClick={() => setMenu(menu === 'commands' ? undefined : 'commands')}\n >\n <SlashIcon size={18} />\n </button>\n {toolbarExtra}\n {showTimer && elapsed !== undefined && (\n <span className=\"awr-tchip\" title={busy ? L.timerRunning : L.timerLast}>\n <ClockIcon size={14} /> {formatElapsed(elapsed)}\n </span>\n )}\n {showAgents && (\n <span\n className={`awr-tchip awr-agents${runningAgents.length ? ' is-busy' : ''}`}\n title={\n agent.subagents.length\n ? agent.subagents.map((s) => `${s.name} (${s.status}): ${s.task}`).join('\\n')\n : L.agentsTitle\n }\n >\n <span className=\"awr-agents__dot\" aria-hidden=\"true\" />\n <BotIcon size={14} />{' '}\n {compactBar ? runningAgents.length : L.agents(runningAgents.length)}\n </span>\n )}\n {(model || thinking) && (\n <span className=\"awr-popwrap awr-popwrap--model\" ref={modelRef}>\n <button\n type=\"button\"\n className=\"awr-tchip awr-tchip--btn\"\n onClick={() => setMenu(menu === 'model' ? undefined : 'model')}\n aria-haspopup=\"menu\"\n aria-expanded={menu === 'model'}\n title={[model?.label, thinkingLabel].filter(Boolean).join(' · ')}\n >\n <span className=\"awr-tchip__label\">{model?.label ?? L.model}</span>\n {thinkingLabel && !compactBar && (\n <span className=\"awr-tchip__sub\">{thinkingLabel}</span>\n )}\n </button>\n {menu === 'model' && (\n <div className=\"awr-menu awr-menu--pop\" style={modelStyle} role=\"menu\">\n {thinking && (\n <>\n <div className=\"awr-menu__head\">{L.thinking}</div>\n {thinkingOptions.map((o) => (\n <button\n key={o.id}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={thinking.value === o.id}\n className={`awr-menu__item${thinking.value === o.id ? ' is-active' : ''}`}\n onClick={() => {\n thinking.onChange(o.id)\n setMenu(undefined)\n }}\n >\n {o.label}\n </button>\n ))}\n </>\n )}\n {model?.options?.length ? (\n <>\n <div className=\"awr-menu__head\">{L.model}</div>\n {model.options.map((o) => (\n <button\n key={o.id}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={model.value === o.id}\n className={`awr-menu__item${model.value === o.id ? ' is-active' : ''}`}\n onClick={() => {\n model.onSelect?.(o.id)\n setMenu(undefined)\n }}\n >\n {o.label}\n {o.group && <span className=\"awr-menu__group\">{o.group}</span>}\n </button>\n ))}\n </>\n ) : null}\n </div>\n )}\n </span>\n )}\n\n <span className=\"awr-toolbar__spacer\" />\n {toolbarEnd}\n\n {showApprovalMode && (\n <span className=\"awr-popwrap\" ref={modeRef}>\n <button\n type=\"button\"\n className={`awr-tchip awr-tchip--btn awr-mode awr-mode--${agent.approvalMode}`}\n title={MODE_CHIP[agent.approvalMode].hint}\n onClick={() => setMenu(menu === 'mode' ? undefined : 'mode')}\n aria-haspopup=\"menu\"\n aria-expanded={menu === 'mode'}\n aria-label={`${L.toolConsent}: ${MODE_CHIP[agent.approvalMode].label}`}\n >\n <ModeIcon mode={agent.approvalMode} />\n {!compactBar && ` ${MODE_CHIP[agent.approvalMode].label}`}\n </button>\n {menu === 'mode' && (\n <div className=\"awr-menu awr-menu--pop\" style={modeStyle} role=\"menu\">\n <div className=\"awr-menu__head\">{L.toolConsent}</div>\n {MODES.map((m) => (\n <button\n key={m}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={agent.approvalMode === m}\n className={`awr-menu__item${agent.approvalMode === m ? ' is-active' : ''}`}\n onClick={() => {\n agent.setApprovalMode(m)\n setMenu(undefined)\n }}\n >\n <ModeIcon mode={m} /> {MODE_CHIP[m].label}\n <span className=\"awr-menu__desc\">{MODE_CHIP[m].hint}</span>\n </button>\n ))}\n </div>\n )}\n </span>\n )}\n\n {canSteer && (\n <button type=\"button\" className=\"awr-sendbtn\" onClick={submit} aria-label={L.steer}>\n <SendIcon size={16} />\n </button>\n )}\n {busy ? (\n <button\n type=\"button\"\n className=\"awr-sendbtn awr-sendbtn--stop\"\n onClick={agent.stop}\n aria-label={L.stop}\n >\n <StopIcon size={16} />\n </button>\n ) : (\n <button\n type=\"button\"\n className=\"awr-sendbtn\"\n onClick={submit}\n disabled={!canSend}\n aria-label={L.send}\n >\n {agent.status === 'initializing' ? <SpinnerIcon size={16} /> : <SendIcon size={16} />}\n </button>\n )}\n </div>\n </div>\n )\n}\n","// Tiny inline SVG icons — no icon-font or image dependency. Each inherits the\n// current text color (`stroke=\"currentColor\"`) and takes an optional size.\n\nexport interface IconProps {\n size?: number\n className?: string\n}\n\nconst base = (size = 16) => ({\n width: size,\n height: size,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round' as const,\n strokeLinejoin: 'round' as const,\n 'aria-hidden': true,\n})\n\nexport const SendIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M22 2 11 13\" />\n <path d=\"M22 2 15 22l-4-9-9-4Z\" />\n </svg>\n)\n\nexport const StopIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n </svg>\n)\n\nexport const SpinnerIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={['awr-spin', className].filter(Boolean).join(' ')}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </svg>\n)\n\nexport const CheckIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n)\n\nexport const AlertIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </svg>\n)\n\nexport const ToolIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z\" />\n </svg>\n)\n\nexport const ChevronIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n)\n\nexport const ShieldIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n </svg>\n)\n\nexport const BrainIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M9 3a3 3 0 0 0-3 3 3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 6 1V4a3 3 0 0 0-3-1Z\" />\n <path d=\"M15 3a3 3 0 0 1 3 3 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-6 1\" />\n </svg>\n)\n\nexport const BotIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"4\" y=\"8\" width=\"16\" height=\"12\" rx=\"3\" />\n <path d=\"M12 8V4\" />\n <path d=\"M9 14h.01M15 14h.01\" />\n </svg>\n)\n\nexport const PlusIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n)\n\nexport const SlashIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"3\" />\n <path d=\"m15 7-6 10\" />\n </svg>\n)\n\nexport const ClockIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M12 7v5l3 2\" />\n </svg>\n)\n\nexport const MicIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5 11a7 7 0 0 0 14 0M12 18v3\" />\n </svg>\n)\n\nexport const BoltIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M13 2 4 14h7l-1 8 9-12h-7Z\" />\n </svg>\n)\n\nexport const EyeIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </svg>\n)\n\nexport const XIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n)\n\nexport const FileIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z\" />\n <path d=\"M14 3v6h6\" />\n </svg>\n)\n\nexport const HistoryIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M3 12a9 9 0 1 0 3-6.7L3 8\" />\n <path d=\"M3 3v5h5M12 7v5l3 2\" />\n </svg>\n)\n\nexport const DownloadIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 3v12m-5-5 5 5 5-5M5 21h14\" />\n </svg>\n)\n","import { Fragment } from 'react'\nimport type { ReactNode } from 'react'\nimport type { ChatSummary } from '../chat-history.js'\nimport type { UseChatHistoryReturn } from '../hooks/use-chat-history.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { PlusIcon, XIcon } from './icons.js'\n\nexport interface ChatHistoryListProps {\n /** From `useChatHistory(agent)`. */\n history: UseChatHistoryReturn\n title?: ReactNode\n /** Disable switching (e.g. while a run is in flight). */\n disabled?: boolean\n /** Render an entry yourself; `fallback` is the built-in `<li>` — return it, or your own `<li>`. */\n renderChat?: (chat: ChatSummary, active: boolean, fallback: ReactNode) => ReactNode\n /** Format an entry's time (default: locale date + time). */\n formatTime?: (ms: number) => string\n labels?: AgentLabelsOverride\n className?: string\n}\n\nconst defaultTime = (ms: number): string => {\n const d = new Date(ms)\n const today = new Date().toDateString() === d.toDateString()\n return today\n ? d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n : d.toLocaleDateString()\n}\n\n/** The saved conversations: a \"New chat\" button, then one row per chat (newest first). */\nexport const ChatHistoryList = ({\n history,\n title,\n disabled,\n renderChat,\n formatTime = defaultTime,\n labels,\n className,\n}: ChatHistoryListProps) => {\n const L = useLabels(labels)\n return (\n <div className={['awr-history', className].filter(Boolean).join(' ')}>\n <div className=\"awr-panel__head\">\n <span className=\"awr-panel__title\">{title ?? L.history}</span>\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--ghost awr-history__new\"\n onClick={history.newChat}\n disabled={disabled}\n >\n <PlusIcon size={14} /> {L.newChat}\n </button>\n </div>\n {!history.loading && history.chats.length === 0 && (\n <div className=\"awr-panel__empty\">{L.historyEmpty}</div>\n )}\n <ul className=\"awr-history__list\">\n {history.chats.map((c) => {\n const active = c.id === history.currentId\n const row = (\n <li key={c.id} className={`awr-history__item${active ? ' is-active' : ''}`}>\n <button\n type=\"button\"\n className=\"awr-history__open\"\n onClick={() => void history.select(c.id)}\n disabled={disabled || active}\n aria-current={active ? 'true' : undefined}\n >\n <span className=\"awr-history__title\">{c.title}</span>\n <span className=\"awr-history__meta\">\n {formatTime(c.updatedAt)} · {L.messagesCount(c.messageCount)}\n </span>\n </button>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={`${L.deleteChat}: ${c.title}`}\n title={L.deleteChat}\n onClick={() => void history.remove(c.id)}\n disabled={disabled}\n >\n <XIcon size={14} />\n </button>\n </li>\n )\n return renderChat ? <Fragment key={c.id}>{renderChat(c, active, row)}</Fragment> : row\n })}\n </ul>\n </div>\n )\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","import type { IUsage } from '@dudko.dev/agent-web'\nimport type { BudgetView, CompactionView } from '../types.js'\nimport { formatTokens } from './format.js'\n\nexport interface ContextMeterProps {\n usage: IUsage\n /** A run budget to draw the bar against (e.g. limits.maxTotalTokens). */\n budgetTokens?: number\n /** The limit that stopped the run, if any. */\n budget?: BudgetView\n compactions?: CompactionView[]\n /** Show a \"Compact\" button (e.g. `agent.compact`). */\n onCompact?: () => void\n compacting?: boolean\n className?: string\n}\n\n/**\n * Where the run's tokens went — input, output, thinking, prompt-cache hits —\n * with an optional budget bar, the last compaction and a \"Compact\" button.\n */\nexport const ContextMeter = ({\n usage,\n budgetTokens,\n budget,\n compactions = [],\n onCompact,\n compacting,\n className,\n}: ContextMeterProps) => {\n const cached = usage.cachedInputTokens ?? 0\n const reasoning = usage.reasoningTokens ?? 0\n // Nothing spent, nothing compacted, no budget to show: stay out of the way.\n if (usage.totalTokens === 0 && !budget && compactions.length === 0 && !budgetTokens) {\n return null\n }\n const hitRate = usage.inputTokens > 0 ? Math.round((cached / usage.inputTokens) * 100) : 0\n const fill = budgetTokens ? Math.min(1, usage.totalTokens / budgetTokens) : undefined\n const last = compactions.at(-1)\n return (\n <div className={['awr-context', className].filter(Boolean).join(' ')}>\n <div className=\"awr-context__row\">\n <span title=\"input tokens\">in {formatTokens(usage.inputTokens)}</span>\n <span title=\"output tokens\">out {formatTokens(usage.outputTokens)}</span>\n {reasoning > 0 && <span title=\"thinking tokens\">think {formatTokens(reasoning)}</span>}\n <span title=\"input tokens served from the provider's prompt cache\">\n cached {formatTokens(cached)}\n {hitRate > 0 ? ` (${hitRate}%)` : ''}\n </span>\n {onCompact && (\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--ghost awr-context__compact\"\n onClick={onCompact}\n disabled={compacting}\n >\n {compacting ? 'Compacting…' : 'Compact'}\n </button>\n )}\n </div>\n {fill !== undefined && (\n <div\n className={`awr-context__track${fill >= 1 ? ' is-full' : ''}`}\n title={`${usage.totalTokens} / ${budgetTokens} tokens`}\n >\n <div className=\"awr-context__fill\" style={{ width: `${fill * 100}%` }} />\n </div>\n )}\n {budget && (\n <div className=\"awr-context__note awr-context__note--warn\">\n {budget.kind === 'tool-calls' ? 'Tool-call' : `${budget.kind} token`} limit reached (\n {budget.tokens}/{budget.cap}) — the agent stopped early.\n </div>\n )}\n {last && (\n <div className=\"awr-context__note\">\n Compacted {last.scope}: {formatTokens(last.beforeTokens)} →{' '}\n {formatTokens(last.afterTokens)} tokens\n </div>\n )}\n </div>\n )\n}\n","import { Fragment, useEffect, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { VirtualFileInfo, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { useVirtualFiles } from '../hooks/use-virtual-files.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { DownloadIcon, FileIcon, PlusIcon, XIcon } from './icons.js'\n\nexport interface FilesPanelProps {\n /** The workspace (the core's `VirtualFileSystem`). */\n files: VirtualFileSystem\n /** Only list paths under this prefix (default '/'). */\n prefix?: string\n title?: ReactNode\n /** Upload button (default true). */\n allowUpload?: boolean\n /** Delete buttons (default true). */\n allowDelete?: boolean\n /** Directory uploads go to (default '/uploads'). */\n uploadDir?: string\n /** Called when a file row is clicked (in addition to the preview). */\n onOpen?: (file: VirtualFileInfo) => void\n /** Render a row yourself; `fallback` is the built-in `<li>` — return it, or your own `<li>`. */\n renderFile?: (file: VirtualFileInfo, fallback: ReactNode) => ReactNode\n labels?: AgentLabelsOverride\n className?: string\n}\n\ntype Preview =\n { path: string; kind: 'image'; src: string } | { path: string; kind: 'text'; text: string }\n\nconst PREVIEW_CHARS = 20_000\n\n/**\n * The agent's workspace — attachments the user dropped in, files the agent\n * wrote with its `fs_*` tools — live, with a preview (text / image),\n * download, delete and upload.\n */\nexport const FilesPanel = ({\n files: vfs,\n prefix = '/',\n title,\n allowUpload = true,\n allowDelete = true,\n uploadDir,\n onOpen,\n renderFile,\n labels,\n className,\n}: FilesPanelProps) => {\n const L = useLabels(labels)\n const fs = useVirtualFiles(vfs, prefix)\n const [preview, setPreview] = useState<Preview | undefined>()\n const inputRef = useRef<HTMLInputElement>(null)\n\n // Drop a preview whose file went away.\n useEffect(() => {\n if (preview && !fs.files.some((f) => f.path === preview.path)) setPreview(undefined)\n }, [fs.files, preview])\n\n const open = async (f: VirtualFileInfo) => {\n onOpen?.(f)\n if (preview?.path === f.path) return setPreview(undefined)\n if (f.mimeType.startsWith('image/')) {\n const src = await fs.dataUrl(f.path)\n if (src) setPreview({ path: f.path, kind: 'image', src })\n return\n }\n const text = await fs.text(f.path)\n if (text !== undefined) setPreview({ path: f.path, kind: 'text', text })\n else setPreview(undefined)\n }\n\n const download = async (f: VirtualFileInfo) => {\n const href = await fs.dataUrl(f.path)\n if (!href) return\n const a = document.createElement('a')\n a.href = href\n a.download = f.path.split('/').pop() || 'file'\n a.click()\n }\n\n return (\n <div className={['awr-filespanel', className].filter(Boolean).join(' ')}>\n <div className=\"awr-panel__head\">\n <span className=\"awr-panel__title\">{title ?? L.files}</span>\n {allowUpload && (\n <>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.upload}\n title={L.upload}\n onClick={() => inputRef.current?.click()}\n >\n <PlusIcon size={16} />\n </button>\n <input\n ref={inputRef}\n type=\"file\"\n multiple\n hidden\n onChange={async (e) => {\n for (const f of Array.from(e.target.files ?? [])) await fs.upload(f, uploadDir)\n e.target.value = ''\n }}\n />\n </>\n )}\n </div>\n {fs.error && <div className=\"awr-notice awr-notice--warn\">{fs.error}</div>}\n {!fs.loading && fs.files.length === 0 && (\n <div className=\"awr-panel__empty\">{L.filesEmpty}</div>\n )}\n <ul className=\"awr-filelist\">\n {fs.files.map((f) => {\n const row = (\n <li\n key={f.path}\n className={`awr-filelist__item${preview?.path === f.path ? ' is-active' : ''}`}\n >\n <button\n type=\"button\"\n className=\"awr-filelist__open\"\n onClick={() => void open(f)}\n title={`${L.preview}: ${f.path}`}\n >\n <FileIcon size={14} />\n <span className=\"awr-filelist__path\">{f.path}</span>\n <span className=\"awr-filelist__size\">{L.bytes(f.size)}</span>\n </button>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={`${L.download} ${f.path}`}\n title={L.download}\n onClick={() => void download(f)}\n >\n <DownloadIcon size={14} />\n </button>\n {allowDelete && (\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={`${L.delete} ${f.path}`}\n title={L.delete}\n onClick={() => void fs.remove(f.path)}\n >\n <XIcon size={14} />\n </button>\n )}\n </li>\n )\n return renderFile ? <Fragment key={f.path}>{renderFile(f, row)}</Fragment> : row\n })}\n </ul>\n {preview && (\n <div className=\"awr-filepreview\">\n {preview.kind === 'image' ? (\n <img src={preview.src} alt={preview.path} />\n ) : (\n <pre>\n {preview.text.length > PREVIEW_CHARS\n ? `${preview.text.slice(0, PREVIEW_CHARS)}\\n…`\n : preview.text}\n </pre>\n )}\n </div>\n )}\n </div>\n )\n}\n","import { Fragment } from 'react'\nimport type { ReactNode } from 'react'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ApprovalView, StepView, SubagentView, ToolCallView, UserNoteView } from '../types.js'\nimport { formatDuration, formatTokens, imagesInOutput, previewValue } from './format.js'\nimport {\n AlertIcon,\n BotIcon,\n BrainIcon,\n CheckIcon,\n SendIcon,\n ShieldIcon,\n SpinnerIcon,\n StopIcon,\n ToolIcon,\n} from './icons.js'\n\n/** Render a tool call yourself; `fallback` is the built-in `<li>` row — return it, or your own `<li>`. */\nexport type RenderToolCall = (call: ToolCallView, fallback: ReactNode) => ReactNode\n\nexport interface ToolCallRowProps {\n call: ToolCallView\n showUsage?: boolean\n labels?: AgentLabelsOverride\n}\n\n/** One tool call: name, arguments, status — and optionally its cost and any images it returned. */\nexport const ToolCallRow = ({ call, showUsage = true, labels }: ToolCallRowProps) => {\n const L = useLabels(labels)\n const state = call.status === 'calling' ? 'calling' : call.ok === false ? 'failed' : 'ok'\n const images = call.ok === false ? [] : imagesInOutput(call.output).slice(0, 4)\n const cost = [\n call.inputTokens ? `≈${formatTokens(call.inputTokens)} in` : '',\n call.outputTokens ? `≈${formatTokens(call.outputTokens)} out` : '',\n call.durationMs !== undefined ? formatDuration(call.durationMs) : '',\n ]\n .filter(Boolean)\n .join(' · ')\n return (\n <li className={`awr-tool awr-tool--${state}`}>\n <div className=\"awr-tool__row\">\n <ToolIcon size={13} className=\"awr-tool__icon\" />\n <code className=\"awr-tool__name\">{call.name}</code>\n {previewValue(call.input) && (\n <span className=\"awr-tool__args\">{previewValue(call.input)}</span>\n )}\n {call.status === 'calling' && <SpinnerIcon size={12} className=\"awr-tool__spin\" />}\n {call.status === 'done' && call.ok === false && (\n <span className=\"awr-tool__badge\">{L.failed}</span>\n )}\n {showUsage && cost && (\n <span className=\"awr-tool__cost\" title={L.toolCostTitle}>\n {cost}\n </span>\n )}\n </div>\n {images.length > 0 && (\n <div className=\"awr-tool__images\">\n {images.map((src, i) => (\n <a key={i} href={src} target=\"_blank\" rel=\"noreferrer\">\n <img className=\"awr-thumb\" src={src} alt={`${call.name} result ${i + 1}`} />\n </a>\n ))}\n </div>\n )}\n </li>\n )\n}\n\n/**\n * A subagent delegation: name, task, live activity, and its answer when done. With\n * `onStop`, a running one gets a stop button (the run and its siblings go on).\n */\nexport const SubagentRow = ({\n sub,\n onStop,\n labels,\n}: {\n sub: SubagentView\n /** Stop this subagent (`useAgent().stopSubagent`); the button shows while it runs. */\n onStop?: (id: string) => void\n labels?: AgentLabelsOverride\n}) => {\n const L = useLabels(labels)\n return (\n <li className={`awr-subagent awr-subagent--${sub.status}`}>\n <div className=\"awr-subagent__head\">\n <BotIcon size={13} className=\"awr-subagent__icon\" />\n <span className=\"awr-subagent__name\">{sub.name}</span>\n {sub.profile && <span className=\"awr-subagent__profile\">{sub.profile}</span>}\n <span className=\"awr-subagent__task\" title={sub.task}>\n {previewValue(sub.task, 90)}\n </span>\n {sub.status === 'running' && <SpinnerIcon size={12} className=\"awr-tool__spin\" />}\n {sub.status === 'running' && onStop && (\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-subagent__stop\"\n aria-label={L.stopSubagent}\n title={L.stopSubagent}\n onClick={() => onStop(sub.id)}\n >\n <StopIcon size={12} />\n </button>\n )}\n </div>\n <div className=\"awr-subagent__activity\">\n {sub.status === 'error'\n ? sub.error\n : sub.status === 'stopped'\n ? L.subagentStopped\n : sub.status === 'done'\n ? previewValue(sub.text, 160)\n : `${sub.activity}${sub.toolCalls ? ` · ${L.toolCalls(sub.toolCalls)}` : ''}`}\n </div>\n </li>\n )\n}\n\n/** What the user said while the run was going, and where it reached the agent. */\nexport const UserNoteRow = ({\n note,\n labels,\n}: {\n note: UserNoteView\n labels?: AgentLabelsOverride\n}) => {\n const L = useLabels(labels)\n return (\n <li className={`awr-note awr-note--${note.at}`}>\n <SendIcon size={12} className=\"awr-note__icon\" />\n <span className=\"awr-note__where\">{L.noteAt[note.at]}</span>\n <q className=\"awr-note__text\">{note.text}</q>\n </li>\n )\n}\n\nconst decisionLabel = (a: ApprovalView, L: AgentLabels): string =>\n a.status === 'pending'\n ? L.consentWaiting\n : a.status === 'approved'\n ? L.consentAllowed\n : L.consentDenied(a.reason)\n\ninterface StepItemProps {\n step: StepView\n subagents: SubagentView[]\n approvals: ApprovalView[]\n notes: UserNoteView[]\n onStopSubagent?: (id: string) => void\n showToolCalls: boolean\n showUsage: boolean\n showThoughts: boolean\n renderToolCall?: RenderToolCall\n L: AgentLabels\n}\n\nconst StepItem = ({\n step,\n subagents,\n approvals,\n notes,\n onStopSubagent,\n showToolCalls,\n showUsage,\n showThoughts,\n renderToolCall,\n L,\n}: StepItemProps) => (\n <li className={`awr-step awr-step--${step.blocked ? 'blocked' : step.status}`}>\n <div className=\"awr-step__head\">\n <span className=\"awr-step__marker\">\n {step.status === 'running' ? (\n <SpinnerIcon size={14} />\n ) : step.blocked ? (\n <AlertIcon size={14} />\n ) : (\n <CheckIcon size={14} />\n )}\n </span>\n <span className=\"awr-step__index\">\n {step.index}/{step.total}\n </span>\n <span className=\"awr-step__desc\">{step.step.description}</span>\n </div>\n {showThoughts && step.reasoning.trim() && (\n <details className=\"awr-thought\" open={step.status === 'running' && !step.text}>\n <summary>\n <BrainIcon size={13} /> {L.stepThoughts}\n </summary>\n <p className=\"awr-thought__text\">{step.reasoning.trim()}</p>\n </details>\n )}\n {step.text.trim() && <p className=\"awr-step__text\">{step.text.trim()}</p>}\n {showToolCalls && step.toolCalls.length > 0 && (\n <ul className=\"awr-step__tools\">\n {step.toolCalls.map((call, i) => {\n const row = <ToolCallRow key={i} call={call} showUsage={showUsage} />\n return renderToolCall ? <Fragment key={i}>{renderToolCall(call, row)}</Fragment> : row\n })}\n </ul>\n )}\n {approvals.length > 0 && (\n <ul className=\"awr-step__tools\">\n {approvals.map((a) => (\n <li key={a.id} className={`awr-tool awr-tool__row awr-tool--approval-${a.status}`}>\n <ShieldIcon size={13} className=\"awr-tool__icon\" />\n <code className=\"awr-tool__name\">{a.name}</code>\n <span className=\"awr-tool__args\">{decisionLabel(a, L)}</span>\n </li>\n ))}\n </ul>\n )}\n {subagents.length > 0 && (\n <ul className=\"awr-subagents\">\n {subagents.map((sub) => (\n <SubagentRow key={sub.id} sub={sub} onStop={onStopSubagent} />\n ))}\n </ul>\n )}\n {notes.length > 0 && (\n <ul className=\"awr-notes\">\n {notes.map((n) => (\n <UserNoteRow key={n.id} note={n} />\n ))}\n </ul>\n )}\n {step.blocked && step.summary && <p className=\"awr-step__blocked\">{step.summary}</p>}\n </li>\n)\n\nexport interface StepListProps {\n steps: StepView[]\n /** Subagent delegations (`agent.subagents`) — shown under the step that made them. */\n subagents?: SubagentView[]\n /** Consent decisions (`agent.approvals`) — shown under their step. */\n approvals?: ApprovalView[]\n /** What the user said mid-run (`agent.notes`) — shown under the step it reached. */\n notes?: UserNoteView[]\n /** Show those notes (default true). */\n showNotes?: boolean\n /** Give a running subagent a stop button (`agent.stopSubagent`). */\n onStopSubagent?: (id: string) => void\n /** Show each tool call (default true). */\n showToolCalls?: boolean\n /** Show each tool call's ≈tokens and duration (default true). */\n showUsage?: boolean\n /** Show each step's thoughts when the model thinks (default true). */\n showThoughts?: boolean\n /** Render tool calls yourself (gets the built-in row as `fallback`). */\n renderToolCall?: RenderToolCall\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * The live execution: each step, its thoughts, streamed text, tool calls,\n * consent decisions and subagent delegations.\n */\nexport const StepList = ({\n steps,\n subagents = [],\n approvals = [],\n notes = [],\n showNotes = true,\n onStopSubagent,\n showToolCalls = true,\n showUsage = true,\n showThoughts = true,\n renderToolCall,\n labels,\n className,\n}: StepListProps) => {\n const L = useLabels(labels)\n if (steps.length === 0) return null\n const known = new Set(steps.map((s) => s.id))\n // A note tied to a step shows under it; one said before the answer (or whose step is\n // gone) shows at the end.\n const atEnd = showNotes ? notes.filter((n) => !n.stepId || !known.has(n.stepId)) : []\n return (\n <ol className={['awr-steps', className].filter(Boolean).join(' ')}>\n {steps.map((step) => (\n <StepItem\n key={step.id}\n step={step}\n subagents={subagents.filter((s) => s.stepId === step.id)}\n approvals={approvals.filter((a) => a.stepId === step.id && a.status !== 'pending')}\n notes={showNotes ? notes.filter((n) => n.stepId === step.id) : []}\n onStopSubagent={onStopSubagent}\n showToolCalls={showToolCalls}\n showUsage={showUsage}\n showThoughts={showThoughts}\n renderToolCall={renderToolCall}\n L={L}\n />\n ))}\n {atEnd.length > 0 && (\n <li className=\"awr-step awr-step--notes\">\n <ul className=\"awr-notes\">\n {atEnd.map((n) => (\n <UserNoteRow key={n.id} note={n} />\n ))}\n </ul>\n </li>\n )}\n </ol>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { IUsage } from '@dudko.dev/agent-web'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ChatAttachment, ChatMessage } from '../types.js'\nimport { formatDuration, formatTokens } from './format.js'\nimport { BrainIcon, FileIcon, SpinnerIcon } from './icons.js'\nimport { StepList, type RenderToolCall } from './StepList.js'\n\nexport interface MessageListProps {\n messages: ChatMessage[]\n /** Rendered when there are no messages yet. */\n empty?: ReactNode\n /** Each answer's steps, thoughts, subagents and consent decisions (default true). */\n showActivity?: boolean\n /** Each tool call inside the activity (default true). */\n showToolCalls?: boolean\n /** Tokens per answer and per tool call (default true). */\n showUsage?: boolean\n /** Thoughts (step + answer) when the model thinks (default true). */\n showThoughts?: boolean\n /** What the user said while the agent worked, under the step it reached (default true). */\n showNotes?: boolean\n /** Give a running subagent a stop button (`useAgent().stopSubagent`). */\n onStopSubagent?: (id: string) => void\n /** Open the activity of finished answers too (default: only while it runs). */\n activityOpen?: boolean\n /** Extra content under the latest assistant turn while it streams (plan thought, …). */\n liveExtra?: ReactNode\n /**\n * A message's text — e.g. through your markdown renderer. Default: plain\n * text, line breaks kept.\n */\n renderContent?: (message: ChatMessage) => ReactNode\n /** A whole message; `fallback` is the built-in one, to wrap or ignore. */\n renderMessage?: (message: ChatMessage, fallback: ReactNode) => ReactNode\n /** An attachment shown with a message (thumbnail / chip by default). */\n renderAttachment?: (attachment: ChatAttachment, message: ChatMessage) => ReactNode\n /** Tool calls inside the activity. */\n renderToolCall?: RenderToolCall\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/** \"in 12k · out 456 · think 120 · cached 9k · 4.2 s\" for one answer. */\nexport const usageLine = (usage: IUsage | undefined, durationMs?: number): string => {\n const parts: string[] = []\n if (usage && usage.totalTokens > 0) {\n parts.push(`in ${formatTokens(usage.inputTokens)}`, `out ${formatTokens(usage.outputTokens)}`)\n if (usage.reasoningTokens) parts.push(`think ${formatTokens(usage.reasoningTokens)}`)\n if (usage.cachedInputTokens) parts.push(`cached ${formatTokens(usage.cachedInputTokens)}`)\n }\n if (durationMs !== undefined) parts.push(formatDuration(durationMs))\n return parts.join(' · ')\n}\n\n/** The built-in attachment: an image thumbnail (opens full size) or a file chip. */\nexport const AttachmentView = ({ attachment: a }: { attachment: ChatAttachment }) =>\n a.dataUrl && a.mediaType.startsWith('image/') ? (\n <a href={a.dataUrl} target=\"_blank\" rel=\"noreferrer\" title={a.path ?? a.name}>\n <img className=\"awr-thumb awr-thumb--msg\" src={a.dataUrl} alt={a.name} />\n </a>\n ) : (\n <span className=\"awr-chip awr-file\" title={a.path ?? a.mediaType}>\n <FileIcon size={13} /> {a.name}\n </span>\n )\n\nconst toolCallCount = (m: ChatMessage): number =>\n (m.steps ?? []).reduce((n, s) => n + s.toolCalls.length, 0)\n\nconst activitySummary = (m: ChatMessage, showToolCalls: boolean, L: AgentLabels): string => {\n const steps = m.steps ?? []\n const parts = [L.steps(steps.length)]\n if (showToolCalls) parts.push(L.toolCalls(toolCallCount(m)))\n if (m.subagents?.length) parts.push(L.subagents(m.subagents.length))\n if (m.skills?.length) parts.push(L.skillsUsed(m.skills.join(', ')))\n return parts.join(' · ')\n}\n\n/**\n * The chat transcript. User turns show their text and attachments (image\n * thumbnails, file chips); every assistant turn keeps its own activity — the\n * steps with each tool call (≈tokens, duration, returned images), thoughts,\n * subagents, consent decisions — and the tokens it spent by kind. Every part\n * can be hidden, relabelled or rendered by the host.\n */\nexport const MessageList = ({\n messages,\n empty,\n showActivity = true,\n showToolCalls = true,\n showUsage = true,\n showThoughts = true,\n showNotes = true,\n onStopSubagent,\n activityOpen = false,\n liveExtra,\n renderContent,\n renderMessage,\n renderAttachment,\n renderToolCall,\n labels,\n className,\n}: MessageListProps) => {\n const L = useLabels(labels)\n if (messages.length === 0) {\n return empty ? <div className=\"awr-messages__empty\">{empty}</div> : null\n }\n return (\n <div className={['awr-messages', className].filter(Boolean).join(' ')}>\n {messages.map((m) => {\n const steps = m.steps ?? []\n const hasActivity =\n showActivity &&\n (steps.length > 0 || (m.subagents?.length ?? 0) > 0 || (m.pending && !!liveExtra))\n const usage = showUsage ? usageLine(m.usage, m.durationMs) : ''\n const node = (\n <div\n key={m.id}\n className={`awr-msg awr-msg--${m.role}${m.error ? ' awr-msg--error' : ''}${m.pending ? ' is-pending' : ''}`}\n >\n <div className=\"awr-msg__col\">\n {m.role === 'assistant' && hasActivity && (\n <details className=\"awr-activity\" open={m.pending || activityOpen}>\n <summary className=\"awr-activity__summary\">\n {activitySummary(m, showToolCalls, L)}\n </summary>\n {m.pending && liveExtra}\n <StepList\n steps={steps}\n subagents={m.subagents}\n approvals={m.approvals}\n notes={m.notes}\n showNotes={showNotes}\n onStopSubagent={m.pending ? onStopSubagent : undefined}\n showToolCalls={showToolCalls}\n showUsage={showUsage}\n showThoughts={showThoughts}\n renderToolCall={renderToolCall}\n labels={labels}\n />\n {showThoughts && m.reasoning?.trim() && (\n <details className=\"awr-thought\">\n <summary>\n <BrainIcon size={13} /> {L.answerThoughts}\n </summary>\n <p className=\"awr-thought__text\">{m.reasoning.trim()}</p>\n </details>\n )}\n </details>\n )}\n {(m.content || m.pending || !m.attachments?.length) && (\n <div className=\"awr-msg__bubble\">\n {m.content ? (renderContent ? renderContent(m) : m.content) : null}\n {m.pending && !m.content && (\n <SpinnerIcon size={14} className=\"awr-msg__pending\" />\n )}\n </div>\n )}\n {m.attachments?.length ? (\n <div className=\"awr-msg__attachments\" aria-label={L.attachments}>\n {m.attachments.map((a, i) => (\n <span key={i} className=\"awr-msg__attachment\">\n {renderAttachment ? (\n renderAttachment(a, m)\n ) : (\n <AttachmentView attachment={a} />\n )}\n </span>\n ))}\n </div>\n ) : null}\n {m.role === 'assistant' && usage && !m.pending && (\n <div className=\"awr-msg__usage\" title={L.usageTitle}>\n {usage}\n </div>\n )}\n </div>\n </div>\n )\n return renderMessage ? <div key={m.id}>{renderMessage(m, node)}</div> : node\n })}\n </div>\n )\n}\n","import type { ModelLoadState } from '../types.js'\n\nexport interface ModelLoadBarProps {\n load: ModelLoadState\n className?: string\n}\n\n/** A progress bar for WebLLM weight download / engine init (0..1). */\nexport const ModelLoadBar = ({ load, className }: ModelLoadBarProps) => {\n const pct = Math.round(Math.max(0, Math.min(1, load.progress)) * 100)\n return (\n <div className={['awr-modelload', className].filter(Boolean).join(' ')}>\n <div className=\"awr-modelload__head\">\n <span className=\"awr-modelload__text\">{load.text || 'Loading model…'}</span>\n <span className=\"awr-modelload__pct\">{pct}%</span>\n </div>\n <div className=\"awr-modelload__track\" role=\"progressbar\" aria-valuenow={pct}>\n <div className=\"awr-modelload__fill\" style={{ width: `${pct}%` }} />\n </div>\n </div>\n )\n}\n","import type { ReactNode } from 'react'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ApprovalView } from '../types.js'\nimport { previewValue } from './format.js'\nimport { ShieldIcon } from './icons.js'\n\nexport interface ToolApprovalPromptProps {\n /** Pending requests (e.g. `agent.pendingApprovals`). */\n approvals: ApprovalView[]\n onApprove: (id: string, options?: { remember?: boolean }) => void\n onDeny: (id: string, reason?: string) => void\n /** Offer \"Always allow\" (remembers the tool for the agent's life). Default true. */\n allowRemember?: boolean\n /** Render a request yourself (gets the built-in card as `fallback`). */\n renderApproval?: (approval: ApprovalView, fallback: ReactNode) => ReactNode\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * Consent cards for tool calls the agent wants to make — \"Allow once\",\n * \"Always allow\" and \"Deny\". Wire it to {@link useAgent}'s `pendingApprovals`,\n * `approve` and `deny`; `<AgentChat>` renders it for you.\n */\nexport const ToolApprovalPrompt = ({\n approvals,\n onApprove,\n onDeny,\n allowRemember = true,\n renderApproval,\n labels,\n className,\n}: ToolApprovalPromptProps) => {\n const L = useLabels(labels)\n if (approvals.length === 0) return null\n return (\n <div className={['awr-approvals', className].filter(Boolean).join(' ')} role=\"alert\">\n {approvals.map((a) => {\n const card = (\n <div key={a.id} className=\"awr-approval\">\n <div className=\"awr-approval__head\">\n <ShieldIcon size={14} className=\"awr-approval__icon\" />\n <span>\n {L.approvalLead} <code className=\"awr-tool__name\">{a.name}</code>\n {a.readOnly ? ` (${L.readOnlyTool})` : ''}\n </span>\n </div>\n {previewValue(a.input, 300) && (\n <pre className=\"awr-approval__input\">{previewValue(a.input, 300)}</pre>\n )}\n <div className=\"awr-approval__actions\">\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--primary\"\n onClick={() => onApprove(a.id)}\n >\n {L.approve}\n </button>\n {allowRemember && (\n <button\n type=\"button\"\n className=\"awr-btn\"\n onClick={() => onApprove(a.id, { remember: true })}\n >\n {L.alwaysAllow}\n </button>\n )}\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--danger\"\n onClick={() => onDeny(a.id, L.declinedReason)}\n >\n {L.deny}\n </button>\n </div>\n </div>\n )\n return renderApproval ? <div key={a.id}>{renderApproval(a, card)}</div> : card\n })}\n </div>\n )\n}\n","import type { IUsage } from '@dudko.dev/agent-web'\nimport { formatTokens } from './format.js'\n\nexport interface UsageBadgeProps {\n usage: IUsage\n /** Only in ↑ out ↓ (the rest stays in the tooltip) — for tight headers. */\n compact?: boolean\n className?: string\n}\n\n/**\n * A compact token-usage readout: in ↑ out ↓, plus thinking (🧠) and cache-hit\n * tokens when the provider reported any. The full breakdown is on hover.\n */\nexport const UsageBadge = ({ usage, compact = false, className }: UsageBadgeProps) => {\n if (usage.totalTokens === 0) return null\n const reasoning = usage.reasoningTokens ?? 0\n const cached = usage.cachedInputTokens ?? 0\n const title = [\n `${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`,\n reasoning ? `${reasoning} thinking` : '',\n cached ? `${cached} input tokens from the prompt cache` : '',\n ]\n .filter(Boolean)\n .join(' · ')\n return (\n <span className={['awr-usage', className].filter(Boolean).join(' ')} title={title}>\n {formatTokens(usage.inputTokens)}↑ {formatTokens(usage.outputTokens)}↓\n {!compact && reasoning > 0 && ` · ${formatTokens(reasoning)} think`}\n {!compact && cached > 0 && ` · ${formatTokens(cached)} cached`}\n </span>\n )\n}\n","import { useState } from 'react'\nimport type { KeyboardEvent } from 'react'\nimport { SendIcon, SpinnerIcon, StopIcon } from './icons.js'\n\nexport interface ComposerProps {\n /** Called with the trimmed text when the user submits. */\n onSubmit: (text: string) => void\n /** A run is in flight — show a stop button instead of send. */\n busy?: boolean\n /** Called when the stop button is pressed (only shown while `busy`). */\n onStop?: () => void\n /** Disable input (e.g. while the agent is still initializing). */\n disabled?: boolean\n placeholder?: string\n className?: string\n}\n\n/** A textarea + send/stop button. Enter submits; Shift+Enter inserts a newline. */\nexport const Composer = ({\n onSubmit,\n busy = false,\n onStop,\n disabled = false,\n placeholder = 'Ask the agent to do something…',\n className,\n}: ComposerProps) => {\n const [text, setText] = useState('')\n\n const submit = () => {\n const value = text.trim()\n if (!value || busy || disabled) return\n setText('')\n onSubmit(value)\n }\n\n const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault()\n submit()\n }\n }\n\n return (\n <form\n className={['awr-composer', className].filter(Boolean).join(' ')}\n onSubmit={(e) => {\n e.preventDefault()\n submit()\n }}\n >\n <textarea\n className=\"awr-composer__input\"\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={onKeyDown}\n placeholder={placeholder}\n disabled={disabled}\n rows={1}\n />\n {busy ? (\n <button\n type=\"button\"\n className=\"awr-composer__btn awr-composer__btn--stop\"\n onClick={onStop}\n aria-label=\"Stop\"\n >\n <StopIcon size={18} />\n </button>\n ) : (\n <button\n type=\"submit\"\n className=\"awr-composer__btn\"\n disabled={disabled || !text.trim()}\n aria-label=\"Send\"\n >\n {disabled ? <SpinnerIcon size={18} /> : <SendIcon size={18} />}\n </button>\n )}\n </form>\n )\n}\n","import type { IPlan } from '@dudko.dev/agent-web'\n\nexport interface PlanViewProps {\n plan: IPlan\n /** Also render the planner's reasoning (\"thought\"). Default true. */\n showThought?: boolean\n className?: string\n}\n\n/** The plan the agent produced: its reasoning and the ordered step list. */\nexport const PlanView = ({ plan, showThought = true, className }: PlanViewProps) => {\n if (!plan.steps.length && !plan.thought) return null\n return (\n <div className={['awr-plan', className].filter(Boolean).join(' ')}>\n {showThought && plan.thought.trim() && <p className=\"awr-plan__thought\">{plan.thought}</p>}\n {plan.steps.length > 0 && (\n <ol className=\"awr-plan__steps\">\n {plan.steps.map((step) => (\n <li key={step.id} className=\"awr-plan__step\">\n {step.description}\n </li>\n ))}\n </ol>\n )}\n </div>\n )\n}\n","import type { ToolApprovalMode } from '@dudko.dev/agent-web'\n\nexport interface ApprovalModeSwitchProps {\n mode: ToolApprovalMode\n onChange: (mode: ToolApprovalMode) => void\n /** Which modes to offer, in order (default: all four). */\n modes?: ToolApprovalMode[]\n /** Override the button labels. */\n labels?: Partial<Record<ToolApprovalMode, string>>\n disabled?: boolean\n className?: string\n}\n\nconst DEFAULT_LABELS: Record<ToolApprovalMode, string> = {\n autopilot: 'Autopilot',\n 'ask-writes': 'Ask before changes',\n 'ask-all': 'Ask always',\n 'read-only': 'Read-only',\n}\n\nconst HINTS: Record<ToolApprovalMode, string> = {\n autopilot: 'Run every tool without asking',\n 'ask-writes': 'Run read-only tools freely; ask before anything that may change state',\n 'ask-all': 'Ask before every tool call',\n 'read-only': 'Run read-only tools; refuse everything else without asking',\n}\n\n/**\n * A segmented control for the tool-consent policy — the \"autopilot\" switch.\n * Pair it with {@link useAgent}'s `approvalMode` / `setApprovalMode`.\n */\nexport const ApprovalModeSwitch = ({\n mode,\n onChange,\n modes = ['autopilot', 'ask-writes', 'ask-all', 'read-only'],\n labels,\n disabled,\n className,\n}: ApprovalModeSwitchProps) => (\n <div\n className={['awr-modeswitch', className].filter(Boolean).join(' ')}\n role=\"radiogroup\"\n aria-label=\"Tool consent\"\n >\n {modes.map((m) => (\n <button\n key={m}\n type=\"button\"\n role=\"radio\"\n aria-checked={mode === m}\n title={HINTS[m]}\n className={`awr-modeswitch__opt${mode === m ? ' is-active' : ''}`}\n onClick={() => onChange(m)}\n disabled={disabled}\n >\n {labels?.[m] ?? DEFAULT_LABELS[m]}\n </button>\n ))}\n </div>\n)\n","import { useEffect, useState } from 'react'\nimport type { UseCredentialsReturn } from '../hooks/use-credentials.js'\nimport { CheckIcon } from './icons.js'\n\nexport interface ApiKeyFormProps {\n /** The value returned by {@link useCredentials}. */\n credentials: UseCredentialsReturn\n /** The ref id under which the key is stored (matches your `credentialRef`). */\n credentialRef: string\n label?: string\n placeholder?: string\n /** Called after a key is saved or removed (e.g. to `reload()` the agent). */\n onChange?: (present: boolean) => void\n className?: string\n}\n\n/**\n * A BYOK key input that stores the key **encrypted at rest** via\n * {@link useCredentials}. Shows a \"saved\" state when a key already exists and\n * lets the user replace or remove it. The plaintext key never leaves the form.\n */\nexport const ApiKeyForm = ({\n credentials,\n credentialRef,\n label = 'API key',\n placeholder = 'sk-…',\n onChange,\n className,\n}: ApiKeyFormProps) => {\n const [value, setValue] = useState('')\n const [present, setPresent] = useState(false)\n const [busy, setBusy] = useState(false)\n\n useEffect(() => {\n let active = true\n credentials.hasKey(credentialRef).then((has) => {\n if (active) setPresent(has)\n })\n return () => {\n active = false\n }\n }, [credentials, credentialRef, credentials.version])\n\n const save = async () => {\n const key = value.trim()\n if (!key) return\n setBusy(true)\n try {\n await credentials.setKey(credentialRef, key)\n setValue('')\n setPresent(true)\n onChange?.(true)\n } finally {\n setBusy(false)\n }\n }\n\n const remove = async () => {\n setBusy(true)\n try {\n await credentials.removeKey(credentialRef)\n setPresent(false)\n onChange?.(false)\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <div className={['awr-keyform', className].filter(Boolean).join(' ')}>\n <label className=\"awr-keyform__label\">\n {label}\n {present && (\n <span className=\"awr-keyform__saved\">\n <CheckIcon size={12} /> stored, encrypted\n </span>\n )}\n </label>\n <div className=\"awr-keyform__row\">\n <input\n className=\"awr-keyform__input\"\n type=\"password\"\n autoComplete=\"off\"\n value={value}\n placeholder={present ? '•••••••• (replace)' : placeholder}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n void save()\n }\n }}\n disabled={busy}\n />\n <button\n type=\"button\"\n className=\"awr-keyform__btn\"\n onClick={() => void save()}\n disabled={busy || !value.trim()}\n >\n Save\n </button>\n {present && (\n <button\n type=\"button\"\n className=\"awr-keyform__btn awr-keyform__btn--ghost\"\n onClick={() => void remove()}\n disabled={busy}\n >\n Remove\n </button>\n )}\n </div>\n </div>\n )\n}\n","// ── Hooks ────────────────────────────────────────────────────────────────────\nexport { useAgent } from './hooks/use-agent.js'\nexport type {\n ApproveOptions,\n RunGoalOptions,\n UseAgentOptions,\n UseAgentReturn,\n} from './hooks/use-agent.js'\nexport { useChatHistory } from './hooks/use-chat-history.js'\nexport type { UseChatHistoryOptions, UseChatHistoryReturn } from './hooks/use-chat-history.js'\nexport { useVirtualFiles } from './hooks/use-virtual-files.js'\nexport type { UseVirtualFilesReturn } from './hooks/use-virtual-files.js'\nexport { useSpeechToText } from './hooks/use-speech-to-text.js'\nexport type {\n UseSpeechToTextOptions,\n UseSpeechToTextReturn,\n SpeechRecognizerLike,\n} from './hooks/use-speech-to-text.js'\nexport { useCredentials } from './hooks/use-credentials.js'\nexport type { UseCredentialsReturn } from './hooks/use-credentials.js'\nexport { createWebLLMEngine, useWebLLMModel } from './hooks/use-webllm-model.js'\nexport { useLocalModel } from './hooks/use-local-model.js'\nexport type {\n LocalModelEngine,\n LocalModelLoadContext,\n LocalModelProgress,\n UseLocalModelOptions,\n UseLocalModelReturn,\n} from './hooks/use-local-model.js'\nexport type {\n UseWebLLMModelReturn,\n UseWebLLMModelOptions,\n WebLLMModelFactory,\n} from './hooks/use-webllm-model.js'\n\n// ── Chat history, labels (i18n), composer helpers, images ────────────────────\nexport { ChatHistoryStore, chatTitle, newChatId } from './chat-history.js'\nexport type { ChatRecord, ChatSummary, ChatHistoryStoreOptions } from './chat-history.js'\nexport { AgentLabelsProvider, defaultLabels, mergeLabels, useLabels } from './labels.js'\nexport type { AgentLabels, AgentLabelsOverride, AgentLabelsProviderProps } from './labels.js'\nexport {\n parseSlash,\n filterCommands,\n attachmentKindOf,\n withAttachments,\n attachmentRefusal,\n formatElapsed,\n noticesOf,\n steerIntent,\n} from './composer.js'\nexport type {\n SlashCommand,\n ComposerAttachment,\n ComposerNotice,\n NoticeTexts,\n SteerIntent,\n} from './composer.js'\nexport { downscaleImage } from './image-resize.js'\nexport type { DownscaleOptions } from './image-resize.js'\n\n// ── Context ──────────────────────────────────────────────────────────────────\nexport { AgentProvider, useAgentContext, useOptionalAgentContext } from './context.js'\nexport type { AgentProviderProps } from './context.js'\n\n// ── Headless state (the pure event → UI reducer, for custom UIs) ─────────────\nexport { agentStateReducer, createInitialAgentState } from './state.js'\nexport type { AgentAction } from './state.js'\nexport type {\n AgentUiState,\n AgentStatus,\n QueuedMessageView,\n UserNoteView,\n ApprovalView,\n BudgetView,\n ChatAttachment,\n ChatMessage,\n CompactionView,\n StepView,\n SubagentView,\n ToolCallView,\n ModelLoadState,\n ReplanState,\n} from './types.js'\n\n// ── Components (optional, pre-styled — import '@dudko.dev/agent-web-react/styles.css') ─\nexport { AgentChat } from './components/AgentChat.js'\nexport type {\n AgentChatProps,\n AgentChatSlots,\n AgentChatComponents,\n AgentChatClassNames,\n} from './components/AgentChat.js'\nexport { AgentComposer } from './components/AgentComposer.js'\nexport type {\n AgentComposerProps,\n ComposerModelChip,\n ComposerThinkingChip,\n ConvertedFile,\n} from './components/AgentComposer.js'\nexport { MessageList, AttachmentView, usageLine } from './components/MessageList.js'\nexport type { MessageListProps } from './components/MessageList.js'\nexport { ChatHistoryList } from './components/ChatHistoryList.js'\nexport type { ChatHistoryListProps } from './components/ChatHistoryList.js'\nexport { FilesPanel } from './components/FilesPanel.js'\nexport type { FilesPanelProps } from './components/FilesPanel.js'\nexport { Composer } from './components/Composer.js'\nexport type { ComposerProps } from './components/Composer.js'\nexport { PlanView } from './components/PlanView.js'\nexport type { PlanViewProps } from './components/PlanView.js'\nexport { StepList, SubagentRow, ToolCallRow, UserNoteRow } from './components/StepList.js'\nexport type { StepListProps, ToolCallRowProps, RenderToolCall } from './components/StepList.js'\nexport { ToolApprovalPrompt } from './components/ToolApprovalPrompt.js'\nexport type { ToolApprovalPromptProps } from './components/ToolApprovalPrompt.js'\nexport { ApprovalModeSwitch } from './components/ApprovalModeSwitch.js'\nexport type { ApprovalModeSwitchProps } from './components/ApprovalModeSwitch.js'\nexport { ContextMeter } from './components/ContextMeter.js'\nexport type { ContextMeterProps } from './components/ContextMeter.js'\nexport { ModelLoadBar } from './components/ModelLoadBar.js'\nexport type { ModelLoadBarProps } from './components/ModelLoadBar.js'\nexport { UsageBadge } from './components/UsageBadge.js'\nexport type { UsageBadgeProps } from './components/UsageBadge.js'\nexport { ApiKeyForm } from './components/ApiKeyForm.js'\nexport type { ApiKeyFormProps } from './components/ApiKeyForm.js'\n\n// ── Convenience re-exports from the core (a peer dep), so a React app can\n// import the agent primitives it needs from one place. ──────────────────────\nexport {\n createAgent,\n defineTool,\n defineSkill,\n parseSkillMarkdown,\n loadSkillFromUrl,\n createRunControl,\n createSubagentTool,\n serveSubagentWorker,\n markReadOnly,\n createWebLLMModel,\n preloadWebLLMModel,\n unloadWebLLMModel,\n isWebGPUAvailable,\n VaultCredentialStore,\n MemoryCredentialStore,\n MemoryStore,\n IndexedDBStore,\n VirtualFileSystem,\n createFileTools,\n AttachmentsNotSupportedError,\n ImagesNotSupportedError,\n supportsImages,\n supportsPdf,\n} from '@dudko.dev/agent-web'\nexport type {\n Agent,\n RunControl,\n RunOptions,\n RunResult,\n SubagentInfo,\n BrowserAgentConfig,\n AgentEvent,\n AgentEventHandler,\n AgentTool,\n AgentToolSet,\n CredentialStore,\n ProviderModelSpec,\n ProviderType,\n ModelInput,\n LogLevel,\n AgentLoggerSink,\n IPlan,\n IPlanStep,\n IStepResult,\n IToolCall,\n IUsage,\n Skill,\n ThinkingSetting,\n ThinkingLevel,\n TokenLimits,\n CompactionConfig,\n CompactResult,\n ToolApprovalConfig,\n ToolApprovalMode,\n ToolApprovalRequest,\n SubagentToolOptions,\n SubagentWorkerConfig,\n RunFile,\n VirtualFile,\n VirtualFileInfo,\n FileToolsOptions,\n} from '@dudko.dev/agent-web'\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,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K;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,OAAO;AAAA,UAC3B,UAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OAEJ;AAAA,KACF;AAEJ;;;ACWA;AAAA,EACE,eAAAI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,sBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["base","m","req","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect","useCallback","useEffect","useState","useCallback","useEffect","useRef","useState","useCallback","useMemo","useState","useCallback","useRef","useState","useState","useRef","model","useCallback","useMemo","base","useMemo","createContext","useContext","jsx","createContext","useContext","useEffect","useRef","useState","useEffect","useMemo","useRef","useState","jsx","jsx","jsx","jsxs","useEffect","useState","readDataUrl","useRef","useMemo","Fragment","jsx","jsxs","Fragment","jsx","jsxs","Fragment","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useEffect","Fragment","jsx","jsxs","Fragment","jsx","jsxs","jsx","jsxs","jsx","jsxs","jsxs","Fragment","jsx","jsxs","useState","useRef","useEffect","Composer","useState","jsx","jsxs","useState","jsx","jsxs","jsx","useEffect","useState","jsx","jsxs","useState","useEffect","createAgent","createRunControl","createWebLLMModel","preloadWebLLMModel","unloadWebLLMModel","isWebGPUAvailable","VaultCredentialStore"]}
1
+ {"version":3,"sources":["../src/hooks/use-agent.ts","../src/state.ts","../src/util.ts","../src/hooks/use-chat-history.ts","../src/chat-history.ts","../src/hooks/use-virtual-files.ts","../src/hooks/use-speech-to-text.ts","../src/hooks/use-credentials.ts","../src/hooks/use-webllm-model.ts","../src/hooks/use-local-model.ts","../src/labels.tsx","../src/composer.ts","../src/image-resize.ts","../src/context.tsx","../src/components/AgentChat.tsx","../src/components/AgentComposer.tsx","../src/components/icons.tsx","../src/components/ChatHistoryList.tsx","../src/components/format.ts","../src/components/ContextMeter.tsx","../src/components/FilesPanel.tsx","../src/components/StepList.tsx","../src/components/MessageList.tsx","../src/components/ModelLoadBar.tsx","../src/components/ToolApprovalPrompt.tsx","../src/components/UsageBadge.tsx","../src/components/LearnedSkills.tsx","../src/components/Composer.tsx","../src/components/PlanView.tsx","../src/components/ApprovalModeSwitch.tsx","../src/components/ApiKeyForm.tsx","../src/index.ts"],"sourcesContent":["import { useCallback, useEffect, useReducer, useRef, useState } from 'react'\nimport type { DependencyList } from 'react'\nimport {\n createAgent,\n createRunControl,\n type IUsage,\n type Agent,\n type AgentEventHandler,\n type BrowserAgentConfig,\n type CompactResult,\n type RunControl,\n type RunFile,\n type RunResult,\n type ToolApprovalDecision,\n type ToolApprovalMode,\n type ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\nimport { agentStateReducer, createInitialAgentState, lessonsOf } from '../state.js'\nimport type { AgentUiState, ApprovalView, ChatAttachment, ChatMessage } from '../types.js'\nimport { errMessage } from '../util.js'\n\nexport interface UseAgentOptions {\n /**\n * Rebuild the agent when any of these values change — compared like a\n * `useEffect` dependency array (so it must keep a stable length across\n * renders). Default: build once on mount. Bump this when you switch\n * model/provider so a fresh agent is constructed with the new config.\n *\n * Keep dynamic config (`tools`, `describeState`) referentially stable across\n * renders (e.g. via `useRef`/`useCallback`) so it survives without a rebuild.\n */\n deps?: DependencyList\n /** Invoked for every raw agent event, after the internal reducer folds it. */\n onEvent?: AgentEventHandler\n /** Build the agent immediately on mount (default `true`). */\n autoStart?: boolean\n /** Cap the retained raw event log length (default 200; 0 = unbounded). */\n maxEvents?: number\n /**\n * Route tool-consent requests into the hook (`pendingApprovals`, `approve`,\n * `deny`) when the config has no `toolApproval.onRequest` of its own\n * (default true). Render them with `<ToolApprovalPrompt>`, or your own UI.\n */\n approvals?: boolean\n /**\n * What the run never showed the agent — a message sent while the answer was being\n * written — is sent as the next message, once the run has ended (default true).\n * A run the user stopped never does this: those messages stay in `undelivered`\n * for the UI to offer (`sendUndelivered` / `discardUndelivered`).\n */\n followUp?: boolean\n}\n\nexport interface ApproveOptions {\n /** Also allow this tool for the rest of the agent's life (\"always allow\"). */\n remember?: boolean\n}\n\nexport interface RunGoalOptions {\n /**\n * What the transcript shows for this turn when it differs from what the\n * agent receives — e.g. the typed text without the attached files' contents.\n */\n label?: string\n /** Images sent to the model with the goal (vision models; see `agent.capabilities`). */\n images?: RunFile[]\n /** PDFs / files / URLs sent to the model with the goal. */\n files?: RunFile[]\n /** What the transcript shows as attached to this turn (thumbnails, chips). */\n attachments?: ChatAttachment[]\n}\n\nexport interface UseAgentReturn extends AgentUiState {\n /** Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. */\n run: (goal: string, options?: RunGoalOptions) => Promise<RunResult | undefined>\n /** Abort the in-flight run (observed between phases and mid-stream). */\n stop: () => void\n /**\n * Say something to the agent while it works. It is shown to the model at the next\n * boundary (between tool calls, or when the step ends — where the replanner then\n * re-checks the plan), never cutting a tool call short. `false` when no run is in\n * flight or the text is empty — then use `run`. Watch `queued` / `notes`.\n */\n send: (text: string) => boolean\n /** Stop ONE running subagent (`SubagentView.id`); the run and its siblings go on. */\n stopSubagent: (id: string) => boolean\n /**\n * Delete one of the agent's own lessons (`learned`), e.g. one gone stale. Resolves false when\n * there is no such lesson (or no agent yet). Needs `config.learning`.\n */\n forgetSkill: (name: string) => Promise<boolean>\n /** Send the `undelivered` messages (a stopped run's leftovers) as a new message. */\n sendUndelivered: () => void\n /** Drop the `undelivered` messages. */\n discardUndelivered: () => void\n /** Clear the whole conversation — transcript, current run, and the agent's memory. */\n reset: () => void\n /** Rebuild the agent now (e.g. after the user stores a new API key). */\n reload: () => void\n /** The built agent, once ready. */\n agent: Agent | undefined\n isRunning: boolean\n isReady: boolean\n /** Tool calls waiting for the user's consent. */\n pendingApprovals: ApprovalView[]\n /** Let a pending call run (`remember` → never ask for this tool again). */\n approve: (id: string, options?: ApproveOptions) => void\n /** Refuse a pending call; the model is told and works around it. */\n deny: (id: string, reason?: string) => void\n /** The consent policy in effect. */\n approvalMode: ToolApprovalMode\n /** Switch the consent policy live — the \"autopilot\" toggle. */\n setApprovalMode: (mode: ToolApprovalMode) => void\n /** Summarise the stored transcript now (needs `config.memory`). */\n compact: () => Promise<CompactResult | undefined>\n /** The memory session runs use (config.sessionId until switched). */\n sessionId: string\n /**\n * Switch to another conversation: its id becomes the memory session of the\n * next runs, and its saved transcript (chat history) is shown.\n */\n loadChat: (chat: { sessionId: string; messages?: ChatMessage[]; totalUsage?: IUsage }) => void\n}\n\n/**\n * The primary React binding for `@dudko.dev/agent-web`. Builds the agent from a\n * {@link BrowserAgentConfig}, streams its typed events into a renderable\n * {@link AgentUiState} (plan, steps, tool calls, thoughts, consent requests,\n * subagents, streamed final answer, token usage, model-load progress and a chat\n * transcript), and exposes `run` / `stop` / `reset` / `reload` plus consent\n * (`approve` / `deny` / `setApprovalMode`) and `compact`.\n *\n * ```tsx\n * const agent = useAgent({\n * model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },\n * credentials,\n * tools,\n * toolApproval: { mode: 'ask-writes' }, // requests land in agent.pendingApprovals\n * })\n * // <button disabled={!agent.isReady} onClick={() => agent.run(text)}>Run</button>\n * ```\n */\nexport const useAgent = (\n config: BrowserAgentConfig,\n options: UseAgentOptions = {},\n): UseAgentReturn => {\n const [state, dispatch] = useReducer(agentStateReducer, undefined, createInitialAgentState)\n const agentRef = useRef<Agent | undefined>(undefined)\n const abortRef = useRef<AbortController | undefined>(undefined)\n // The in-flight run's control: how `send` and `stopSubagent` reach it.\n const controlRef = useRef<RunControl | undefined>(undefined)\n const stateRef = useRef(state)\n stateRef.current = state\n const [generation, setGeneration] = useState(0)\n\n // Keep the latest callbacks/config without forcing an agent rebuild.\n const configRef = useRef(config)\n configRef.current = config\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n // Consent requests waiting for approve()/deny(), by request id.\n const resolversRef = useRef(new Map<string, (d: ToolApprovalDecision) => void>())\n const settleAll = useCallback((decision: ToolApprovalDecision) => {\n for (const resolve of resolversRef.current.values()) resolve(decision)\n resolversRef.current.clear()\n }, [])\n const uiOnRequest = useCallback(\n (req: ToolApprovalRequest) =>\n new Promise<ToolApprovalDecision>((resolve) => {\n resolversRef.current.set(req.id, resolve)\n }),\n [],\n )\n\n // The memory session runs go to; a chat-history switch changes it.\n const [sessionId, setSessionId] = useState(config.sessionId ?? 'default')\n const sessionRef = useRef(sessionId)\n sessionRef.current = sessionId\n\n const configMode = config.toolApproval?.mode ?? 'autopilot'\n const [approvalMode, setApprovalModeState] = useState<ToolApprovalMode>(configMode)\n const modeRef = useRef<ToolApprovalMode>(configMode)\n\n const setApprovalMode = useCallback((mode: ToolApprovalMode) => {\n modeRef.current = mode\n agentRef.current?.setToolApprovalMode(mode)\n setApprovalModeState(mode)\n }, [])\n\n // The config's mode is the source of truth when IT changes; applied live.\n useEffect(() => {\n if (configMode !== modeRef.current) setApprovalMode(configMode)\n }, [configMode, setApprovalMode])\n\n const reload = useCallback(() => setGeneration((g) => g + 1), [])\n\n // The build's own status. A rebuild while a run is in flight (a setting\n // changed mid-run) must not flip the UI out of 'running': the run keeps the\n // agent it started with, and the new one takes the next run.\n type BuildStatus = { status: 'idle' | 'initializing' | 'ready' | 'error'; error?: string }\n const buildStatusRef = useRef<BuildStatus>({ status: 'idle' })\n const setBuildStatus = useCallback((next: BuildStatus) => {\n buildStatusRef.current = next\n if (!abortRef.current) dispatch({ type: 'status', ...next })\n }, [])\n\n // Build (and rebuild) the agent. Model resolution is async (dynamic provider\n // imports, vault key fetch, WebLLM weight download), so this lives in effect.\n const { autoStart, deps } = options\n useEffect(() => {\n // Any dep change invalidates the current agent first.\n agentRef.current = undefined\n const cfg = configRef.current\n // Skip building until we're asked to (autoStart / reload) and actually have\n // a model — a local WebGPU model may still be downloading (config.model\n // undefined), in which case we sit idle rather than build a broken agent.\n const shouldBuild = (autoStart !== false || generation > 0) && Boolean(cfg.model)\n if (!shouldBuild) {\n setBuildStatus({ status: 'idle' })\n return\n }\n // Consent requests come to the hook unless the host handles them itself.\n const routeApprovals = optionsRef.current.approvals !== false && !cfg.toolApproval?.onRequest\n const built: BrowserAgentConfig = routeApprovals\n ? {\n ...cfg,\n toolApproval: { ...cfg.toolApproval, mode: modeRef.current, onRequest: uiOnRequest },\n }\n : cfg\n let cancelled = false\n setBuildStatus({ status: 'initializing' })\n createAgent(built)\n .then((agent) => {\n if (cancelled) return\n agent.setToolApprovalMode(modeRef.current)\n agentRef.current = agent\n // The notebook belongs to the agent just built: what its store brought back (or nothing).\n dispatch({ type: 'notebook', lessons: lessonsOf(agent.listLearnedSkills()) })\n setBuildStatus({ status: 'ready' })\n })\n .catch((err) => {\n if (cancelled) return\n setBuildStatus({ status: 'error', error: errMessage(err) })\n })\n return () => {\n cancelled = true\n }\n // `config` is intentionally excluded: rebuilds are driven only by `deps` /\n // reload(), so a new config object every render doesn't churn the agent.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [generation, autoStart, ...(deps ?? [])])\n\n // Abort any in-flight run (and release waiting consent requests) on unmount.\n useEffect(\n () => () => {\n abortRef.current?.abort()\n settleAll({ approved: false, reason: 'the view was closed' })\n },\n [settleAll],\n )\n\n // `run` calls itself (the follow-up of a run), so it is reached through a ref.\n const runRef = useRef<\n ((goal: string, runOptions?: RunGoalOptions) => Promise<RunResult | undefined>) | undefined\n >(undefined)\n\n const run = useCallback(\n async (goal: string, runOptions?: RunGoalOptions): Promise<RunResult | undefined> => {\n const agent = agentRef.current\n if (!agent || abortRef.current) return undefined // not ready, or already running\n const controller = new AbortController()\n abortRef.current = controller\n const control = createRunControl()\n controlRef.current = control\n // What the run never showed the agent; read once it is over.\n let left: string[] = []\n dispatch({ type: 'status', status: 'running' })\n try {\n const result = await agent.run(goal, {\n signal: controller.signal,\n control,\n sessionId: sessionRef.current,\n ...(runOptions?.images?.length ? { images: runOptions.images } : {}),\n ...(runOptions?.files?.length ? { files: runOptions.files } : {}),\n onEvent: (event) => {\n const start = event.type === 'run.start'\n const shown = start && runOptions?.label ? { ...event, goal: runOptions.label } : event\n dispatch({\n type: 'event',\n event: shown,\n maxEvents: optionsRef.current.maxEvents,\n at: Date.now(),\n ...(start && runOptions?.attachments?.length\n ? { attachments: runOptions.attachments }\n : {}),\n })\n try {\n optionsRef.current.onEvent?.(event)\n } catch {\n /* a bad host handler must not break the run */\n }\n },\n })\n left = result.undelivered ?? []\n return result\n } catch (err) {\n left = control.pending()\n dispatch({\n type: 'event',\n event: { type: 'error', phase: 'run', error: errMessage(err) },\n maxEvents: optionsRef.current.maxEvents,\n })\n return undefined\n } finally {\n abortRef.current = undefined\n controlRef.current = undefined\n settleAll({ approved: false, reason: 'the run ended' })\n // Whatever the agent did meanwhile: rebuilt, still building, or gone.\n dispatch({ type: 'status', ...buildStatusRef.current })\n if (left.length > 0) {\n if (!controller.signal.aborted && optionsRef.current.followUp !== false) {\n // Said too late for this run: just send it next.\n dispatch({ type: 'undelivered', texts: [] })\n void runRef.current?.(left.join('\\n\\n'))\n } else {\n dispatch({ type: 'undelivered', texts: left })\n }\n } else {\n dispatch({ type: 'undelivered', texts: [] })\n }\n }\n },\n [settleAll],\n )\n runRef.current = run\n\n const send = useCallback((text: string): boolean => controlRef.current?.send(text) ?? false, [])\n const stopSubagent = useCallback(\n (id: string): boolean => controlRef.current?.stopSubagent(id) ?? false,\n [],\n )\n const sendUndelivered = useCallback(() => {\n const texts = stateRef.current.undelivered\n if (texts.length === 0) return\n dispatch({ type: 'undelivered', texts: [] })\n void runRef.current?.(texts.join('\\n\\n'))\n }, [])\n const discardUndelivered = useCallback(() => dispatch({ type: 'undelivered', texts: [] }), [])\n\n const stop = useCallback(() => {\n abortRef.current?.abort()\n settleAll({ approved: false, reason: 'stopped by the user' })\n }, [settleAll])\n\n const reset = useCallback(() => {\n dispatch({ type: 'reset' })\n // \"New conversation\" means the agent forgets it too, not just the view.\n void configRef.current.memory?.clear(sessionRef.current).catch(() => {})\n }, [])\n\n const loadChat = useCallback(\n (chat: { sessionId: string; messages?: ChatMessage[]; totalUsage?: IUsage }) => {\n abortRef.current?.abort()\n sessionRef.current = chat.sessionId\n setSessionId(chat.sessionId)\n dispatch({ type: 'load', messages: chat.messages ?? [], totalUsage: chat.totalUsage })\n },\n [],\n )\n\n const forgetSkill = useCallback(async (name: string): Promise<boolean> => {\n const agent = agentRef.current\n if (!agent) return false\n return agent.forgetSkill(name, (event) =>\n dispatch({ type: 'event', event, maxEvents: optionsRef.current.maxEvents, at: Date.now() }),\n )\n }, [])\n\n const approve = useCallback((id: string, opts?: ApproveOptions) => {\n const resolve = resolversRef.current.get(id)\n if (!resolve) return\n resolversRef.current.delete(id)\n resolve({ approved: true, remember: opts?.remember })\n }, [])\n\n const deny = useCallback((id: string, reason?: string) => {\n const resolve = resolversRef.current.get(id)\n if (!resolve) return\n resolversRef.current.delete(id)\n resolve({ approved: false, reason })\n }, [])\n\n const compact = useCallback(async (): Promise<CompactResult | undefined> => {\n const agent = agentRef.current\n if (!agent) return undefined\n const result = await agent.compact({ sessionId: sessionRef.current })\n if (result.compacted) {\n dispatch({\n type: 'event',\n event: {\n type: 'context.compacted',\n scope: 'history',\n beforeTokens: result.beforeTokens,\n afterTokens: result.afterTokens,\n },\n maxEvents: optionsRef.current.maxEvents,\n at: Date.now(),\n })\n }\n return result\n }, [])\n\n return {\n ...state,\n run,\n stop,\n send,\n stopSubagent,\n forgetSkill,\n sendUndelivered,\n discardUndelivered,\n reset,\n reload,\n agent: agentRef.current,\n isRunning: state.status === 'running',\n isReady: state.status === 'ready',\n pendingApprovals: state.approvals.filter((a) => a.status === 'pending'),\n approve,\n deny,\n approvalMode,\n setApprovalMode,\n compact,\n sessionId,\n loadChat,\n }\n}\n","import type { AgentEvent, IUsage, Skill } from '@dudko.dev/agent-web'\nimport type {\n AgentUiState,\n ApprovalView,\n ChatAttachment,\n ChatMessage,\n LessonView,\n StepView,\n SubagentView,\n ToolCallView,\n} from './types.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 }\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[] }\n\ninterface EventContext {\n at?: number\n attachments?: ChatAttachment[]\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\nconst addUsage = (a: IUsage, b: IUsage): 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\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. */\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})\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\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 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 }\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/** 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\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.\n const base = resetRun(state)\n const userId = `msg-${base.seq}`\n const assistantId = `msg-${base.seq + 1}`\n return {\n ...base,\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.attachments?.length ? { attachments: ctx.attachments } : {}),\n },\n { id: assistantId, role: 'assistant', content: '', pending: true },\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 }\n return { ...state, steps: [...state.steps, view] }\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 steps: patchStep(state.steps, event.step.id, (s) => ({ ...s, text: s.text + event.delta })),\n }\n\n case 'step.tool-call': {\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 }\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 ...(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 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 }\n })\n })(),\n })),\n }\n\n case 'replan.decision':\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n },\n }\n\n case 'message.queued':\n return state.queued.some((q) => q.id === event.id)\n ? state\n : { ...state, queued: [...state.queued, { id: event.id, text: event.text }] }\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 { id: event.id, text: event.text, at: event.at, ...(anchor ? { stepId: anchor } : {}) },\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 return {\n ...state,\n usage: addUsage(state.usage, event.usage),\n totalUsage: addUsage(state.totalUsage, event.usage),\n }\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 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 ...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 return {\n ...state,\n subagents: [\n ...state.subagents,\n {\n id: event.id,\n name: event.name,\n task: event.task,\n status: 'running',\n ...(event.profile ? { profile: event.profile } : {}),\n stepId: runningStepId(state.steps),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n },\n ],\n }\n\n case 'subagent.event':\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) =>\n applySubagentEvent(s, event.event),\n ),\n }\n\n case 'subagent.complete':\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({\n ...s,\n status: 'done',\n activity: 'done',\n text: event.text,\n usage: event.usage,\n })),\n }\n\n case 'subagent.error':\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({\n ...s,\n status: event.stopped ? 'stopped' : 'error',\n activity: event.stopped ? 'stopped' : 'failed',\n error: event.error,\n })),\n }\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 'stopped':\n return {\n ...state,\n stopped: true,\n // Nothing is waiting any more once the run has stopped.\n approvals: state.approvals.map((a) =>\n a.status === 'pending' ? { ...a, status: 'denied' as const, reason: 'stopped' } : a,\n ),\n messages: finalizeAssistant(\n state.messages,\n state.finalText || 'Stopped.',\n runDuration(state, ctx.at),\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 return event.phase === 'run'\n ? {\n ...state,\n error: event.error,\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 const decided = state.approvals.filter((a) => a.status !== 'pending')\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 (\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\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 'status':\n return {\n ...state,\n status: action.status,\n error: action.status === 'error' ? action.error : undefined,\n }\n case 'event': {\n const next = syncRunMessage(\n applyEvent(state, action.event, { at: action.at, attachments: action.attachments }),\n )\n const cap = action.maxEvents ?? 200\n const events =\n cap > 0 ? [...state.events, action.event].slice(-cap) : [...state.events, action.event]\n return { ...next, events }\n }\n case 'undelivered':\n return { ...state, queued: [], undelivered: action.texts }\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","/** Normalize any thrown value into a message string. */\nexport const errMessage = (err: unknown): string =>\n err instanceof Error ? err.message : String(err)\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n ChatHistoryStore,\n chatTitle,\n newChatId,\n type ChatRecord,\n type ChatSummary,\n} from '../chat-history.js'\nimport type { UseAgentReturn } from './use-agent.js'\n\nexport interface UseChatHistoryOptions {\n /** Where chats are saved (default: a ChatHistoryStore on IndexedDB). */\n store?: ChatHistoryStore\n /** Switch the hook off (keeps hook order stable in components). Default true. */\n enabled?: boolean\n /** Open the most recent chat on mount (default true). */\n resumeLatest?: boolean\n}\n\nexport interface UseChatHistoryReturn {\n chats: ChatSummary[]\n /** The open conversation (the agent's memory session). */\n currentId: string\n loading: boolean\n /** Open a saved conversation. */\n select: (id: string) => Promise<void>\n /** Start an empty conversation. */\n newChat: () => void\n /** Delete a conversation (and start a new one if it was open). */\n remove: (id: string) => Promise<void>\n}\n\n/**\n * Persist an agent's conversations — the transcript with its tool calls, usage\n * and image attachments — and switch between them. Each chat id is also the\n * agent's memory session, so with a persistent `memory` (IndexedDBStore) a\n * reopened chat continues with the model's context intact.\n */\nexport const useChatHistory = (\n agent: UseAgentReturn,\n options: UseChatHistoryOptions = {},\n): UseChatHistoryReturn => {\n const enabled = options.enabled !== false\n const store = useMemo(() => options.store ?? new ChatHistoryStore(), [options.store])\n const [chats, setChats] = useState<ChatSummary[]>([])\n const [loading, setLoading] = useState(enabled)\n const createdRef = useRef(new Map<string, number>())\n const agentRef = useRef(agent)\n agentRef.current = agent\n\n const refresh = useCallback(async () => {\n try {\n setChats(await store.list())\n } catch {\n /* storage unavailable: history simply stays empty */\n }\n }, [store])\n\n const newChat = useCallback(() => {\n agentRef.current.loadChat({ sessionId: newChatId(), messages: [] })\n }, [])\n\n const select = useCallback(\n async (id: string) => {\n const record = await store.get(id).catch(() => undefined)\n if (!record) return\n createdRef.current.set(id, record.createdAt)\n agentRef.current.loadChat({\n sessionId: record.id,\n messages: record.messages,\n totalUsage: record.totalUsage,\n })\n },\n [store],\n )\n\n const remove = useCallback(\n async (id: string) => {\n await store.delete(id).catch(() => {})\n if (id === agentRef.current.sessionId) newChat()\n await refresh()\n },\n [store, newChat, refresh],\n )\n\n // On mount: open the latest chat, or start a fresh one.\n useEffect(() => {\n if (!enabled) return\n let active = true\n void (async () => {\n const list = await store.list().catch(() => [] as ChatSummary[])\n if (!active) return\n setChats(list)\n if (options.resumeLatest !== false && list[0]) await select(list[0].id)\n else newChat()\n setLoading(false)\n })()\n return () => {\n active = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [enabled, store])\n\n // Save the open chat whenever its transcript settles (not on every streamed token).\n const { messages, totalUsage, sessionId, isRunning } = agent\n useEffect(() => {\n if (!enabled || loading || isRunning || messages.length === 0) return\n const now = Date.now()\n const createdAt = createdRef.current.get(sessionId) ?? now\n createdRef.current.set(sessionId, createdAt)\n const record: ChatRecord = {\n id: sessionId,\n title: chatTitle(messages),\n createdAt,\n updatedAt: now,\n messages,\n totalUsage,\n }\n void store\n .put(record)\n .then(refresh)\n .catch(() => {})\n }, [enabled, loading, isRunning, messages, totalUsage, sessionId, store, refresh])\n\n return { chats, currentId: sessionId, loading, select, newChat, remove }\n}\n","import type { IUsage } from '@dudko.dev/agent-web'\nimport type { 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/** IndexedDB-backed chat history (raw IndexedDB — no extra dependency). */\nexport class ChatHistoryStore {\n private readonly dbName: 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.dbName = opts.dbName ?? 'agent-web-react'\n this.storeName = opts.storeName ?? 'chats'\n if (opts.memory || typeof indexedDB === 'undefined') this.memory = new Map()\n }\n\n private open(): Promise<IDBDatabase> {\n this.db ??= new Promise<IDBDatabase>((resolve, reject) => {\n const r = indexedDB.open(this.dbName, 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 = () => resolve(r.result)\n r.onerror = () => reject(r.error)\n }).catch((err: unknown) => {\n this.db = undefined\n throw err\n })\n return this.db\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 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 req((await this.tx('readwrite')).put(record))\n }\n\n async delete(id: string): Promise<void> {\n if (this.memory) {\n this.memory.delete(id)\n return\n }\n await req((await this.tx('readwrite')).delete(id))\n }\n\n async clear(): Promise<void> {\n if (this.memory) {\n this.memory.clear()\n return\n }\n await req((await this.tx('readwrite')).clear())\n }\n}\n\n/** A chat's title: its first user message, trimmed. */\nexport const chatTitle = (messages: ChatMessage[]): string => {\n const first = messages\n .find((m) => m.role === 'user')\n ?.content.replace(/\\s+/g, ' ')\n .trim()\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","import { useCallback, useEffect, useState } from 'react'\nimport type { VirtualFileInfo, VirtualFileSystem } from '@dudko.dev/agent-web'\n\nexport interface UseVirtualFilesReturn {\n files: VirtualFileInfo[]\n loading: boolean\n error?: string\n refresh: () => Promise<void>\n /** Save a browser File (text as text, anything else as base64). */\n upload: (file: File, dir?: string) => Promise<void>\n remove: (path: string) => Promise<void>\n /** A data URL of a file (for previews and downloads). */\n dataUrl: (path: string) => Promise<string | undefined>\n /** A text file's content. */\n text: (path: string) => Promise<string | undefined>\n}\n\nconst readDataUrl = (file: Blob): Promise<string> =>\n new Promise((resolve, reject) => {\n const r = new FileReader()\n r.onload = () => resolve(String(r.result))\n r.onerror = () => reject(r.error ?? new Error('could not read the file'))\n r.readAsDataURL(file)\n })\n\n/**\n * A live listing of a {@link VirtualFileSystem} (the core's browser\n * workspace): re-reads on every write / delete — by the user or by the agent's\n * `fs_*` tools — and offers upload / remove / read helpers. Headless: render\n * it with `<FilesPanel>` or your own UI.\n */\nexport const useVirtualFiles = (\n vfs: VirtualFileSystem | undefined,\n prefix = '/',\n): UseVirtualFilesReturn => {\n const [files, setFiles] = useState<VirtualFileInfo[]>([])\n const [loading, setLoading] = useState(Boolean(vfs))\n const [error, setError] = useState<string | undefined>()\n\n const refresh = useCallback(async () => {\n if (!vfs) return\n try {\n setFiles(await vfs.list(prefix))\n setError(undefined)\n } catch (err) {\n setError(err instanceof Error ? err.message : String(err))\n } finally {\n setLoading(false)\n }\n }, [vfs, prefix])\n\n useEffect(() => {\n if (!vfs) return\n void refresh()\n return vfs.onChange(() => void refresh())\n }, [vfs, refresh])\n\n const upload = useCallback(\n async (file: File, dir = '/uploads') => {\n if (!vfs) return\n const path = `${dir.replace(/\\/$/, '')}/${file.name.replace(/[^\\w.-]+/g, '_') || 'file'}`\n const type = file.type || 'application/octet-stream'\n if (type.startsWith('text/') || /json|xml|yaml|markdown|csv/.test(type)) {\n await vfs.write(path, await file.text(), { mimeType: type })\n } else {\n await vfs.writeDataUrl(path, await readDataUrl(file))\n }\n },\n [vfs],\n )\n\n const remove = useCallback(\n async (path: string) => {\n await vfs?.delete(path)\n },\n [vfs],\n )\n\n const dataUrl = useCallback(async (path: string) => vfs?.readDataUrl(path), [vfs])\n const text = useCallback(\n async (path: string) => {\n const f = await vfs?.read(path)\n return f && f.encoding === 'utf8' ? f.content : undefined\n },\n [vfs],\n )\n\n return { files, loading, error, refresh, upload, remove, dataUrl, text }\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\n\n/** The slice of the Web Speech API recognizer this hook 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 onerror: ((ev: { error?: string }) => void) | null\n onend: (() => void) | null\n}\n\ninterface SpeechResultEventLike {\n resultIndex: number\n results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>\n}\n\nexport interface UseSpeechToTextOptions {\n /** BCP-47 language (default: the page's `navigator.language`). */\n lang?: string\n /** Keep listening across pauses until stopped (default true). */\n continuous?: boolean\n /**\n * Build your own recognizer (e.g. a fully local Whisper/WebGPU one) instead\n * of the browser's `SpeechRecognition`.\n */\n createRecognizer?: () => SpeechRecognizerLike\n /** Final text chunks, as they are recognized. */\n onFinal?: (text: string) => void\n}\n\nexport interface UseSpeechToTextReturn {\n /** The browser (or your `createRecognizer`) can do speech-to-text. */\n supported: boolean\n listening: boolean\n /** Words heard but not final yet (for a live preview). */\n interim: string\n error?: string\n start: () => void\n stop: () => void\n toggle: () => void\n}\n\nconst browserRecognizer = (): (() => SpeechRecognizerLike) | undefined => {\n const g = globalThis as unknown as {\n SpeechRecognition?: new () => SpeechRecognizerLike\n webkitSpeechRecognition?: new () => SpeechRecognizerLike\n }\n const Ctor = g.SpeechRecognition ?? g.webkitSpeechRecognition\n return Ctor ? () => new Ctor() : undefined\n}\n\n/**\n * Speech-to-text in the browser via the Web Speech API (`SpeechRecognition`,\n * prefixed in Chrome/Safari). Note that Chrome sends the audio to its own\n * recognition service; pass `createRecognizer` for an on-device engine.\n */\nexport const useSpeechToText = (options: UseSpeechToTextOptions = {}): UseSpeechToTextReturn => {\n const optionsRef = useRef(options)\n optionsRef.current = options\n const factory = options.createRecognizer ?? browserRecognizer()\n const [listening, setListening] = useState(false)\n const [interim, setInterim] = useState('')\n const [error, setError] = useState<string | undefined>()\n const recRef = useRef<SpeechRecognizerLike | undefined>(undefined)\n\n const stop = useCallback(() => {\n recRef.current?.stop()\n }, [])\n\n const start = useCallback(() => {\n if (!factory || recRef.current) return\n const rec = factory()\n rec.lang =\n optionsRef.current.lang ??\n (typeof navigator !== 'undefined' ? navigator.language : undefined) ??\n 'en-US'\n rec.continuous = optionsRef.current.continuous !== false\n rec.interimResults = true\n rec.onresult = (ev) => {\n let pending = ''\n for (let i = ev.resultIndex; i < ev.results.length; i += 1) {\n const r = ev.results[i]\n if (r.isFinal) optionsRef.current.onFinal?.(r[0].transcript.trim())\n else pending += r[0].transcript\n }\n setInterim(pending)\n }\n rec.onerror = (ev) => {\n // \"no-speech\" / \"aborted\" are routine; anything else is worth showing.\n if (ev.error && ev.error !== 'no-speech' && ev.error !== 'aborted') setError(ev.error)\n }\n rec.onend = () => {\n recRef.current = undefined\n setListening(false)\n setInterim('')\n }\n recRef.current = rec\n setError(undefined)\n try {\n rec.start()\n setListening(true)\n } catch (err) {\n recRef.current = undefined\n setError(err instanceof Error ? err.message : String(err))\n }\n }, [factory])\n\n useEffect(() => () => recRef.current?.abort?.(), [])\n\n return {\n supported: Boolean(factory),\n listening,\n interim,\n error,\n start,\n stop,\n toggle: () => (recRef.current ? stop() : start()),\n }\n}\n","import { useCallback, useMemo, useState } from 'react'\nimport { VaultCredentialStore, type CredentialStore } from '@dudko.dev/agent-web'\n\nexport interface UseCredentialsReturn {\n /** The underlying store — pass this straight to `createAgent({ credentials })`. */\n store: CredentialStore\n /** Store (encrypted at rest) an API key under a ref id. */\n setKey: (ref: string, key: string) => Promise<void>\n /** Remove a stored key. */\n removeKey: (ref: string) => Promise<void>\n /** Resolve whether a key is currently present for a ref. */\n hasKey: (ref: string) => Promise<boolean>\n /**\n * Bumped whenever a key is written or removed — depend on it in an effect to\n * re-query `hasKey` and reflect the change in your UI.\n */\n version: number\n}\n\n/**\n * Manage BYOK API keys in the agent's encrypted vault (WebCrypto AES-GCM key in\n * IndexedDB). Defaults to a fresh {@link VaultCredentialStore}; pass your own\n * {@link CredentialStore} (e.g. a short-lived-token fetcher) to override.\n *\n * ```tsx\n * const creds = useCredentials()\n * // await creds.setKey('openai', userInput)\n * // <AgentProvider config={{ model, credentials: creds.store }}>…\n * ```\n */\nexport const useCredentials = (store?: CredentialStore): UseCredentialsReturn => {\n const resolved = useMemo<CredentialStore>(() => store ?? new VaultCredentialStore(), [store])\n const [version, setVersion] = useState(0)\n\n const setKey = useCallback(\n async (ref: string, key: string) => {\n await resolved.setApiKey(ref, key)\n setVersion((v) => v + 1)\n },\n [resolved],\n )\n\n const removeKey = useCallback(\n async (ref: string) => {\n await resolved.deleteApiKey(ref)\n setVersion((v) => v + 1)\n },\n [resolved],\n )\n\n const hasKey = useCallback(\n async (ref: string) => (await resolved.getApiKey(ref)) !== undefined,\n [resolved],\n )\n\n return { store: resolved, setKey, removeKey, hasKey, version }\n}\n","import {\n createWebLLMModel,\n isWebGPUAvailable,\n preloadWebLLMModel,\n unloadWebLLMModel,\n webLLMContextWindow,\n type WebLLMModelOptions,\n} from '@dudko.dev/agent-web'\nimport {\n useLocalModel,\n type LocalModelEngine,\n type UseLocalModelReturn,\n} from './use-local-model.js'\n\n/** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */\ntype WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>\n\n/**\n * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's\n * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.\n */\nexport type WebLLMModelFactory = (\n modelId: string,\n options?: WebLLMModelOptions,\n) => Promise<WebLLMModel>\n\nexport interface UseWebLLMModelOptions extends WebLLMModelOptions {\n /**\n * Override how the model is built. **Bundled browser apps (Vite, Next, …)\n * usually need this**: the core builds WebLLM via `await import('@browser-ai/\n * web-llm')`, and a bundler frequently stubs that dynamic import to an empty\n * module — the failure surfaces as `webLLM is not a function`. Pass a factory\n * that imports `webLLM` statically so the bundler includes it:\n *\n * ```ts\n * import { webLLM } from '@browser-ai/web-llm'\n * const create = (id, opts) => Promise.resolve(webLLM(id, opts))\n * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })\n * ```\n *\n * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.\n */\n create?: WebLLMModelFactory\n}\n\n/** What {@link useWebLLMModel} returns — {@link UseLocalModelReturn} for a WebLLM model. */\nexport type UseWebLLMModelReturn = UseLocalModelReturn<WebLLMModel>\n\n/**\n * Load a local WebGPU model with WebLLM and track its download progress —\n * {@link useLocalModel} with the WebLLM engine. Nothing downloads until you\n * call `load()` (models are large), so you can gate it behind a user action.\n * `load()` eagerly initializes the engine (via the core's\n * `preloadWebLLMModel`), so `ready` means \"ready to chat\" and progress fills\n * during the load rather than silently on the first message.\n *\n * Everything it reports is about the **current** `modelId`: switch the id and\n * `model` / `ready` / `progress` / `error` describe the new one (not loaded\n * yet), while the previous model stays in memory — switching back is instant.\n * Loading the new id frees the previous one first, so two models never hold\n * GPU memory at once; `unload()` frees it on demand.\n *\n * WebLLM loads its models with a 4096-token window; pass `contextWindowTokens`\n * to load with more (Qwen3, Llama 3.x take far more — it costs KV-cache VRAM,\n * not a new download). A different window is a different load.\n *\n * ```tsx\n * import { webLLM } from '@browser-ai/web-llm' // your app's optional peer\n * const create = (id: string, opts?: WebLLMModelOptions) => Promise.resolve(webLLM(id, opts))\n * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })\n * // <button disabled={!local.supported || local.loading} onClick={local.load}>Load</button>\n * // {local.loading && <ModelLoadBar load={{ progress: local.progress, text: local.text }} />}\n * // local.ready && <AgentProvider config={{ model: local.model! }}>…\n * ```\n */\nexport const useWebLLMModel = (\n modelId: string,\n options?: UseWebLLMModelOptions,\n): UseWebLLMModelReturn =>\n useLocalModel(modelId, createWebLLMEngine(options), {\n contextWindowTokens: options?.contextWindowTokens,\n })\n\n/**\n * The WebLLM {@link LocalModelEngine}: what {@link useWebLLMModel} runs, for\n * hosts that switch between local runtimes with one {@link useLocalModel}\n * (pass the window to that hook's `contextWindowTokens`).\n */\nexport const createWebLLMEngine = (\n options?: UseWebLLMModelOptions,\n): LocalModelEngine<WebLLMModel> => {\n // The window comes per load (useLocalModel's option), not from here.\n const {\n create = createWebLLMModel,\n contextWindowTokens: _perLoad,\n ...modelOptions\n } = options ?? {}\n return {\n create: (id, ctx) =>\n create(id, {\n ...modelOptions,\n ...(ctx.contextWindowTokens ? { contextWindowTokens: ctx.contextWindowTokens } : {}),\n // Drive preload in warmUp (below) so download progress is reported the\n // same way whether `create` is the core's `createWebLLMModel` or an\n // injected factory (e.g. a statically-imported `webLLM`, needed under\n // bundlers).\n preload: false,\n initProgressCallback: (report) => {\n ctx.onProgress({ progress: report.progress, text: report.text })\n modelOptions.initProgressCallback?.(report)\n },\n }),\n // Download the weights + init the engine now via the core's helper (a\n // 1-token warm-up). WebLLM builds are otherwise lazy — the ~GB download\n // would only start on the first `run()`, long after we told the UI the\n // model is \"ready\". Fast + idempotent once the weights are cached.\n warmUp: (model) => preloadWebLLMModel(model),\n unload: unloadWebLLMModel,\n supported: isWebGPUAvailable,\n unsupportedMessage: 'WebGPU is not available in this browser.',\n contextWindowOf: webLLMContextWindow,\n }\n}\n","import { useCallback, useRef, useState } from 'react'\nimport type { createWebLLMModel } from '@dudko.dev/agent-web'\nimport { errMessage } from '../util.js'\n\n/** An AI SDK `LanguageModel` (the type, via the core — no `ai` import here). */\ntype LanguageModel = Awaited<ReturnType<typeof createWebLLMModel>>\n\n/** Download / initialisation progress of a local model. */\nexport interface LocalModelProgress {\n /** 0..1. */\n progress: number\n /** Human-readable status from the runtime. */\n text: string\n}\n\n/** What `create` and `warmUp` are given. */\nexport interface LocalModelLoadContext {\n /** Report progress; the hook shows it for the load in flight only. */\n onProgress: (report: LocalModelProgress) => void\n /** The window to load the model with, when the host asked for one. */\n contextWindowTokens?: number\n}\n\n/**\n * How to run one kind of on-device model — WebLLM, the browser's built-in\n * model (`@browser-ai/core`), transformers.js (`@browser-ai/transformers-js`),\n * or your own. Only `create` is required.\n */\nexport interface LocalModelEngine<M extends LanguageModel = LanguageModel> {\n /** Build the model (cheap: the download starts in `warmUp`). */\n create: (modelId: string, ctx: LocalModelLoadContext) => Promise<M>\n /**\n * Download the weights and initialise now, so `ready` means \"ready to chat\"\n * and the progress shows during the load (default: nothing — the runtime\n * then loads on the first message).\n */\n warmUp?: (model: M, ctx: LocalModelLoadContext) => Promise<void>\n /** Free the model's memory (default: nothing). */\n unload?: (model: M) => Promise<void>\n /** Whether this browser can run it at all (default true). */\n supported?: () => boolean\n /** The error a load reports when `supported()` is false. */\n unsupportedMessage?: string\n /** The model's context window once loaded, when the runtime says. */\n contextWindowOf?: (model: M) => number | undefined\n}\n\nexport interface UseLocalModelOptions {\n /**\n * The window to load the model with (WebLLM loads with 4096 unless told\n * otherwise). A different window is a different load.\n */\n contextWindowTokens?: number\n}\n\nexport interface UseLocalModelReturn<M extends LanguageModel = LanguageModel> {\n /**\n * The built model, once **this** `modelId` is loaded — pass to\n * `createAgent({ model })`. Undefined right after the id changes, until the\n * new one is loaded.\n */\n model: M | undefined\n /**\n * Download and initialize the current `modelId`. Resolves with the model\n * already loaded for it, if any. Loading another id first frees the previous\n * model's memory (one model per hook); call again after an error to retry.\n */\n load: () => Promise<M | undefined>\n /** Free the loaded model's memory (and drop a load in flight). */\n unload: () => Promise<void>\n /** The id of the model held in memory, whichever id is current. */\n loadedModelId: string | undefined\n /** True while the current `modelId` is downloading / initializing. */\n loading: boolean\n /** Load progress of the current `modelId`, 0..1. */\n progress: number\n /** Human-readable progress text from the runtime. */\n text: string\n /** Why the current `modelId` failed to load. */\n error: string | undefined\n /** Whether this browser can run the engine. */\n supported: boolean\n /** True once the current `modelId` is ready. */\n ready: boolean\n /** The loaded model's context window, in tokens, when the runtime says. */\n contextWindow: number | undefined\n}\n\ninterface Loaded<M> {\n id: string\n /** The id and the window it was loaded with: another window is another load. */\n key: string\n model: M\n /** Frees it with the engine that built it (the engine may change since). */\n free: () => Promise<void>\n}\n\nconst keyOf = (id: string, tokens: number | undefined) => (tokens ? `${id}@${tokens}` : id)\n\n/**\n * Load an on-device model and track its download — for any local runtime,\n * described by an {@link LocalModelEngine}. Nothing downloads until you call\n * `load()` (models are large), so you can gate it behind a user action.\n *\n * Everything it reports is about the **current** `modelId`: switch the id and\n * `model` / `ready` / `progress` / `error` describe the new one (not loaded\n * yet), while the previous model stays in memory — switching back is instant.\n * Loading the new id frees the previous one first, so two models never hold\n * memory at once; `unload()` frees it on demand. A load superseded by another\n * frees its model; a second `load()` of the same id shares the download.\n *\n * ```tsx\n * import { browserAI, doesBrowserSupportBrowserAI } from '@browser-ai/core'\n * const nano: LocalModelEngine = {\n * create: async () => browserAI('text', { expectedInputs: [{ type: 'image' }] }),\n * warmUp: async (m, { onProgress }) => {\n * await m.createSessionWithProgress((p) => onProgress({ progress: p, text: 'Downloading' }))\n * },\n * supported: doesBrowserSupportBrowserAI,\n * contextWindowOf: (m) => m.getContextWindow(),\n * }\n * const local = useLocalModel('gemini-nano', nano)\n * ```\n *\n * {@link useWebLLMModel} is this hook with the WebLLM engine.\n */\nexport const useLocalModel = <M extends LanguageModel = LanguageModel>(\n modelId: string,\n engine: LocalModelEngine<M>,\n options?: UseLocalModelOptions,\n): UseLocalModelReturn<M> => {\n const [loaded, setLoaded] = useState<Loaded<M> | undefined>(undefined)\n const [pending, setPending] = useState<{ key: string; progress: number; text: string }>()\n const [failure, setFailure] = useState<{ key: string; message: string }>()\n // The engine is read at load time: a new object every render is fine.\n const engineRef = useRef(engine)\n engineRef.current = engine\n // The source of truth for async code (state lags a render behind).\n const loadedRef = useRef<Loaded<M> | undefined>(undefined)\n const inflightRef = useRef<{ key: string; promise: Promise<M | undefined> } | undefined>(\n undefined,\n )\n const windowTokens = options?.contextWindowTokens\n const key = keyOf(modelId, windowTokens)\n // Bumped by every load()/unload(): an older load that finishes late is stale.\n const seqRef = useRef(0)\n\n const setHeld = (next: Loaded<M> | undefined) => {\n loadedRef.current = next\n setLoaded(next)\n }\n const freeWith = (eng: LocalModelEngine<M>, model: M) => async () => {\n try {\n await eng.unload?.(model)\n } catch {\n /* best-effort */\n }\n }\n\n const load = useCallback((): Promise<M | undefined> => {\n const id = modelId\n if (loadedRef.current?.key === key) return Promise.resolve(loadedRef.current.model)\n if (inflightRef.current?.key === key) return inflightRef.current.promise\n const eng = engineRef.current\n if (eng.supported && !eng.supported()) {\n setFailure({\n key,\n message: eng.unsupportedMessage ?? 'This browser cannot run this model.',\n })\n return Promise.resolve(undefined)\n }\n const seq = ++seqRef.current\n const current = () => seq === seqRef.current\n const ctx: LocalModelLoadContext = {\n onProgress: (report) => {\n if (current()) setPending({ key, progress: report.progress, text: report.text })\n },\n ...(windowTokens ? { contextWindowTokens: windowTokens } : {}),\n }\n const promise = (async (): Promise<M | undefined> => {\n setPending({ key, progress: 0, text: '' })\n setFailure(undefined)\n let built: M | undefined\n try {\n // One model per hook: free the previous one before the next download.\n const previous = loadedRef.current\n if (previous) {\n setHeld(undefined)\n await previous.free()\n }\n built = await eng.create(id, ctx)\n await eng.warmUp?.(built, ctx)\n if (!current()) {\n // Superseded by another load() or an unload(): don't leak its memory.\n await freeWith(eng, built)()\n return undefined\n }\n setHeld({ id, key, model: built, free: freeWith(eng, built) })\n return built\n } catch (err) {\n if (built) await freeWith(eng, built)()\n if (current()) setFailure({ key, message: errMessage(err) })\n return undefined\n } finally {\n if (current()) {\n inflightRef.current = undefined\n setPending(undefined)\n }\n }\n })()\n inflightRef.current = { key, promise }\n return promise\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [modelId, key])\n\n const unload = useCallback(async (): Promise<void> => {\n seqRef.current++ // a load in flight becomes stale and frees itself\n inflightRef.current = undefined\n setPending(undefined)\n const previous = loadedRef.current\n setHeld(undefined)\n if (previous) await previous.free()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const model = loaded?.key === key ? loaded.model : undefined\n const progressing = pending?.key === key ? pending : undefined\n return {\n model,\n load,\n unload,\n loadedModelId: loaded?.id,\n loading: progressing !== undefined,\n progress: progressing?.progress ?? 0,\n text: progressing?.text ?? '',\n error: failure?.key === key ? failure.message : undefined,\n supported: engine.supported ? engine.supported() : true,\n ready: model !== undefined,\n contextWindow: model ? engine.contextWindowOf?.(model) : undefined,\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { ToolApprovalMode } from '@dudko.dev/agent-web'\nimport { defaultNoticeTexts, type NoticeTexts } from './composer.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 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 // ── 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 microphone: 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 attachmentsOnly: string\n seeAttachments: string\n tooLarge: (name: string, mb: number) => string\n binaryText: (name: 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 /** 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 // ── steps / tool calls ─────────────────────────────────────────────────────\n failed: string\n toolCostTitle: string\n}\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`\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 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 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 microphone: 'Microphone',\n model: 'Model',\n thinking: 'Thinking',\n toolConsent: 'Tool consent',\n modes: {\n autopilot: { label: 'Auto', hint: 'Autopilot — run every tool without asking' },\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 binaryText: (name) => `${name} looks binary — it can't be attached as text.`,\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 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 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\n/** Overrides: any label, with the nested groups merged key by key. */\nexport type AgentLabelsOverride = Partial<\n Omit<\n AgentLabels,\n 'status' | 'modes' | 'commandGroups' | 'commandDescriptions' | 'thinkingLevels' | 'notices'\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}\n\nconst NESTED = [\n 'status',\n 'modes',\n 'commandGroups',\n 'commandDescriptions',\n 'thinkingLevels',\n 'noteAt',\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\nconst LabelsContext = createContext<AgentLabels>(defaultLabels)\n\nexport interface AgentLabelsProviderProps {\n labels: AgentLabelsOverride\n children?: ReactNode\n}\n\n/** Override labels for every component below (nests: inner providers win). */\nexport const AgentLabelsProvider = ({ labels, children }: AgentLabelsProviderProps) => {\n const parent = useContext(LabelsContext)\n const value = useMemo(() => mergeLabels(parent, labels), [parent, labels])\n return <LabelsContext.Provider value={value}>{children}</LabelsContext.Provider>\n}\n\n/** The labels in effect: the provider's, with a component's own `labels` prop on top. */\nexport const useLabels = (over?: AgentLabelsOverride): AgentLabels => {\n const ctx = useContext(LabelsContext)\n return useMemo(() => mergeLabels(ctx, over), [ctx, over])\n}\n","import 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}\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/**\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.\n */\nexport const withAttachments = (text: string, files: ComposerAttachment[]): string => {\n const texts = files.filter((f) => f.kind === 'text' && f.text !== undefined)\n if (texts.length === 0) return text\n const blocks = texts.map((f) => {\n const body = f.text as string\n const fence = body.includes('```') ? '~~~' : '```'\n const where = f.path ? ` (also saved as ${f.path})` : ''\n return `### ${f.name}${where}\\n${fence}\\n${body}\\n${fence}`\n })\n return `${text}\\n\\nAttached file(s):\\n${blocks.join('\\n\\n')}`\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/** 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 * 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/** 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","import { createContext, useContext } from 'react'\nimport type { ReactNode } from 'react'\nimport type { BrowserAgentConfig } from '@dudko.dev/agent-web'\nimport { useAgent, type UseAgentOptions, type UseAgentReturn } from './hooks/use-agent.js'\n\nconst AgentContext = createContext<UseAgentReturn | null>(null)\n\nexport interface AgentProviderProps extends UseAgentOptions {\n /** The agent configuration (see `@dudko.dev/agent-web`). */\n config: BrowserAgentConfig\n children: ReactNode\n}\n\n/**\n * Build one agent with {@link useAgent} and share it with the subtree, so a\n * chat panel, a plan view and a usage badge can all read the same live run.\n *\n * ```tsx\n * <AgentProvider config={{ model, tools, credentials }}>\n * <AgentChat />\n * </AgentProvider>\n * ```\n */\nexport const AgentProvider = ({ config, children, ...options }: AgentProviderProps) => {\n const agent = useAgent(config, options)\n return <AgentContext.Provider value={agent}>{children}</AgentContext.Provider>\n}\n\n/** Read the shared agent. Throws if used outside an {@link AgentProvider}. */\nexport const useAgentContext = (): UseAgentReturn => {\n const ctx = useContext(AgentContext)\n if (!ctx) throw new Error('useAgentContext must be used within an <AgentProvider>')\n return ctx\n}\n\n/** Non-throwing variant: returns `null` when outside a provider. */\nexport const useOptionalAgentContext = (): UseAgentReturn | null => useContext(AgentContext)\n","import { useEffect, useRef, useState } from 'react'\nimport type { ComponentType, CSSProperties, ReactNode } from 'react'\nimport type { VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { ChatHistoryStore } from '../chat-history.js'\nimport { useOptionalAgentContext } from '../context.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { useChatHistory, type UseChatHistoryReturn } from '../hooks/use-chat-history.js'\nimport { AgentLabelsProvider, useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { AgentComposer, type AgentComposerProps } from './AgentComposer.js'\nimport { ChatHistoryList, type ChatHistoryListProps } from './ChatHistoryList.js'\nimport { ContextMeter } from './ContextMeter.js'\nimport { FilesPanel, type FilesPanelProps } from './FilesPanel.js'\nimport { AlertIcon, FileIcon, HistoryIcon } from './icons.js'\nimport { MessageList, type MessageListProps } from './MessageList.js'\nimport { ModelLoadBar } from './ModelLoadBar.js'\nimport type { RenderToolCall } from './StepList.js'\nimport { ToolApprovalPrompt, type ToolApprovalPromptProps } from './ToolApprovalPrompt.js'\nimport { UsageBadge } from './UsageBadge.js'\n\n/** Places to put your own content in the panel. */\nexport interface AgentChatSlots {\n /** Replaces the whole header; `false` hides it. */\n header?: ReactNode | false\n /** In the header, before the title. */\n headerStart?: ReactNode\n /** In the header, after the usage badge. */\n headerEnd?: ReactNode\n /** In the body, above / below the transcript. */\n beforeMessages?: ReactNode\n afterMessages?: ReactNode\n /** Above the composer. */\n footerStart?: ReactNode\n /** Under the chat list in the history sidebar. */\n sidebar?: ReactNode\n}\n\n/** Swap any built-in part for your own component (same props). */\nexport interface AgentChatComponents {\n Composer?: ComponentType<AgentComposerProps>\n MessageList?: ComponentType<MessageListProps>\n HistoryList?: ComponentType<ChatHistoryListProps>\n FilesPanel?: ComponentType<FilesPanelProps>\n ApprovalPrompt?: ComponentType<ToolApprovalPromptProps>\n}\n\n/** Extra class names per part (added to the built-in `awr-` ones). */\nexport interface AgentChatClassNames {\n root?: string\n main?: string\n header?: string\n body?: string\n footer?: string\n sidebar?: string\n files?: string\n}\n\nexport interface AgentChatProps {\n /**\n * An explicit controller from {@link useAgent}. If omitted, the component\n * reads the shared controller from an enclosing `<AgentProvider>`.\n */\n controller?: UseAgentReturn\n title?: ReactNode\n /** Content shown before the first message. */\n emptyState?: ReactNode\n /** @deprecated use `composer={{ placeholder }}` */\n placeholder?: string\n\n // ── what is shown ──────────────────────────────────────────────────────────\n /** Each answer's steps, thoughts, subagents, consent decisions (default true). */\n showActivity?: boolean\n /** Each tool call inside the activity (default true). */\n showToolCalls?: boolean\n /** Tokens per answer and per tool call (default true). */\n showUsage?: boolean\n /** Thoughts, when the model thinks (default true). */\n showThoughts?: boolean\n /** What you said while the agent worked, under the step it reached (default true). */\n showNotes?: boolean\n /** The lessons the agent wrote down during an answer, and the pages it fetched (default true). */\n showLearned?: boolean\n /** A stop button on each running subagent (default true). */\n stoppableSubagents?: boolean\n /** Conversation total in the header (default true). */\n showTotalUsage?: boolean\n /** Status dot in the header (default true). */\n showStatus?: boolean\n /** Consent-mode chip in the composer — \"⚡ Auto\" (default true). */\n showApprovalMode?: boolean\n /**\n * Context meter (tokens by kind, budget bar, Compact) above the composer\n * (default false). A number draws the bar against that budget.\n */\n showContext?: boolean | number\n /** Keep finished answers' activity expanded (default false). */\n activityOpen?: boolean\n\n // ── features ───────────────────────────────────────────────────────────────\n /**\n * Saved conversations in IndexedDB with a sidebar to switch between them:\n * `true` (default store), your own `ChatHistoryStore`, or the result of your\n * own `useChatHistory()` (e.g. to render the list elsewhere).\n */\n history?: boolean | ChatHistoryStore | UseChatHistoryReturn\n /**\n * Sidebar open at first (default: on a wide panel yes; on a narrow one —\n * under `narrowWidth` — it starts closed and opens over the chat).\n */\n defaultHistoryOpen?: boolean\n /**\n * The workspace: attachments are saved here, and a Files panel shows it\n * (add `createFileTools(files)` to the agent's tools so it can use it too).\n */\n files?: VirtualFileSystem\n /** Files panel open at first (default false). */\n defaultFilesOpen?: boolean\n /** Below this width (px) side panels overlay the chat instead of sitting beside it (default 760). */\n narrowWidth?: number\n /** Composer options (model / thinking chips, commands, convertFile, speech…), or `false` to hide it. */\n composer?: Partial<Omit<AgentComposerProps, 'controller'>> | false\n\n // ── how it is rendered ─────────────────────────────────────────────────────\n /** A message's text — plug in your markdown renderer here. */\n renderContent?: MessageListProps['renderContent']\n renderMessage?: MessageListProps['renderMessage']\n renderAttachment?: MessageListProps['renderAttachment']\n renderToolCall?: RenderToolCall\n renderApproval?: ToolApprovalPromptProps['renderApproval']\n slots?: AgentChatSlots\n components?: AgentChatComponents\n /** Override any text (i18n); applies to every part inside. */\n labels?: AgentLabelsOverride\n /** Force a colour scheme (default 'auto' = follow the OS). */\n theme?: 'auto' | 'light' | 'dark'\n classNames?: AgentChatClassNames\n className?: string\n /** Inline styles on the root — handy for sizing (e.g. `{ height: 520 }`). */\n style?: CSSProperties\n}\n\nconst isHistoryHook = (h: AgentChatProps['history']): h is UseChatHistoryReturn =>\n typeof h === 'object' && h !== null && 'select' in h && 'chats' in h\n\nconst cx = (...names: (string | false | undefined)[]) => names.filter(Boolean).join(' ')\n\n/**\n * A drop-in chat panel: transcript with every answer's activity (steps, tool\n * calls with their cost, thoughts, subagents, consent decisions) and tokens by\n * kind, live consent prompts, model-load progress, and the full composer\n * (attachments by \"+\", Ctrl+V and drag & drop; slash commands; timer; agents;\n * model + thinking; consent mode; dictation). Optional: saved chats in\n * IndexedDB (`history`) and a workspace panel (`files`).\n *\n * Everything is switchable (`show*`), relabelable (`labels`), replaceable\n * (`render*`, `slots`, `components`) and themable (`theme`, `--awr-*`\n * variables, `classNames`). Give it a `controller` from {@link useAgent}, or\n * wrap it in an {@link AgentProvider}.\n *\n * ```tsx\n * <AgentChat controller={agent} history files={vfs} composer={{ model: { label: 'Gemini' } }} />\n * ```\n */\nexport const AgentChat = (props: AgentChatProps) => (\n <AgentLabelsProvider labels={props.labels ?? NO_LABELS}>\n <AgentChatInner {...props} />\n </AgentLabelsProvider>\n)\n\nconst NO_LABELS: AgentLabelsOverride = {}\n\nconst AgentChatInner = ({\n controller,\n title,\n emptyState,\n placeholder,\n showActivity = true,\n showToolCalls = true,\n showUsage = true,\n showThoughts = true,\n showNotes = true,\n showLearned = true,\n stoppableSubagents = true,\n showTotalUsage = true,\n showStatus = true,\n showApprovalMode = true,\n showContext = false,\n activityOpen = false,\n history,\n defaultHistoryOpen,\n files,\n defaultFilesOpen = false,\n narrowWidth = 760,\n composer,\n renderContent,\n renderMessage,\n renderAttachment,\n renderToolCall,\n renderApproval,\n slots = {},\n components = {},\n theme = 'auto',\n classNames = {},\n className,\n style,\n}: AgentChatProps) => {\n const ctx = useOptionalAgentContext()\n const agent = controller ?? ctx\n if (!agent) {\n throw new Error(\n '<AgentChat> needs a `controller` prop from useAgent(), or an enclosing <AgentProvider>.',\n )\n }\n const L = useLabels()\n\n // History: an external hook result, or our own over the given / default store.\n const external = isHistoryHook(history) ? history : undefined\n const [ownStore] = useState(() =>\n history instanceof ChatHistoryStore ? history : new ChatHistoryStore(),\n )\n const own = useChatHistory(agent, {\n store: ownStore,\n enabled: Boolean(history) && !external,\n })\n const chats = history ? (external ?? own) : undefined\n\n // Narrow panel → the side panels overlay the chat (and start closed).\n const rootRef = useRef<HTMLDivElement>(null)\n const [narrow, setNarrow] = useState<boolean | undefined>(undefined)\n useEffect(() => {\n const el = rootRef.current\n if (!el || typeof ResizeObserver === 'undefined') return setNarrow(false)\n const measure = () => setNarrow(el.getBoundingClientRect().width < narrowWidth)\n measure()\n const ro = new ResizeObserver(measure)\n ro.observe(el)\n return () => ro.disconnect()\n }, [narrowWidth])\n const [historyChoice, setHistoryOpen] = useState<boolean | undefined>(defaultHistoryOpen)\n const historyOpen = historyChoice ?? narrow === false\n const [filesOpen, setFilesOpen] = useState(defaultFilesOpen)\n // On a narrow panel one overlay at a time.\n const toggleHistory = () => {\n setHistoryOpen(!historyOpen)\n if (narrow && !historyOpen) setFilesOpen(false)\n }\n const toggleFiles = () => {\n setFilesOpen((o) => !o)\n if (narrow && !filesOpen) setHistoryOpen(false)\n }\n\n // Follow the transcript while the user is at the bottom; leave them be when\n // they scrolled up to read.\n const bodyRef = useRef<HTMLDivElement>(null)\n const stickRef = useRef(true)\n useEffect(() => {\n const el = bodyRef.current\n if (el && stickRef.current) el.scrollTop = el.scrollHeight\n }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad, agent.pendingApprovals])\n\n const [compacting, setCompacting] = useState(false)\n const compact = () => {\n setCompacting(true)\n void agent.compact().finally(() => setCompacting(false))\n }\n\n const Composer = components.Composer ?? AgentComposer\n const Messages = components.MessageList ?? MessageList\n const HistoryList = components.HistoryList ?? ChatHistoryList\n const Files = components.FilesPanel ?? FilesPanel\n const Approvals = components.ApprovalPrompt ?? ToolApprovalPrompt\n\n const loading = agent.modelLoad && agent.modelLoad.progress < 1\n const showReplan = agent.replan && agent.replan.mode !== 'continue'\n const liveExtra =\n agent.planThought.trim() || showReplan ? (\n <>\n {agent.planThought.trim() && (\n <details className=\"awr-activity__plan\">\n <summary>{L.planned}</summary>\n <p className=\"awr-activity__thought\">{agent.planThought}</p>\n </details>\n )}\n {showReplan && (\n <div className=\"awr-activity__replan\">\n {L.replanned(agent.replan!.mode, agent.replan!.reason)}\n </div>\n )}\n </>\n ) : undefined\n\n const header =\n slots.header === false ? null : slots.header !== undefined ? (\n slots.header\n ) : (\n <div className={cx('awr-chat__header', classNames.header)}>\n {chats && (\n <button\n type=\"button\"\n className={cx('awr-iconbtn', historyOpen && 'is-on')}\n aria-label={L.showHistory}\n title={L.showHistory}\n aria-pressed={historyOpen}\n onClick={toggleHistory}\n >\n <HistoryIcon size={16} />\n </button>\n )}\n {slots.headerStart}\n <div className=\"awr-chat__title\">{title}</div>\n {showStatus && (\n <span className={`awr-status awr-status--${agent.status}`} title={L.status[agent.status]}>\n <span className=\"awr-status__dot\" />\n <span className=\"awr-status__text\">{L.status[agent.status]}</span>\n </span>\n )}\n {showTotalUsage && (\n <span title={L.totalUsage}>\n <UsageBadge usage={agent.totalUsage} compact={narrow !== false} />\n </span>\n )}\n {files && (\n <button\n type=\"button\"\n className={cx('awr-iconbtn', filesOpen && 'is-on')}\n aria-label={L.showFiles}\n title={L.showFiles}\n aria-pressed={filesOpen}\n onClick={toggleFiles}\n >\n <FileIcon size={16} />\n </button>\n )}\n {slots.headerEnd}\n </div>\n )\n\n return (\n <div\n ref={rootRef}\n className={cx('awr-chat', narrow && 'awr-chat--narrow', className, classNames.root)}\n style={style}\n data-awr-theme={theme === 'auto' ? undefined : theme}\n >\n {chats && historyOpen && (\n <aside className={cx('awr-chat__sidebar', classNames.sidebar)}>\n <HistoryList\n history={{\n ...chats,\n // Picking a chat on a narrow panel closes the overlay.\n select: async (id) => {\n await chats.select(id)\n if (narrow) setHistoryOpen(false)\n },\n newChat: () => {\n chats.newChat()\n if (narrow) setHistoryOpen(false)\n },\n }}\n disabled={agent.isRunning}\n />\n {slots.sidebar}\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-chat__closeside\"\n aria-label={L.close}\n onClick={() => setHistoryOpen(false)}\n >\n ×\n </button>\n </aside>\n )}\n\n <div className={cx('awr-chat__main', classNames.main)}>\n {header}\n\n <div\n className={cx('awr-chat__body', classNames.body)}\n ref={bodyRef}\n onScroll={(e) => {\n const el = e.currentTarget\n stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80\n }}\n >\n {slots.beforeMessages}\n <Messages\n messages={agent.messages}\n empty={emptyState ?? L.emptyState}\n showActivity={showActivity}\n showToolCalls={showToolCalls}\n showUsage={showUsage}\n showThoughts={showThoughts}\n showNotes={showNotes}\n showLearned={showLearned}\n onStopSubagent={stoppableSubagents ? agent.stopSubagent : undefined}\n activityOpen={activityOpen}\n liveExtra={liveExtra}\n renderContent={renderContent}\n renderMessage={renderMessage}\n renderAttachment={renderAttachment}\n renderToolCall={renderToolCall}\n />\n <Approvals\n approvals={agent.pendingApprovals}\n onApprove={agent.approve}\n onDeny={agent.deny}\n renderApproval={renderApproval}\n />\n {agent.modelLoad && loading && <ModelLoadBar load={agent.modelLoad} />}\n {slots.afterMessages}\n </div>\n\n <div className={cx('awr-chat__footer', classNames.footer)}>\n {slots.footerStart}\n {showContext !== false && (\n <ContextMeter\n usage={agent.usage}\n budgetTokens={typeof showContext === 'number' ? showContext : undefined}\n budget={agent.budget}\n compactions={agent.compactions}\n onCompact={agent.isRunning ? undefined : compact}\n compacting={compacting}\n />\n )}\n {composer === false ? (\n agent.error &&\n agent.status === 'error' && (\n <div className=\"awr-chat__error\">\n <AlertIcon size={14} /> {agent.error}\n </div>\n )\n ) : (\n <Composer\n controller={agent}\n showApprovalMode={showApprovalMode}\n files={files}\n dropZone={rootRef}\n {...(placeholder ? { placeholder } : {})}\n {...composer}\n />\n )}\n </div>\n </div>\n\n {files && filesOpen && (\n <aside className={cx('awr-chat__files', classNames.files)}>\n <Files files={files} />\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-chat__closeside\"\n aria-label={L.close}\n onClick={() => setFilesOpen(false)}\n >\n ×\n </button>\n </aside>\n )}\n </div>\n )\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport type { ClipboardEvent, CSSProperties, KeyboardEvent, ReactNode, RefObject } from 'react'\nimport type { RunFile, ToolApprovalMode, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport {\n attachmentKindOf,\n attachmentRefusal,\n filterCommands,\n formatElapsed,\n noticesOf,\n parseSlash,\n steerIntent,\n withAttachments,\n type ComposerAttachment,\n type SlashCommand,\n} from '../composer.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { useSpeechToText } from '../hooks/use-speech-to-text.js'\nimport { downscaleImage } from '../image-resize.js'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ChatAttachment } from '../types.js'\nimport {\n AlertIcon,\n BoltIcon,\n BotIcon,\n ClockIcon,\n EyeIcon,\n FileIcon,\n MicIcon,\n PlusIcon,\n SendIcon,\n ShieldIcon,\n SlashIcon,\n SpinnerIcon,\n StopIcon,\n XIcon,\n} from './icons.js'\n\nexport interface ComposerModelChip {\n /** What the chip says, e.g. \"Gemini 3.5 Flash\". */\n label: string\n /** Models to switch to from the chip's menu (omit for a read-only label). */\n options?: { id: string; label: string; group?: string }[]\n value?: string\n onSelect?: (id: string) => void\n}\n\nexport interface ComposerThinkingChip {\n /** Current level, e.g. 'off' | 'low' | 'medium' | 'high'. */\n value: string\n /** Offered levels (default: default / low / medium / high). */\n options?: { id: string; label: string }[]\n onChange: (value: string) => void\n}\n\n/** A file turned into text by the host (e.g. a PDF converted to Markdown). */\nexport interface ConvertedFile {\n text: string\n /** Name of the text attachment (default: the file's name + \".md\"). */\n name?: string\n}\n\nexport interface AgentComposerProps {\n /** The agent from `useAgent()` (or `useAgentContext()`). */\n controller: UseAgentReturn\n placeholder?: string\n /** Model chip (and switcher). */\n model?: ComposerModelChip\n /** Thinking level, shown next to the model and switchable from its menu. */\n thinking?: ComposerThinkingChip\n /** Override any text the composer renders (see `AgentLabels`). */\n labels?: AgentLabelsOverride\n /** Extra slash commands (merged after the built-ins and the agent's skills). */\n commands?: SlashCommand[]\n /** Built-in commands: /compact /new /stop /autopilot /ask /ask-all /read-only /think (default true). */\n builtinCommands?: boolean\n /** Offer the agent's skills as \"/skill-name …\" commands (default true). */\n skillCommands?: boolean\n /**\n * \"+\" button, paste (Ctrl+V) and drag & drop of files and images (default\n * true). Text files are inlined into the message; images, PDFs and other\n * files go to the model as attachments — when the model can take them.\n */\n attachments?:\n | boolean\n | {\n /** The file picker's `accept`. */\n accept?: string\n /** Refuse larger files (default 20 MB). */\n maxBytes?: number\n /**\n * Downscale images to this longest edge before sending (default 1568 —\n * what providers bill for; larger only costs upload). false = as is.\n */\n imageMaxDimension?: number | false\n /** …and to this many pixels (default 1 150 000). */\n imageMaxPixels?: number\n }\n /**\n * Turn a file into text — e.g. PDF → Markdown with `@dudko.dev/pdf-to-md-core`.\n * Used for PDFs the model can't read (or every PDF with `convert: 'always'`)\n * and for files of a kind the model refuses. Return undefined to skip.\n */\n convertFile?: (file: File) => Promise<ConvertedFile | undefined>\n /** When to use `convertFile` for PDFs (default 'when-needed'). */\n convert?: 'when-needed' | 'always'\n /** Save attachments into this virtual file system (under `/attachments/`). */\n files?: VirtualFileSystem\n /**\n * Where dropping files attaches them: the composer itself ('self', default),\n * the whole window ('window'), or any element (a ref — `<AgentChat>` passes\n * its own panel).\n */\n dropZone?: 'self' | 'window' | RefObject<HTMLElement | null>\n /** Speech-to-text mic — the browser's Web Speech API (default: on when supported). */\n speech?: boolean | { lang?: string }\n /** Run timer chip (default true). */\n showTimer?: boolean\n /** Running-subagents chip (default true). */\n showAgents?: boolean\n /** Consent-mode chip — \"⚡ Auto\" for autopilot (default true). */\n showApprovalMode?: boolean\n /** Banners for limits, compaction and errors above the input (default true). */\n showNotices?: boolean\n /**\n * Let the user type to the agent while it works (default true): Enter sends the text\n * to the running agent, which sees it at its next boundary (see `useAgent().send`).\n * Off: the input does nothing while a run is going, as before.\n */\n steering?: boolean\n /** Messages waiting for the agent, and the ones a stopped run left undelivered (default true). */\n showQueued?: boolean\n /** Below this width (px) the toolbar chips show icons and numbers only (default 460). */\n compactWidth?: number\n /** Extra content in the toolbar, after the \"/\" button. */\n toolbarExtra?: ReactNode\n /** Extra content at the end of the toolbar, before the consent chip. */\n toolbarEnd?: ReactNode\n /** Render an attachment chip yourself (`remove` drops it). */\n renderAttachment?: (attachment: ComposerAttachment, remove: () => void) => ReactNode\n disabled?: boolean\n className?: string\n}\n\nconst thinkingDefaults = (l: AgentLabels) => [\n { id: 'off', label: l.thinkingLevels.off },\n { id: 'none', label: l.thinkingLevels.none },\n { id: 'low', label: l.thinkingLevels.low },\n { id: 'medium', label: l.thinkingLevels.medium },\n { id: 'high', label: l.thinkingLevels.high },\n]\n\nconst MODES: ToolApprovalMode[] = ['autopilot', 'ask-writes', 'ask-all', 'read-only']\n\nconst ModeIcon = ({ mode }: { mode: ToolApprovalMode }) =>\n mode === 'autopilot' ? (\n <BoltIcon size={14} />\n ) : mode === 'read-only' ? (\n <EyeIcon size={14} />\n ) : (\n <ShieldIcon size={14} />\n )\n\ntype Menu = 'commands' | 'model' | 'mode' | undefined\n\nlet attachSeq = 0\n\n// useLayoutEffect warns during SSR; menus only exist in the browser anyway.\nconst useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect\n\n/**\n * Where an open menu goes: fixed, next to its anchor — above it when there is\n * room (the composer sits at the bottom of a panel), below otherwise — so the\n * panel's `overflow` never clips it and it never leaves the viewport.\n */\nconst useMenuPlacement = (\n open: boolean,\n anchor: RefObject<HTMLElement | null>,\n align: 'left' | 'right' | 'stretch',\n): CSSProperties | undefined => {\n const [style, setStyle] = useState<CSSProperties>()\n useIsoLayoutEffect(() => {\n if (!open) return\n const place = () => {\n const el = anchor.current\n if (!el) return\n const r = el.getBoundingClientRect()\n const vw = window.innerWidth\n const vh = window.innerHeight\n const above = r.top - 8\n const below = vh - r.bottom - 8\n const up = above >= 240 || above >= below\n const s: CSSProperties = {\n maxHeight: Math.max(120, (up ? above : below) - 6),\n top: up ? 'auto' : r.bottom + 6,\n bottom: up ? vh - r.top + 6 : 'auto',\n maxWidth: vw - 16,\n }\n if (align === 'stretch') {\n s.left = Math.max(8, r.left)\n s.width = Math.min(r.width, vw - 16)\n } else if (align === 'right') {\n s.left = 'auto'\n s.right = Math.max(8, vw - r.right)\n } else {\n s.left = Math.max(8, Math.min(r.left, vw - 248))\n }\n setStyle(s)\n }\n place()\n window.addEventListener('resize', place)\n window.addEventListener('scroll', place, true)\n return () => {\n window.removeEventListener('resize', place)\n window.removeEventListener('scroll', place, true)\n }\n }, [open, anchor, align])\n return open ? style : undefined\n}\n\nconst readDataUrl = (file: Blob): Promise<string> =>\n new Promise((resolve, reject) => {\n const r = new FileReader()\n r.onload = () => resolve(String(r.result))\n r.onerror = () => reject(r.error ?? new Error('could not read the file'))\n r.readAsDataURL(file)\n })\n\nconst safeName = (name: string): string => name.replace(/[^\\w.-]+/g, '_').slice(0, 80) || 'file'\n\n/**\n * A full chat composer for the agent — the input plus everything around it:\n *\n * - banners for a limit that stopped the run, a compaction, a start failure,\n * or an attachment the model can't take;\n * - the \"+\" button, Ctrl+V and drag & drop: images (thumbnails), PDFs and text\n * files — checked against the model's capabilities, optionally converted\n * (PDF → Markdown) and saved to a virtual file system;\n * - slash commands: `/compact`, `/new`, `/stop`, the consent modes, `/think`,\n * and the agent's skills as `/skill-name …`;\n * - a run timer, the number of running subagents, the model + thinking chip,\n * the consent-mode chip (\"⚡ Auto\" = autopilot), a speech-to-text mic, and\n * send / stop.\n *\n * Every piece can be switched off; `<AgentChat>` uses it as its footer.\n */\nexport const AgentComposer = ({\n controller: agent,\n placeholder,\n model,\n thinking,\n labels: labelsOverride,\n commands = [],\n builtinCommands = true,\n skillCommands = true,\n attachments = true,\n convertFile,\n convert = 'when-needed',\n files: vfs,\n dropZone = 'self',\n speech = true,\n showTimer = true,\n showAgents = true,\n showApprovalMode = true,\n showNotices = true,\n steering = true,\n showQueued = true,\n compactWidth = 460,\n toolbarExtra,\n toolbarEnd,\n renderAttachment,\n disabled = false,\n className,\n}: AgentComposerProps) => {\n const L = useLabels(labelsOverride)\n const MODE_CHIP = L.modes\n const DEFAULT_THINKING = thinkingDefaults(L)\n const [text, setText] = useState('')\n const [pending, setPending] = useState<ComposerAttachment[]>([])\n const [menu, setMenu] = useState<Menu>(undefined)\n const [active, setActive] = useState(0)\n const [dismissed, setDismissed] = useState<Set<string>>(() => new Set())\n const [attachError, setAttachError] = useState<string | undefined>()\n const [dragging, setDragging] = useState(false)\n const rootRef = useRef<HTMLDivElement>(null)\n const modelRef = useRef<HTMLSpanElement>(null)\n const modeRef = useRef<HTMLSpanElement>(null)\n // Where the drop overlay goes: over the whole drop zone, not just the input.\n const [dropRect, setDropRect] = useState<CSSProperties>()\n // A narrow composer (a phone, a side panel) keeps one toolbar row by\n // dropping the chips' words — icons and numbers stay, words go to tooltips.\n const [compactBar, setCompactBar] = useState(false)\n useEffect(() => {\n const el = rootRef.current\n if (!el || typeof ResizeObserver === 'undefined') return\n const ro = new ResizeObserver(() =>\n setCompactBar(el.getBoundingClientRect().width < compactWidth),\n )\n ro.observe(el)\n return () => ro.disconnect()\n }, [compactWidth])\n const fileRef = useRef<HTMLInputElement>(null)\n const inputRef = useRef<HTMLTextAreaElement>(null)\n\n const busy = agent.isRunning\n const ready = agent.isReady && !disabled\n const caps = agent.agent?.capabilities\n\n // ── speech-to-text ──────────────────────────────────────────────────────────\n const stt = useSpeechToText({\n lang: typeof speech === 'object' ? speech.lang : undefined,\n onFinal: (heard) => setText((t) => (t.trim() ? `${t.trimEnd()} ${heard}` : heard)),\n })\n const showMic = speech !== false && stt.supported\n\n // ── run timer ───────────────────────────────────────────────────────────────\n const [startedAt, setStartedAt] = useState<number | undefined>()\n const [now, setNow] = useState(() => Date.now())\n const [lastElapsed, setLastElapsed] = useState<number | undefined>()\n useEffect(() => {\n if (!busy) {\n if (startedAt !== undefined) setLastElapsed(Date.now() - startedAt)\n setStartedAt(undefined)\n return\n }\n const t0 = Date.now()\n setStartedAt(t0)\n setNow(t0)\n const id = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(id)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [busy])\n const elapsed = startedAt !== undefined ? now - startedAt : lastElapsed\n\n // ── commands ────────────────────────────────────────────────────────────────\n const allCommands = useMemo<SlashCommand[]>(() => {\n const out: SlashCommand[] = []\n if (builtinCommands) {\n out.push(\n {\n name: 'compact',\n description: L.commandDescriptions.compact,\n group: L.commandGroups.commands,\n run: () => void agent.compact(),\n },\n {\n name: 'new',\n description: L.commandDescriptions.new,\n group: L.commandGroups.commands,\n run: agent.reset,\n },\n {\n name: 'stop',\n description: L.commandDescriptions.stop,\n group: L.commandGroups.commands,\n run: agent.stop,\n },\n {\n name: 'autopilot',\n description: L.commandDescriptions.autopilot,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('autopilot'),\n },\n {\n name: 'ask',\n description: L.commandDescriptions.ask,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('ask-writes'),\n },\n {\n name: 'ask-all',\n description: L.commandDescriptions.askAll,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('ask-all'),\n },\n {\n name: 'read-only',\n description: L.commandDescriptions.readOnly,\n group: L.commandGroups.consent,\n run: () => agent.setApprovalMode('read-only'),\n },\n )\n if (thinking) {\n const levels = (thinking.options ?? DEFAULT_THINKING).map((o) => o.id)\n out.push({\n name: 'think',\n description: L.commandDescriptions.think(levels.join(' | ')),\n group: L.commandGroups.commands,\n run: (args) => {\n const level = args.trim().toLowerCase()\n if (levels.includes(level)) thinking.onChange(level)\n },\n })\n }\n }\n if (skillCommands) {\n for (const s of agent.agent?.skills ?? []) {\n out.push({\n name: s.name,\n description: s.description,\n group: L.commandGroups.skills,\n kind: 'prefix',\n transform: (args) => `Use the \"${s.name}\" skill. ${args}`.trim(),\n })\n }\n }\n return [...out, ...commands]\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, builtinCommands, skillCommands, commands, thinking, L])\n\n const slash = parseSlash(text)\n const matches =\n slash && !/\\s/.test(text.trimStart()) ? filterCommands(allCommands, slash.name) : []\n const palette = menu === 'commands' && !slash ? allCommands : matches\n const paletteOpen = palette.length > 0 && (menu === 'commands' || matches.length > 0)\n const commandsStyle = useMenuPlacement(paletteOpen, rootRef, 'stretch')\n const modelStyle = useMenuPlacement(menu === 'model', modelRef, 'left')\n const modeStyle = useMenuPlacement(menu === 'mode', modeRef, 'right')\n\n useEffect(() => setActive(0), [text, menu])\n\n // Close popovers on an outside click.\n useEffect(() => {\n if (!menu) return\n const onDown = (e: MouseEvent) => {\n if (!rootRef.current?.contains(e.target as Node)) setMenu(undefined)\n }\n document.addEventListener('mousedown', onDown)\n return () => document.removeEventListener('mousedown', onDown)\n }, [menu])\n\n const pick = (cmd: SlashCommand) => {\n setMenu(undefined)\n if (cmd.kind === 'prefix') {\n setText(`/${cmd.name} `)\n inputRef.current?.focus()\n return\n }\n const args = parseSlash(text)?.args ?? ''\n setText('')\n void cmd.run?.(args)\n }\n\n // ── attachments ─────────────────────────────────────────────────────────────\n const attachCfg = typeof attachments === 'object' ? attachments : {}\n const maxBytes = attachCfg.maxBytes ?? 20 * 1024 * 1024\n const imageMax = attachCfg.imageMaxDimension ?? 1568\n\n const addFiles = async (list: File[]) => {\n const added: ComposerAttachment[] = []\n let problem: string | undefined\n for (const f of list) {\n const mediaType = f.type || 'application/octet-stream'\n const name = f.name || `pasted-${Date.now()}.${mediaType.split('/')[1] ?? 'bin'}`\n const kind = attachmentKindOf(mediaType, name)\n if (f.size > maxBytes) {\n problem = L.tooLarge(name, Math.round(maxBytes / 1024 / 1024))\n continue\n }\n try {\n const id = `att-${(attachSeq += 1)}`\n if (kind === 'text') {\n const content = await f.text()\n if (content.includes('\\u0000')) {\n problem = L.binaryText(name)\n continue\n }\n added.push({ id, name, kind, mediaType, text: content, bytes: f.size })\n continue\n }\n // A kind the model can't take: convert it to text when the host can,\n // otherwise refuse with a sentence the user can act on.\n const refusal = attachmentRefusal(kind, caps)\n const wantConvert = convertFile && (refusal || (kind === 'pdf' && convert === 'always'))\n if (wantConvert && convertFile) {\n const converted = await convertFile(f)\n if (converted) {\n added.push({\n id,\n name: converted.name ?? `${name}.md`,\n kind: 'text',\n mediaType: 'text/markdown',\n text: converted.text,\n bytes: converted.text.length,\n note: `converted from ${name}`,\n })\n continue\n }\n }\n if (refusal) {\n problem = refusal\n continue\n }\n // Images go at the size providers bill for, not the camera's.\n const blob =\n kind === 'image' && imageMax !== false\n ? await downscaleImage(f, {\n maxDimension: imageMax,\n maxPixels: attachCfg.imageMaxPixels,\n })\n : f\n added.push({\n id,\n name,\n kind,\n mediaType: blob.type || mediaType,\n dataUrl: await readDataUrl(blob),\n bytes: blob.size,\n ...(blob !== f ? { note: `downscaled from ${L.bytes(f.size)}` } : {}),\n })\n } catch (err) {\n problem = `${name}: ${err instanceof Error ? err.message : String(err)}`\n }\n }\n setAttachError(problem)\n if (added.length) setPending((cur) => [...cur, ...added])\n if (fileRef.current) fileRef.current.value = ''\n }\n\n const onPaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {\n if (attachments === false) return\n const pasted = Array.from(e.clipboardData?.files ?? [])\n if (pasted.length === 0) return // plain text: let the textarea take it\n e.preventDefault()\n void addFiles(pasted)\n }\n\n // Drag & drop onto the drop zone (the composer, a panel, or the window).\n const addFilesRef = useRef(addFiles)\n addFilesRef.current = addFiles\n useEffect(() => {\n if (attachments === false) return\n const target: EventTarget | null | undefined =\n dropZone === 'window'\n ? globalThis.window\n : dropZone === 'self'\n ? rootRef.current\n : dropZone.current\n if (!target) return\n let depth = 0\n const hasFiles = (e: Event) =>\n Array.from((e as globalThis.DragEvent).dataTransfer?.types ?? []).includes('Files')\n const onEnter = (e: Event) => {\n if (!hasFiles(e)) return\n depth += 1\n if (target === globalThis.window) setDropRect({ inset: 0 })\n else {\n const r = (target as HTMLElement).getBoundingClientRect()\n setDropRect({ left: r.left, top: r.top, width: r.width, height: r.height })\n }\n setDragging(true)\n }\n const onOver = (e: Event) => {\n if (hasFiles(e)) e.preventDefault() // allow the drop\n }\n const onLeave = () => {\n depth = Math.max(0, depth - 1)\n if (depth === 0) setDragging(false)\n }\n const onDropFiles = (e: Event) => {\n const dropped = (e as globalThis.DragEvent).dataTransfer?.files\n depth = 0\n setDragging(false)\n if (!dropped?.length) return\n e.preventDefault()\n void addFilesRef.current(Array.from(dropped))\n }\n target.addEventListener('dragenter', onEnter)\n target.addEventListener('dragover', onOver)\n target.addEventListener('dragleave', onLeave)\n target.addEventListener('drop', onDropFiles)\n return () => {\n target.removeEventListener('dragenter', onEnter)\n target.removeEventListener('dragover', onOver)\n target.removeEventListener('dragleave', onLeave)\n target.removeEventListener('drop', onDropFiles)\n }\n }, [attachments, dropZone])\n\n // ── submit ──────────────────────────────────────────────────────────────────\n const submit = () => {\n const raw = text.trim()\n // While the agent works, text is said TO it; everything else waits for the next message.\n const intent = steerIntent({ raw, busy, steering, hasAttachments: pending.length > 0 })\n if (intent === 'steer') {\n // If the run ended a moment ago `send` refuses: the text stays, nothing is lost.\n if (agent.send(raw)) setText('')\n return\n }\n if (intent === 'attachments') {\n setAttachError(L.noAttachmentsWhileBusy)\n return\n }\n if (intent === 'ignore') return\n if (!ready) return\n const parsed = parseSlash(raw)\n if (parsed) {\n const cmd = allCommands.find((c) => c.name === parsed.name)\n if (cmd?.kind !== 'prefix') {\n if (cmd) {\n setText('')\n void cmd.run?.(parsed.args)\n }\n return\n }\n if (!parsed.args && pending.length === 0) return\n void send(cmd.transform ? cmd.transform(parsed.args) : parsed.args, raw)\n return\n }\n if (!raw && pending.length === 0) return\n void send(raw, raw)\n }\n\n const send = async (goal: string, shown: string) => {\n if (stt.listening) stt.stop()\n const items = pending\n setText('')\n setPending([])\n // Keep a copy in the workspace, so the agent's fs_* tools can reach it later.\n if (vfs) {\n for (const a of items) {\n const path = `/attachments/${safeName(a.name)}`\n try {\n if (a.dataUrl) await vfs.writeDataUrl(path, a.dataUrl)\n else if (a.text !== undefined) await vfs.write(path, a.text, { mimeType: a.mediaType })\n a.path = path\n } catch {\n /* the message still goes out without the copy */\n }\n }\n }\n const toModel = (a: ComposerAttachment): RunFile => ({\n data: a.dataUrl as string,\n mediaType: a.mediaType,\n name: a.name,\n })\n const shownAttachments: ChatAttachment[] = items.map((a) => ({\n name: a.name,\n mediaType: a.mediaType,\n size: a.bytes,\n ...(a.kind === 'image' && a.dataUrl ? { dataUrl: a.dataUrl } : {}),\n ...(a.path ? { path: a.path } : {}),\n }))\n const full = withAttachments(goal || L.seeAttachments, items)\n // The transcript shows the attachments as chips/thumbnails, not in the text.\n const label = shown || (items.length ? L.attachmentsOnly : '')\n void agent.run(full, {\n ...(full !== label ? { label } : {}),\n images: items.filter((a) => a.kind === 'image' && a.dataUrl).map(toModel),\n files: items.filter((a) => (a.kind === 'pdf' || a.kind === 'file') && a.dataUrl).map(toModel),\n attachments: shownAttachments,\n })\n }\n\n const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (paletteOpen) {\n if (e.key === 'ArrowDown') {\n e.preventDefault()\n setActive((i) => (i + 1) % palette.length)\n return\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault()\n setActive((i) => (i - 1 + palette.length) % palette.length)\n return\n }\n if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey && matches.length > 0)) {\n e.preventDefault()\n pick(palette[active] ?? palette[0])\n return\n }\n if (e.key === 'Escape') {\n setMenu(undefined)\n setText('')\n return\n }\n }\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault()\n submit()\n }\n }\n\n // ── notices ────────────────────────────────────────────────────────────────\n const notices = showNotices\n ? [\n ...noticesOf(agent, L.notices),\n ...(attachError\n ? [{ id: `attach:${attachError}`, tone: 'warn' as const, text: attachError }]\n : []),\n ...(stt.error\n ? [\n {\n id: `stt:${stt.error}`,\n tone: 'warn' as const,\n text: `${L.microphone}: ${stt.error}`,\n },\n ]\n : []),\n ].filter((n) => !dismissed.has(n.id))\n : []\n\n const runningAgents = agent.subagents.filter((s) => s.status === 'running')\n const thinkingOptions = thinking?.options ?? DEFAULT_THINKING\n const thinkingLabel = thinking\n ? (thinkingOptions.find((o) => o.id === thinking.value)?.label ?? thinking.value)\n : undefined\n const canSend = ready && (text.trim().length > 0 || pending.length > 0)\n const canSteer = busy && steering && text.trim().length > 0\n const queuedStrip =\n showQueued && (agent.queued.length > 0 || agent.undelivered.length > 0) ? (\n <div className=\"awr-queued\">\n {agent.queued.map((q) => (\n <div key={q.id} className=\"awr-queued__item\" role=\"status\">\n <ClockIcon size={13} className=\"awr-queued__icon\" />\n <span className=\"awr-queued__text\" title={q.text}>\n {q.text}\n </span>\n <span className=\"awr-queued__state\">{L.queuedWaiting}</span>\n </div>\n ))}\n {agent.undelivered.length > 0 && (\n <div className=\"awr-queued__item awr-queued__item--undelivered\" role=\"status\">\n <AlertIcon size={13} className=\"awr-queued__icon\" />\n <span className=\"awr-queued__text\" title={agent.undelivered.join('\\n\\n')}>\n {L.undelivered(agent.undelivered.length)}: {agent.undelivered.join(' · ')}\n </span>\n <button type=\"button\" className=\"awr-linkbtn\" onClick={agent.sendUndelivered}>\n {L.sendUndelivered}\n </button>\n <button type=\"button\" className=\"awr-linkbtn\" onClick={agent.discardUndelivered}>\n {L.discardUndelivered}\n </button>\n </div>\n )}\n </div>\n ) : null\n\n return (\n <div\n className={[\n 'awr-composer2',\n dragging ? 'is-dragging' : '',\n compactBar ? 'awr-composer2--compact' : '',\n className,\n ]\n .filter(Boolean)\n .join(' ')}\n ref={rootRef}\n >\n {dragging && (\n <div className=\"awr-dropnote\" style={dropRect} aria-hidden=\"true\">\n {L.dropHint}\n </div>\n )}\n {queuedStrip}\n {notices.length > 0 && (\n <div className=\"awr-notices\">\n {notices.map((n) => (\n <div key={n.id} className={`awr-notice awr-notice--${n.tone}`} role=\"status\">\n <span>{n.text}</span>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.dismiss}\n onClick={() => {\n setDismissed((d) => new Set(d).add(n.id))\n if (n.id.startsWith('attach:')) setAttachError(undefined)\n }}\n >\n <XIcon size={14} />\n </button>\n </div>\n ))}\n </div>\n )}\n\n {paletteOpen && (\n <ul\n className=\"awr-menu awr-menu--commands\"\n style={commandsStyle}\n role=\"listbox\"\n aria-label={L.commands}\n >\n {palette.map((c, i) => (\n <li key={`${c.group}:${c.name}`}>\n <button\n type=\"button\"\n role=\"option\"\n aria-selected={i === active}\n className={`awr-menu__item${i === active ? ' is-active' : ''}`}\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => pick(c)}\n >\n <code>/{c.name}</code>\n <span className=\"awr-menu__desc\">{c.description}</span>\n {c.group && <span className=\"awr-menu__group\">{c.group}</span>}\n </button>\n </li>\n ))}\n </ul>\n )}\n\n {pending.length > 0 && (\n <div className=\"awr-files\">\n {pending.map((a) => {\n const remove = () => setPending((cur) => cur.filter((x) => x.id !== a.id))\n if (renderAttachment) return <span key={a.id}>{renderAttachment(a, remove)}</span>\n return (\n <span key={a.id} className=\"awr-chip awr-file\" title={a.note ?? a.mediaType}>\n {a.kind === 'image' && a.dataUrl ? (\n <img className=\"awr-file__thumb\" src={a.dataUrl} alt={a.name} />\n ) : (\n <FileIcon size={14} />\n )}\n <span className=\"awr-file__name\">{a.name}</span>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.remove(a.name)}\n onClick={remove}\n >\n <XIcon size={12} />\n </button>\n </span>\n )\n })}\n </div>\n )}\n\n <div className=\"awr-composer2__inputrow\">\n <textarea\n ref={inputRef}\n className=\"awr-composer2__input\"\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={onKeyDown}\n onPaste={onPaste}\n placeholder={\n stt.listening\n ? L.listening\n : busy && steering\n ? L.placeholderBusy\n : (placeholder ?? L.placeholder)\n }\n disabled={disabled}\n rows={2}\n aria-label={L.message}\n />\n {showMic && (\n <button\n type=\"button\"\n className={`awr-iconbtn awr-mic${stt.listening ? ' is-on' : ''}`}\n aria-label={stt.listening ? L.stopDictation : L.dictate}\n title={stt.listening ? L.stopDictation : L.dictateTitle}\n onClick={stt.toggle}\n disabled={disabled}\n >\n <MicIcon size={18} />\n </button>\n )}\n </div>\n {stt.listening && stt.interim && <div className=\"awr-composer2__interim\">{stt.interim}</div>}\n\n <div className=\"awr-toolbar\">\n {attachments !== false && (\n <>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.attach}\n title={L.attachTitle}\n onClick={() => fileRef.current?.click()}\n disabled={disabled}\n >\n <PlusIcon size={18} />\n </button>\n <input\n ref={fileRef}\n type=\"file\"\n multiple\n hidden\n accept={attachCfg.accept}\n onChange={(e) => void addFiles(Array.from(e.target.files ?? []))}\n />\n </>\n )}\n <button\n type=\"button\"\n className={`awr-iconbtn${menu === 'commands' ? ' is-on' : ''}`}\n aria-label={L.commands}\n title={L.commandsTitle}\n onClick={() => setMenu(menu === 'commands' ? undefined : 'commands')}\n >\n <SlashIcon size={18} />\n </button>\n {toolbarExtra}\n {showTimer && elapsed !== undefined && (\n <span className=\"awr-tchip\" title={busy ? L.timerRunning : L.timerLast}>\n <ClockIcon size={14} /> {formatElapsed(elapsed)}\n </span>\n )}\n {showAgents && (\n <span\n className={`awr-tchip awr-agents${runningAgents.length ? ' is-busy' : ''}`}\n title={\n agent.subagents.length\n ? agent.subagents.map((s) => `${s.name} (${s.status}): ${s.task}`).join('\\n')\n : L.agentsTitle\n }\n >\n <span className=\"awr-agents__dot\" aria-hidden=\"true\" />\n <BotIcon size={14} />{' '}\n {compactBar ? runningAgents.length : L.agents(runningAgents.length)}\n </span>\n )}\n {(model || thinking) && (\n <span className=\"awr-popwrap awr-popwrap--model\" ref={modelRef}>\n <button\n type=\"button\"\n className=\"awr-tchip awr-tchip--btn\"\n onClick={() => setMenu(menu === 'model' ? undefined : 'model')}\n aria-haspopup=\"menu\"\n aria-expanded={menu === 'model'}\n title={[model?.label, thinkingLabel].filter(Boolean).join(' · ')}\n >\n <span className=\"awr-tchip__label\">{model?.label ?? L.model}</span>\n {thinkingLabel && !compactBar && (\n <span className=\"awr-tchip__sub\">{thinkingLabel}</span>\n )}\n </button>\n {menu === 'model' && (\n <div className=\"awr-menu awr-menu--pop\" style={modelStyle} role=\"menu\">\n {thinking && (\n <>\n <div className=\"awr-menu__head\">{L.thinking}</div>\n {thinkingOptions.map((o) => (\n <button\n key={o.id}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={thinking.value === o.id}\n className={`awr-menu__item${thinking.value === o.id ? ' is-active' : ''}`}\n onClick={() => {\n thinking.onChange(o.id)\n setMenu(undefined)\n }}\n >\n {o.label}\n </button>\n ))}\n </>\n )}\n {model?.options?.length ? (\n <>\n <div className=\"awr-menu__head\">{L.model}</div>\n {model.options.map((o) => (\n <button\n key={o.id}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={model.value === o.id}\n className={`awr-menu__item${model.value === o.id ? ' is-active' : ''}`}\n onClick={() => {\n model.onSelect?.(o.id)\n setMenu(undefined)\n }}\n >\n {o.label}\n {o.group && <span className=\"awr-menu__group\">{o.group}</span>}\n </button>\n ))}\n </>\n ) : null}\n </div>\n )}\n </span>\n )}\n\n <span className=\"awr-toolbar__spacer\" />\n {toolbarEnd}\n\n {showApprovalMode && (\n <span className=\"awr-popwrap\" ref={modeRef}>\n <button\n type=\"button\"\n className={`awr-tchip awr-tchip--btn awr-mode awr-mode--${agent.approvalMode}`}\n title={MODE_CHIP[agent.approvalMode].hint}\n onClick={() => setMenu(menu === 'mode' ? undefined : 'mode')}\n aria-haspopup=\"menu\"\n aria-expanded={menu === 'mode'}\n aria-label={`${L.toolConsent}: ${MODE_CHIP[agent.approvalMode].label}`}\n >\n <ModeIcon mode={agent.approvalMode} />\n {!compactBar && ` ${MODE_CHIP[agent.approvalMode].label}`}\n </button>\n {menu === 'mode' && (\n <div className=\"awr-menu awr-menu--pop\" style={modeStyle} role=\"menu\">\n <div className=\"awr-menu__head\">{L.toolConsent}</div>\n {MODES.map((m) => (\n <button\n key={m}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={agent.approvalMode === m}\n className={`awr-menu__item${agent.approvalMode === m ? ' is-active' : ''}`}\n onClick={() => {\n agent.setApprovalMode(m)\n setMenu(undefined)\n }}\n >\n <ModeIcon mode={m} /> {MODE_CHIP[m].label}\n <span className=\"awr-menu__desc\">{MODE_CHIP[m].hint}</span>\n </button>\n ))}\n </div>\n )}\n </span>\n )}\n\n {canSteer && (\n <button type=\"button\" className=\"awr-sendbtn\" onClick={submit} aria-label={L.steer}>\n <SendIcon size={16} />\n </button>\n )}\n {busy ? (\n <button\n type=\"button\"\n className=\"awr-sendbtn awr-sendbtn--stop\"\n onClick={agent.stop}\n aria-label={L.stop}\n >\n <StopIcon size={16} />\n </button>\n ) : (\n <button\n type=\"button\"\n className=\"awr-sendbtn\"\n onClick={submit}\n disabled={!canSend}\n aria-label={L.send}\n >\n {agent.status === 'initializing' ? <SpinnerIcon size={16} /> : <SendIcon size={16} />}\n </button>\n )}\n </div>\n </div>\n )\n}\n","// Tiny inline SVG icons — no icon-font or image dependency. Each inherits the\n// current text color (`stroke=\"currentColor\"`) and takes an optional size.\n\nexport interface IconProps {\n size?: number\n className?: string\n}\n\nconst base = (size = 16) => ({\n width: size,\n height: size,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round' as const,\n strokeLinejoin: 'round' as const,\n 'aria-hidden': true,\n})\n\nexport const SendIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M22 2 11 13\" />\n <path d=\"M22 2 15 22l-4-9-9-4Z\" />\n </svg>\n)\n\nexport const StopIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n </svg>\n)\n\nexport const SpinnerIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={['awr-spin', className].filter(Boolean).join(' ')}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </svg>\n)\n\nexport const CheckIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n)\n\nexport const AlertIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </svg>\n)\n\nexport const ToolIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z\" />\n </svg>\n)\n\nexport const ChevronIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n)\n\nexport const ShieldIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n </svg>\n)\n\nexport const BrainIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M9 3a3 3 0 0 0-3 3 3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 6 1V4a3 3 0 0 0-3-1Z\" />\n <path d=\"M15 3a3 3 0 0 1 3 3 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-6 1\" />\n </svg>\n)\n\nexport const BotIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"4\" y=\"8\" width=\"16\" height=\"12\" rx=\"3\" />\n <path d=\"M12 8V4\" />\n <path d=\"M9 14h.01M15 14h.01\" />\n </svg>\n)\n\nexport const PlusIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n)\n\nexport const SlashIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"3\" />\n <path d=\"m15 7-6 10\" />\n </svg>\n)\n\nexport const ClockIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M12 7v5l3 2\" />\n </svg>\n)\n\nexport const MicIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5 11a7 7 0 0 0 14 0M12 18v3\" />\n </svg>\n)\n\nexport const BoltIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M13 2 4 14h7l-1 8 9-12h-7Z\" />\n </svg>\n)\n\nexport const EyeIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </svg>\n)\n\nexport const XIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n)\n\nexport const FileIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z\" />\n <path d=\"M14 3v6h6\" />\n </svg>\n)\n\nexport const HistoryIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M3 12a9 9 0 1 0 3-6.7L3 8\" />\n <path d=\"M3 3v5h5M12 7v5l3 2\" />\n </svg>\n)\n\nexport const BookIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2Z\" />\n <path d=\"M4 19V5M9 7h6\" />\n </svg>\n)\n\nexport const GlobeIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M3 12h18M12 3c3 3.2 3 14.8 0 18M12 3c-3 3.2-3 14.8 0 18\" />\n </svg>\n)\n\nexport const DownloadIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 3v12m-5-5 5 5 5-5M5 21h14\" />\n </svg>\n)\n","import { Fragment } from 'react'\nimport type { ReactNode } from 'react'\nimport type { ChatSummary } from '../chat-history.js'\nimport type { UseChatHistoryReturn } from '../hooks/use-chat-history.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { PlusIcon, XIcon } from './icons.js'\n\nexport interface ChatHistoryListProps {\n /** From `useChatHistory(agent)`. */\n history: UseChatHistoryReturn\n title?: ReactNode\n /** Disable switching (e.g. while a run is in flight). */\n disabled?: boolean\n /** Render an entry yourself; `fallback` is the built-in `<li>` — return it, or your own `<li>`. */\n renderChat?: (chat: ChatSummary, active: boolean, fallback: ReactNode) => ReactNode\n /** Format an entry's time (default: locale date + time). */\n formatTime?: (ms: number) => string\n labels?: AgentLabelsOverride\n className?: string\n}\n\nconst defaultTime = (ms: number): string => {\n const d = new Date(ms)\n const today = new Date().toDateString() === d.toDateString()\n return today\n ? d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n : d.toLocaleDateString()\n}\n\n/** The saved conversations: a \"New chat\" button, then one row per chat (newest first). */\nexport const ChatHistoryList = ({\n history,\n title,\n disabled,\n renderChat,\n formatTime = defaultTime,\n labels,\n className,\n}: ChatHistoryListProps) => {\n const L = useLabels(labels)\n return (\n <div className={['awr-history', className].filter(Boolean).join(' ')}>\n <div className=\"awr-panel__head\">\n <span className=\"awr-panel__title\">{title ?? L.history}</span>\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--ghost awr-history__new\"\n onClick={history.newChat}\n disabled={disabled}\n >\n <PlusIcon size={14} /> {L.newChat}\n </button>\n </div>\n {!history.loading && history.chats.length === 0 && (\n <div className=\"awr-panel__empty\">{L.historyEmpty}</div>\n )}\n <ul className=\"awr-history__list\">\n {history.chats.map((c) => {\n const active = c.id === history.currentId\n const row = (\n <li key={c.id} className={`awr-history__item${active ? ' is-active' : ''}`}>\n <button\n type=\"button\"\n className=\"awr-history__open\"\n onClick={() => void history.select(c.id)}\n disabled={disabled || active}\n aria-current={active ? 'true' : undefined}\n >\n <span className=\"awr-history__title\">{c.title}</span>\n <span className=\"awr-history__meta\">\n {formatTime(c.updatedAt)} · {L.messagesCount(c.messageCount)}\n </span>\n </button>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={`${L.deleteChat}: ${c.title}`}\n title={L.deleteChat}\n onClick={() => void history.remove(c.id)}\n disabled={disabled}\n >\n <XIcon size={14} />\n </button>\n </li>\n )\n return renderChat ? <Fragment key={c.id}>{renderChat(c, active, row)}</Fragment> : row\n })}\n </ul>\n </div>\n )\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","import type { IUsage } from '@dudko.dev/agent-web'\nimport type { BudgetView, CompactionView } from '../types.js'\nimport { formatTokens } from './format.js'\n\nexport interface ContextMeterProps {\n usage: IUsage\n /** A run budget to draw the bar against (e.g. limits.maxTotalTokens). */\n budgetTokens?: number\n /** The limit that stopped the run, if any. */\n budget?: BudgetView\n compactions?: CompactionView[]\n /** Show a \"Compact\" button (e.g. `agent.compact`). */\n onCompact?: () => void\n compacting?: boolean\n className?: string\n}\n\n/**\n * Where the run's tokens went — input, output, thinking, prompt-cache hits —\n * with an optional budget bar, the last compaction and a \"Compact\" button.\n */\nexport const ContextMeter = ({\n usage,\n budgetTokens,\n budget,\n compactions = [],\n onCompact,\n compacting,\n className,\n}: ContextMeterProps) => {\n const cached = usage.cachedInputTokens ?? 0\n const reasoning = usage.reasoningTokens ?? 0\n // Nothing spent, nothing compacted, no budget to show: stay out of the way.\n if (usage.totalTokens === 0 && !budget && compactions.length === 0 && !budgetTokens) {\n return null\n }\n const hitRate = usage.inputTokens > 0 ? Math.round((cached / usage.inputTokens) * 100) : 0\n const fill = budgetTokens ? Math.min(1, usage.totalTokens / budgetTokens) : undefined\n const last = compactions.at(-1)\n return (\n <div className={['awr-context', className].filter(Boolean).join(' ')}>\n <div className=\"awr-context__row\">\n <span title=\"input tokens\">in {formatTokens(usage.inputTokens)}</span>\n <span title=\"output tokens\">out {formatTokens(usage.outputTokens)}</span>\n {reasoning > 0 && <span title=\"thinking tokens\">think {formatTokens(reasoning)}</span>}\n <span title=\"input tokens served from the provider's prompt cache\">\n cached {formatTokens(cached)}\n {hitRate > 0 ? ` (${hitRate}%)` : ''}\n </span>\n {onCompact && (\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--ghost awr-context__compact\"\n onClick={onCompact}\n disabled={compacting}\n >\n {compacting ? 'Compacting…' : 'Compact'}\n </button>\n )}\n </div>\n {fill !== undefined && (\n <div\n className={`awr-context__track${fill >= 1 ? ' is-full' : ''}`}\n title={`${usage.totalTokens} / ${budgetTokens} tokens`}\n >\n <div className=\"awr-context__fill\" style={{ width: `${fill * 100}%` }} />\n </div>\n )}\n {budget && (\n <div className=\"awr-context__note awr-context__note--warn\">\n {budget.kind === 'tool-calls' ? 'Tool-call' : `${budget.kind} token`} limit reached (\n {budget.tokens}/{budget.cap}) — the agent stopped early.\n </div>\n )}\n {last && (\n <div className=\"awr-context__note\">\n Compacted {last.scope}: {formatTokens(last.beforeTokens)} →{' '}\n {formatTokens(last.afterTokens)} tokens\n </div>\n )}\n </div>\n )\n}\n","import { Fragment, useEffect, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { VirtualFileInfo, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { useVirtualFiles } from '../hooks/use-virtual-files.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { DownloadIcon, FileIcon, PlusIcon, XIcon } from './icons.js'\n\nexport interface FilesPanelProps {\n /** The workspace (the core's `VirtualFileSystem`). */\n files: VirtualFileSystem\n /** Only list paths under this prefix (default '/'). */\n prefix?: string\n title?: ReactNode\n /** Upload button (default true). */\n allowUpload?: boolean\n /** Delete buttons (default true). */\n allowDelete?: boolean\n /** Directory uploads go to (default '/uploads'). */\n uploadDir?: string\n /** Called when a file row is clicked (in addition to the preview). */\n onOpen?: (file: VirtualFileInfo) => void\n /** Render a row yourself; `fallback` is the built-in `<li>` — return it, or your own `<li>`. */\n renderFile?: (file: VirtualFileInfo, fallback: ReactNode) => ReactNode\n labels?: AgentLabelsOverride\n className?: string\n}\n\ntype Preview =\n { path: string; kind: 'image'; src: string } | { path: string; kind: 'text'; text: string }\n\nconst PREVIEW_CHARS = 20_000\n\n/**\n * The agent's workspace — attachments the user dropped in, files the agent\n * wrote with its `fs_*` tools — live, with a preview (text / image),\n * download, delete and upload.\n */\nexport const FilesPanel = ({\n files: vfs,\n prefix = '/',\n title,\n allowUpload = true,\n allowDelete = true,\n uploadDir,\n onOpen,\n renderFile,\n labels,\n className,\n}: FilesPanelProps) => {\n const L = useLabels(labels)\n const fs = useVirtualFiles(vfs, prefix)\n const [preview, setPreview] = useState<Preview | undefined>()\n const inputRef = useRef<HTMLInputElement>(null)\n\n // Drop a preview whose file went away.\n useEffect(() => {\n if (preview && !fs.files.some((f) => f.path === preview.path)) setPreview(undefined)\n }, [fs.files, preview])\n\n const open = async (f: VirtualFileInfo) => {\n onOpen?.(f)\n if (preview?.path === f.path) return setPreview(undefined)\n if (f.mimeType.startsWith('image/')) {\n const src = await fs.dataUrl(f.path)\n if (src) setPreview({ path: f.path, kind: 'image', src })\n return\n }\n const text = await fs.text(f.path)\n if (text !== undefined) setPreview({ path: f.path, kind: 'text', text })\n else setPreview(undefined)\n }\n\n const download = async (f: VirtualFileInfo) => {\n const href = await fs.dataUrl(f.path)\n if (!href) return\n const a = document.createElement('a')\n a.href = href\n a.download = f.path.split('/').pop() || 'file'\n a.click()\n }\n\n return (\n <div className={['awr-filespanel', className].filter(Boolean).join(' ')}>\n <div className=\"awr-panel__head\">\n <span className=\"awr-panel__title\">{title ?? L.files}</span>\n {allowUpload && (\n <>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.upload}\n title={L.upload}\n onClick={() => inputRef.current?.click()}\n >\n <PlusIcon size={16} />\n </button>\n <input\n ref={inputRef}\n type=\"file\"\n multiple\n hidden\n onChange={async (e) => {\n for (const f of Array.from(e.target.files ?? [])) await fs.upload(f, uploadDir)\n e.target.value = ''\n }}\n />\n </>\n )}\n </div>\n {fs.error && <div className=\"awr-notice awr-notice--warn\">{fs.error}</div>}\n {!fs.loading && fs.files.length === 0 && (\n <div className=\"awr-panel__empty\">{L.filesEmpty}</div>\n )}\n <ul className=\"awr-filelist\">\n {fs.files.map((f) => {\n const row = (\n <li\n key={f.path}\n className={`awr-filelist__item${preview?.path === f.path ? ' is-active' : ''}`}\n >\n <button\n type=\"button\"\n className=\"awr-filelist__open\"\n onClick={() => void open(f)}\n title={`${L.preview}: ${f.path}`}\n >\n <FileIcon size={14} />\n <span className=\"awr-filelist__path\">{f.path}</span>\n <span className=\"awr-filelist__size\">{L.bytes(f.size)}</span>\n </button>\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={`${L.download} ${f.path}`}\n title={L.download}\n onClick={() => void download(f)}\n >\n <DownloadIcon size={14} />\n </button>\n {allowDelete && (\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={`${L.delete} ${f.path}`}\n title={L.delete}\n onClick={() => void fs.remove(f.path)}\n >\n <XIcon size={14} />\n </button>\n )}\n </li>\n )\n return renderFile ? <Fragment key={f.path}>{renderFile(f, row)}</Fragment> : row\n })}\n </ul>\n {preview && (\n <div className=\"awr-filepreview\">\n {preview.kind === 'image' ? (\n <img src={preview.src} alt={preview.path} />\n ) : (\n <pre>\n {preview.text.length > PREVIEW_CHARS\n ? `${preview.text.slice(0, PREVIEW_CHARS)}\\n…`\n : preview.text}\n </pre>\n )}\n </div>\n )}\n </div>\n )\n}\n","import { Fragment } from 'react'\nimport type { ReactNode } from 'react'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ApprovalView, StepView, SubagentView, ToolCallView, UserNoteView } from '../types.js'\nimport { formatDuration, formatTokens, imagesInOutput, previewValue } from './format.js'\nimport {\n AlertIcon,\n BotIcon,\n BrainIcon,\n CheckIcon,\n SendIcon,\n ShieldIcon,\n SpinnerIcon,\n StopIcon,\n ToolIcon,\n} from './icons.js'\n\n/** Render a tool call yourself; `fallback` is the built-in `<li>` row — return it, or your own `<li>`. */\nexport type RenderToolCall = (call: ToolCallView, fallback: ReactNode) => ReactNode\n\nexport interface ToolCallRowProps {\n call: ToolCallView\n showUsage?: boolean\n labels?: AgentLabelsOverride\n}\n\n/** One tool call: name, arguments, status — and optionally its cost and any images it returned. */\nexport const ToolCallRow = ({ call, showUsage = true, labels }: ToolCallRowProps) => {\n const L = useLabels(labels)\n const state = call.status === 'calling' ? 'calling' : call.ok === false ? 'failed' : 'ok'\n const images = call.ok === false ? [] : imagesInOutput(call.output).slice(0, 4)\n const cost = [\n call.inputTokens ? `≈${formatTokens(call.inputTokens)} in` : '',\n call.outputTokens ? `≈${formatTokens(call.outputTokens)} out` : '',\n call.durationMs !== undefined ? formatDuration(call.durationMs) : '',\n ]\n .filter(Boolean)\n .join(' · ')\n return (\n <li className={`awr-tool awr-tool--${state}`}>\n <div className=\"awr-tool__row\">\n <ToolIcon size={13} className=\"awr-tool__icon\" />\n <code className=\"awr-tool__name\">{call.name}</code>\n {previewValue(call.input) && (\n <span className=\"awr-tool__args\">{previewValue(call.input)}</span>\n )}\n {call.status === 'calling' && <SpinnerIcon size={12} className=\"awr-tool__spin\" />}\n {call.status === 'done' && call.ok === false && (\n <span className=\"awr-tool__badge\">{L.failed}</span>\n )}\n {showUsage && cost && (\n <span className=\"awr-tool__cost\" title={L.toolCostTitle}>\n {cost}\n </span>\n )}\n </div>\n {images.length > 0 && (\n <div className=\"awr-tool__images\">\n {images.map((src, i) => (\n <a key={i} href={src} target=\"_blank\" rel=\"noreferrer\">\n <img className=\"awr-thumb\" src={src} alt={`${call.name} result ${i + 1}`} />\n </a>\n ))}\n </div>\n )}\n </li>\n )\n}\n\n/**\n * A subagent delegation: name, task, live activity, and its answer when done. With\n * `onStop`, a running one gets a stop button (the run and its siblings go on).\n */\nexport const SubagentRow = ({\n sub,\n onStop,\n labels,\n}: {\n sub: SubagentView\n /** Stop this subagent (`useAgent().stopSubagent`); the button shows while it runs. */\n onStop?: (id: string) => void\n labels?: AgentLabelsOverride\n}) => {\n const L = useLabels(labels)\n return (\n <li className={`awr-subagent awr-subagent--${sub.status}`}>\n <div className=\"awr-subagent__head\">\n <BotIcon size={13} className=\"awr-subagent__icon\" />\n <span className=\"awr-subagent__name\">{sub.name}</span>\n {sub.profile && <span className=\"awr-subagent__profile\">{sub.profile}</span>}\n <span className=\"awr-subagent__task\" title={sub.task}>\n {previewValue(sub.task, 90)}\n </span>\n {sub.status === 'running' && <SpinnerIcon size={12} className=\"awr-tool__spin\" />}\n {sub.status === 'running' && onStop && (\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-subagent__stop\"\n aria-label={L.stopSubagent}\n title={L.stopSubagent}\n onClick={() => onStop(sub.id)}\n >\n <StopIcon size={12} />\n </button>\n )}\n </div>\n <div className=\"awr-subagent__activity\">\n {sub.status === 'error'\n ? sub.error\n : sub.status === 'stopped'\n ? L.subagentStopped\n : sub.status === 'done'\n ? previewValue(sub.text, 160)\n : `${sub.activity}${sub.toolCalls ? ` · ${L.toolCalls(sub.toolCalls)}` : ''}`}\n </div>\n </li>\n )\n}\n\n/** What the user said while the run was going, and where it reached the agent. */\nexport const UserNoteRow = ({\n note,\n labels,\n}: {\n note: UserNoteView\n labels?: AgentLabelsOverride\n}) => {\n const L = useLabels(labels)\n return (\n <li className={`awr-note awr-note--${note.at}`}>\n <SendIcon size={12} className=\"awr-note__icon\" />\n <span className=\"awr-note__where\">{L.noteAt[note.at]}</span>\n <q className=\"awr-note__text\">{note.text}</q>\n </li>\n )\n}\n\nconst decisionLabel = (a: ApprovalView, L: AgentLabels): string =>\n a.status === 'pending'\n ? L.consentWaiting\n : a.status === 'approved'\n ? L.consentAllowed\n : L.consentDenied(a.reason)\n\ninterface StepItemProps {\n step: StepView\n subagents: SubagentView[]\n approvals: ApprovalView[]\n notes: UserNoteView[]\n onStopSubagent?: (id: string) => void\n showToolCalls: boolean\n showUsage: boolean\n showThoughts: boolean\n renderToolCall?: RenderToolCall\n L: AgentLabels\n}\n\nconst StepItem = ({\n step,\n subagents,\n approvals,\n notes,\n onStopSubagent,\n showToolCalls,\n showUsage,\n showThoughts,\n renderToolCall,\n L,\n}: StepItemProps) => (\n <li className={`awr-step awr-step--${step.blocked ? 'blocked' : step.status}`}>\n <div className=\"awr-step__head\">\n <span className=\"awr-step__marker\">\n {step.status === 'running' ? (\n <SpinnerIcon size={14} />\n ) : step.blocked ? (\n <AlertIcon size={14} />\n ) : (\n <CheckIcon size={14} />\n )}\n </span>\n <span className=\"awr-step__index\">\n {step.index}/{step.total}\n </span>\n <span className=\"awr-step__desc\">{step.step.description}</span>\n </div>\n {showThoughts && step.reasoning.trim() && (\n <details className=\"awr-thought\" open={step.status === 'running' && !step.text}>\n <summary>\n <BrainIcon size={13} /> {L.stepThoughts}\n </summary>\n <p className=\"awr-thought__text\">{step.reasoning.trim()}</p>\n </details>\n )}\n {step.text.trim() && <p className=\"awr-step__text\">{step.text.trim()}</p>}\n {showToolCalls && step.toolCalls.length > 0 && (\n <ul className=\"awr-step__tools\">\n {step.toolCalls.map((call, i) => {\n const row = <ToolCallRow key={i} call={call} showUsage={showUsage} />\n return renderToolCall ? <Fragment key={i}>{renderToolCall(call, row)}</Fragment> : row\n })}\n </ul>\n )}\n {approvals.length > 0 && (\n <ul className=\"awr-step__tools\">\n {approvals.map((a) => (\n <li key={a.id} className={`awr-tool awr-tool__row awr-tool--approval-${a.status}`}>\n <ShieldIcon size={13} className=\"awr-tool__icon\" />\n <code className=\"awr-tool__name\">{a.name}</code>\n <span className=\"awr-tool__args\">{decisionLabel(a, L)}</span>\n </li>\n ))}\n </ul>\n )}\n {subagents.length > 0 && (\n <ul className=\"awr-subagents\">\n {subagents.map((sub) => (\n <SubagentRow key={sub.id} sub={sub} onStop={onStopSubagent} />\n ))}\n </ul>\n )}\n {notes.length > 0 && (\n <ul className=\"awr-notes\">\n {notes.map((n) => (\n <UserNoteRow key={n.id} note={n} />\n ))}\n </ul>\n )}\n {step.blocked && step.summary && <p className=\"awr-step__blocked\">{step.summary}</p>}\n </li>\n)\n\nexport interface StepListProps {\n steps: StepView[]\n /** Subagent delegations (`agent.subagents`) — shown under the step that made them. */\n subagents?: SubagentView[]\n /** Consent decisions (`agent.approvals`) — shown under their step. */\n approvals?: ApprovalView[]\n /** What the user said mid-run (`agent.notes`) — shown under the step it reached. */\n notes?: UserNoteView[]\n /** Show those notes (default true). */\n showNotes?: boolean\n /** Give a running subagent a stop button (`agent.stopSubagent`). */\n onStopSubagent?: (id: string) => void\n /** Show each tool call (default true). */\n showToolCalls?: boolean\n /** Show each tool call's ≈tokens and duration (default true). */\n showUsage?: boolean\n /** Show each step's thoughts when the model thinks (default true). */\n showThoughts?: boolean\n /** Render tool calls yourself (gets the built-in row as `fallback`). */\n renderToolCall?: RenderToolCall\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * The live execution: each step, its thoughts, streamed text, tool calls,\n * consent decisions and subagent delegations.\n */\nexport const StepList = ({\n steps,\n subagents = [],\n approvals = [],\n notes = [],\n showNotes = true,\n onStopSubagent,\n showToolCalls = true,\n showUsage = true,\n showThoughts = true,\n renderToolCall,\n labels,\n className,\n}: StepListProps) => {\n const L = useLabels(labels)\n if (steps.length === 0) return null\n const known = new Set(steps.map((s) => s.id))\n // A note tied to a step shows under it; one said before the answer (or whose step is\n // gone) shows at the end.\n const atEnd = showNotes ? notes.filter((n) => !n.stepId || !known.has(n.stepId)) : []\n return (\n <ol className={['awr-steps', className].filter(Boolean).join(' ')}>\n {steps.map((step) => (\n <StepItem\n key={step.id}\n step={step}\n subagents={subagents.filter((s) => s.stepId === step.id)}\n approvals={approvals.filter((a) => a.stepId === step.id && a.status !== 'pending')}\n notes={showNotes ? notes.filter((n) => n.stepId === step.id) : []}\n onStopSubagent={onStopSubagent}\n showToolCalls={showToolCalls}\n showUsage={showUsage}\n showThoughts={showThoughts}\n renderToolCall={renderToolCall}\n L={L}\n />\n ))}\n {atEnd.length > 0 && (\n <li className=\"awr-step awr-step--notes\">\n <ul className=\"awr-notes\">\n {atEnd.map((n) => (\n <UserNoteRow key={n.id} note={n} />\n ))}\n </ul>\n </li>\n )}\n </ol>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { IUsage } from '@dudko.dev/agent-web'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ChatAttachment, ChatMessage } from '../types.js'\nimport { formatDuration, formatTokens } from './format.js'\nimport { BookIcon, BrainIcon, FileIcon, GlobeIcon, SpinnerIcon } from './icons.js'\nimport { StepList, type RenderToolCall } from './StepList.js'\n\nexport interface MessageListProps {\n messages: ChatMessage[]\n /** Rendered when there are no messages yet. */\n empty?: ReactNode\n /** Each answer's steps, thoughts, subagents and consent decisions (default true). */\n showActivity?: boolean\n /** Each tool call inside the activity (default true). */\n showToolCalls?: boolean\n /** Tokens per answer and per tool call (default true). */\n showUsage?: boolean\n /** Thoughts (step + answer) when the model thinks (default true). */\n showThoughts?: boolean\n /** What the user said while the agent worked, under the step it reached (default true). */\n showNotes?: boolean\n /** The lessons the agent wrote down during the answer, and the pages it fetched (default true). */\n showLearned?: boolean\n /** Give a running subagent a stop button (`useAgent().stopSubagent`). */\n onStopSubagent?: (id: string) => void\n /** Open the activity of finished answers too (default: only while it runs). */\n activityOpen?: boolean\n /** Extra content under the latest assistant turn while it streams (plan thought, …). */\n liveExtra?: ReactNode\n /**\n * A message's text — e.g. through your markdown renderer. Default: plain\n * text, line breaks kept.\n */\n renderContent?: (message: ChatMessage) => ReactNode\n /** A whole message; `fallback` is the built-in one, to wrap or ignore. */\n renderMessage?: (message: ChatMessage, fallback: ReactNode) => ReactNode\n /** An attachment shown with a message (thumbnail / chip by default). */\n renderAttachment?: (attachment: ChatAttachment, message: ChatMessage) => ReactNode\n /** Tool calls inside the activity. */\n renderToolCall?: RenderToolCall\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/** \"in 12k · out 456 · think 120 · cached 9k · 4.2 s\" for one answer. */\nexport const usageLine = (usage: IUsage | undefined, durationMs?: number): string => {\n const parts: string[] = []\n if (usage && usage.totalTokens > 0) {\n parts.push(`in ${formatTokens(usage.inputTokens)}`, `out ${formatTokens(usage.outputTokens)}`)\n if (usage.reasoningTokens) parts.push(`think ${formatTokens(usage.reasoningTokens)}`)\n if (usage.cachedInputTokens) parts.push(`cached ${formatTokens(usage.cachedInputTokens)}`)\n }\n if (durationMs !== undefined) parts.push(formatDuration(durationMs))\n return parts.join(' · ')\n}\n\n/** The built-in attachment: an image thumbnail (opens full size) or a file chip. */\nexport const AttachmentView = ({ attachment: a }: { attachment: ChatAttachment }) =>\n a.dataUrl && a.mediaType.startsWith('image/') ? (\n <a href={a.dataUrl} target=\"_blank\" rel=\"noreferrer\" title={a.path ?? a.name}>\n <img className=\"awr-thumb awr-thumb--msg\" src={a.dataUrl} alt={a.name} />\n </a>\n ) : (\n <span className=\"awr-chip awr-file\" title={a.path ?? a.mediaType}>\n <FileIcon size={13} /> {a.name}\n </span>\n )\n\nconst toolCallCount = (m: ChatMessage): number =>\n (m.steps ?? []).reduce((n, s) => n + s.toolCalls.length, 0)\n\nconst activitySummary = (\n m: ChatMessage,\n showToolCalls: boolean,\n showLearned: boolean,\n L: AgentLabels,\n): string => {\n const steps = m.steps ?? []\n const parts = [L.steps(steps.length)]\n if (showToolCalls) parts.push(L.toolCalls(toolCallCount(m)))\n if (m.subagents?.length) parts.push(L.subagents(m.subagents.length))\n if (m.skills?.length) parts.push(L.skillsUsed(m.skills.join(', ')))\n if (showLearned && m.learned?.length) parts.push(L.learnedNow(m.learned.join(', ')))\n if (showLearned && m.fetches?.length) parts.push(L.fetches(m.fetches.length))\n return parts.join(' · ')\n}\n\n/**\n * The chat transcript. User turns show their text and attachments (image\n * thumbnails, file chips); every assistant turn keeps its own activity — the\n * steps with each tool call (≈tokens, duration, returned images), thoughts,\n * subagents, consent decisions — and the tokens it spent by kind. Every part\n * can be hidden, relabelled or rendered by the host.\n */\nexport const MessageList = ({\n messages,\n empty,\n showActivity = true,\n showToolCalls = true,\n showUsage = true,\n showThoughts = true,\n showNotes = true,\n showLearned = true,\n onStopSubagent,\n activityOpen = false,\n liveExtra,\n renderContent,\n renderMessage,\n renderAttachment,\n renderToolCall,\n labels,\n className,\n}: MessageListProps) => {\n const L = useLabels(labels)\n if (messages.length === 0) {\n return empty ? <div className=\"awr-messages__empty\">{empty}</div> : null\n }\n return (\n <div className={['awr-messages', className].filter(Boolean).join(' ')}>\n {messages.map((m) => {\n const steps = m.steps ?? []\n const hasActivity =\n showActivity &&\n (steps.length > 0 || (m.subagents?.length ?? 0) > 0 || (m.pending && !!liveExtra))\n const usage = showUsage ? usageLine(m.usage, m.durationMs) : ''\n const node = (\n <div\n key={m.id}\n className={`awr-msg awr-msg--${m.role}${m.error ? ' awr-msg--error' : ''}${m.pending ? ' is-pending' : ''}`}\n >\n <div className=\"awr-msg__col\">\n {m.role === 'assistant' && hasActivity && (\n <details className=\"awr-activity\" open={m.pending || activityOpen}>\n <summary className=\"awr-activity__summary\">\n {activitySummary(m, showToolCalls, showLearned, L)}\n </summary>\n {m.pending && liveExtra}\n <StepList\n steps={steps}\n subagents={m.subagents}\n approvals={m.approvals}\n notes={m.notes}\n showNotes={showNotes}\n onStopSubagent={m.pending ? onStopSubagent : undefined}\n showToolCalls={showToolCalls}\n showUsage={showUsage}\n showThoughts={showThoughts}\n renderToolCall={renderToolCall}\n labels={labels}\n />\n {showLearned && m.fetches?.length ? (\n <ul className=\"awr-fetches\">\n {m.fetches.map((f, i) => (\n <li\n key={i}\n className={`awr-fetch${f.allowed ? '' : ' awr-fetch--refused'}`}\n >\n <GlobeIcon size={12} /> <code>{f.url}</code>{' '}\n <span className=\"awr-fetch__result\">\n {f.allowed ? (f.status ?? 'ok') : L.fetchRefused(f.reason ?? '')}\n </span>\n </li>\n ))}\n </ul>\n ) : null}\n {showLearned && m.learned?.length ? (\n <p className=\"awr-learned\">\n <BookIcon size={12} /> {L.learnedNow(m.learned.join(', '))}\n </p>\n ) : null}\n {showThoughts && m.reasoning?.trim() && (\n <details className=\"awr-thought\">\n <summary>\n <BrainIcon size={13} /> {L.answerThoughts}\n </summary>\n <p className=\"awr-thought__text\">{m.reasoning.trim()}</p>\n </details>\n )}\n </details>\n )}\n {(m.content || m.pending || !m.attachments?.length) && (\n <div className=\"awr-msg__bubble\">\n {m.content ? (renderContent ? renderContent(m) : m.content) : null}\n {m.pending && !m.content && (\n <SpinnerIcon size={14} className=\"awr-msg__pending\" />\n )}\n </div>\n )}\n {m.attachments?.length ? (\n <div className=\"awr-msg__attachments\" aria-label={L.attachments}>\n {m.attachments.map((a, i) => (\n <span key={i} className=\"awr-msg__attachment\">\n {renderAttachment ? (\n renderAttachment(a, m)\n ) : (\n <AttachmentView attachment={a} />\n )}\n </span>\n ))}\n </div>\n ) : null}\n {m.role === 'assistant' && usage && !m.pending && (\n <div className=\"awr-msg__usage\" title={L.usageTitle}>\n {usage}\n </div>\n )}\n </div>\n </div>\n )\n return renderMessage ? <div key={m.id}>{renderMessage(m, node)}</div> : node\n })}\n </div>\n )\n}\n","import type { ModelLoadState } from '../types.js'\n\nexport interface ModelLoadBarProps {\n load: ModelLoadState\n className?: string\n}\n\n/** A progress bar for WebLLM weight download / engine init (0..1). */\nexport const ModelLoadBar = ({ load, className }: ModelLoadBarProps) => {\n const pct = Math.round(Math.max(0, Math.min(1, load.progress)) * 100)\n return (\n <div className={['awr-modelload', className].filter(Boolean).join(' ')}>\n <div className=\"awr-modelload__head\">\n <span className=\"awr-modelload__text\">{load.text || 'Loading model…'}</span>\n <span className=\"awr-modelload__pct\">{pct}%</span>\n </div>\n <div className=\"awr-modelload__track\" role=\"progressbar\" aria-valuenow={pct}>\n <div className=\"awr-modelload__fill\" style={{ width: `${pct}%` }} />\n </div>\n </div>\n )\n}\n","import type { ReactNode } from 'react'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ApprovalView } from '../types.js'\nimport { previewValue } from './format.js'\nimport { ShieldIcon } from './icons.js'\n\nexport interface ToolApprovalPromptProps {\n /** Pending requests (e.g. `agent.pendingApprovals`). */\n approvals: ApprovalView[]\n onApprove: (id: string, options?: { remember?: boolean }) => void\n onDeny: (id: string, reason?: string) => void\n /** Offer \"Always allow\" (remembers the tool for the agent's life). Default true. */\n allowRemember?: boolean\n /** Render a request yourself (gets the built-in card as `fallback`). */\n renderApproval?: (approval: ApprovalView, fallback: ReactNode) => ReactNode\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * Consent cards for tool calls the agent wants to make — \"Allow once\",\n * \"Always allow\" and \"Deny\". Wire it to {@link useAgent}'s `pendingApprovals`,\n * `approve` and `deny`; `<AgentChat>` renders it for you.\n */\nexport const ToolApprovalPrompt = ({\n approvals,\n onApprove,\n onDeny,\n allowRemember = true,\n renderApproval,\n labels,\n className,\n}: ToolApprovalPromptProps) => {\n const L = useLabels(labels)\n if (approvals.length === 0) return null\n return (\n <div className={['awr-approvals', className].filter(Boolean).join(' ')} role=\"alert\">\n {approvals.map((a) => {\n const card = (\n <div key={a.id} className=\"awr-approval\">\n <div className=\"awr-approval__head\">\n <ShieldIcon size={14} className=\"awr-approval__icon\" />\n <span>\n {L.approvalLead} <code className=\"awr-tool__name\">{a.name}</code>\n {a.readOnly ? ` (${L.readOnlyTool})` : ''}\n </span>\n </div>\n {previewValue(a.input, 300) && (\n <pre className=\"awr-approval__input\">{previewValue(a.input, 300)}</pre>\n )}\n <div className=\"awr-approval__actions\">\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--primary\"\n onClick={() => onApprove(a.id)}\n >\n {L.approve}\n </button>\n {allowRemember && (\n <button\n type=\"button\"\n className=\"awr-btn\"\n onClick={() => onApprove(a.id, { remember: true })}\n >\n {L.alwaysAllow}\n </button>\n )}\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--danger\"\n onClick={() => onDeny(a.id, L.declinedReason)}\n >\n {L.deny}\n </button>\n </div>\n </div>\n )\n return renderApproval ? <div key={a.id}>{renderApproval(a, card)}</div> : card\n })}\n </div>\n )\n}\n","import type { IUsage } from '@dudko.dev/agent-web'\nimport { formatTokens } from './format.js'\n\nexport interface UsageBadgeProps {\n usage: IUsage\n /** Only in ↑ out ↓ (the rest stays in the tooltip) — for tight headers. */\n compact?: boolean\n className?: string\n}\n\n/**\n * A compact token-usage readout: in ↑ out ↓, plus thinking (🧠) and cache-hit\n * tokens when the provider reported any. The full breakdown is on hover.\n */\nexport const UsageBadge = ({ usage, compact = false, className }: UsageBadgeProps) => {\n if (usage.totalTokens === 0) return null\n const reasoning = usage.reasoningTokens ?? 0\n const cached = usage.cachedInputTokens ?? 0\n const title = [\n `${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`,\n reasoning ? `${reasoning} thinking` : '',\n cached ? `${cached} input tokens from the prompt cache` : '',\n ]\n .filter(Boolean)\n .join(' · ')\n return (\n <span className={['awr-usage', className].filter(Boolean).join(' ')} title={title}>\n {formatTokens(usage.inputTokens)}↑ {formatTokens(usage.outputTokens)}↓\n {!compact && reasoning > 0 && ` · ${formatTokens(reasoning)} think`}\n {!compact && cached > 0 && ` · ${formatTokens(cached)} cached`}\n </span>\n )\n}\n","import type { ReactNode } from 'react'\nimport { useOptionalAgentContext } from '../context.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { LessonView } from '../types.js'\nimport { BookIcon, XIcon } from './icons.js'\n\nexport interface LearnedSkillsProps {\n /**\n * An explicit controller from {@link useAgent}. If omitted, the component reads the shared\n * controller from an enclosing `<AgentProvider>`. Or pass `lessons` yourself.\n */\n controller?: UseAgentReturn\n /** The lessons to show (default: the controller's `learned`). */\n lessons?: LessonView[]\n /**\n * Delete a lesson (default: the controller's `forgetSkill`). `false` hides the button -\n * a read-only view of what the agent wrote.\n */\n onForget?: ((name: string) => void | Promise<unknown>) | false\n /** Show what each lesson came from - the sources it named, the pages it read (default true). */\n showSources?: boolean\n /** Shown when there are no lessons (default: a short sentence from the labels). */\n empty?: ReactNode\n /** Hide the title row (default false). */\n hideTitle?: boolean\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * The agent's notebook: the lessons it wrote down itself (`config.learning`), each with when it\n * applies, how many times it was rewritten and where it came from - and a button to forget one.\n * Updates live as the agent learns.\n */\nexport const LearnedSkills = ({\n controller,\n lessons,\n onForget,\n showSources = true,\n empty,\n hideTitle = false,\n labels,\n className,\n}: LearnedSkillsProps) => {\n const L = useLabels(labels)\n const ctx = useOptionalAgentContext()\n const c = controller ?? ctx\n const list = lessons ?? c?.learned ?? []\n const forget = onForget === false ? undefined : (onForget ?? c?.forgetSkill)\n return (\n <section className={['awr-notebook', className].filter(Boolean).join(' ')}>\n {!hideTitle && (\n <h3 className=\"awr-notebook__title\">\n <BookIcon size={14} /> {L.notebookTitle}\n {list.length > 0 && <span className=\"awr-notebook__count\">{list.length}</span>}\n </h3>\n )}\n {list.length === 0 ? (\n <p className=\"awr-notebook__empty\">{empty ?? L.notebookEmpty}</p>\n ) : (\n <ul className=\"awr-notebook__list\">\n {list.map((l) => (\n <li key={l.name} className=\"awr-lesson\">\n <div className=\"awr-lesson__head\">\n <code className=\"awr-lesson__name\">{l.name}</code>\n {l.revision > 1 && (\n <span className=\"awr-lesson__rev\">{L.notebookRevision(l.revision)}</span>\n )}\n {forget && (\n <button\n type=\"button\"\n className=\"awr-lesson__forget\"\n title={`${L.notebookForget}: ${l.name}`}\n aria-label={`${L.notebookForget}: ${l.name}`}\n onClick={() => void forget(l.name)}\n >\n <XIcon size={12} />\n </button>\n )}\n </div>\n <p className=\"awr-lesson__when\">{l.description}</p>\n {showSources && l.sources.length > 0 && (\n <p className=\"awr-lesson__from\">\n {L.notebookFrom} {l.sources.join(', ')}\n </p>\n )}\n </li>\n ))}\n </ul>\n )}\n </section>\n )\n}\n","import { useState } from 'react'\nimport type { KeyboardEvent } from 'react'\nimport { SendIcon, SpinnerIcon, StopIcon } from './icons.js'\n\nexport interface ComposerProps {\n /** Called with the trimmed text when the user submits. */\n onSubmit: (text: string) => void\n /** A run is in flight — show a stop button instead of send. */\n busy?: boolean\n /** Called when the stop button is pressed (only shown while `busy`). */\n onStop?: () => void\n /** Disable input (e.g. while the agent is still initializing). */\n disabled?: boolean\n placeholder?: string\n className?: string\n}\n\n/** A textarea + send/stop button. Enter submits; Shift+Enter inserts a newline. */\nexport const Composer = ({\n onSubmit,\n busy = false,\n onStop,\n disabled = false,\n placeholder = 'Ask the agent to do something…',\n className,\n}: ComposerProps) => {\n const [text, setText] = useState('')\n\n const submit = () => {\n const value = text.trim()\n if (!value || busy || disabled) return\n setText('')\n onSubmit(value)\n }\n\n const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault()\n submit()\n }\n }\n\n return (\n <form\n className={['awr-composer', className].filter(Boolean).join(' ')}\n onSubmit={(e) => {\n e.preventDefault()\n submit()\n }}\n >\n <textarea\n className=\"awr-composer__input\"\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={onKeyDown}\n placeholder={placeholder}\n disabled={disabled}\n rows={1}\n />\n {busy ? (\n <button\n type=\"button\"\n className=\"awr-composer__btn awr-composer__btn--stop\"\n onClick={onStop}\n aria-label=\"Stop\"\n >\n <StopIcon size={18} />\n </button>\n ) : (\n <button\n type=\"submit\"\n className=\"awr-composer__btn\"\n disabled={disabled || !text.trim()}\n aria-label=\"Send\"\n >\n {disabled ? <SpinnerIcon size={18} /> : <SendIcon size={18} />}\n </button>\n )}\n </form>\n )\n}\n","import type { IPlan } from '@dudko.dev/agent-web'\n\nexport interface PlanViewProps {\n plan: IPlan\n /** Also render the planner's reasoning (\"thought\"). Default true. */\n showThought?: boolean\n className?: string\n}\n\n/** The plan the agent produced: its reasoning and the ordered step list. */\nexport const PlanView = ({ plan, showThought = true, className }: PlanViewProps) => {\n if (!plan.steps.length && !plan.thought) return null\n return (\n <div className={['awr-plan', className].filter(Boolean).join(' ')}>\n {showThought && plan.thought.trim() && <p className=\"awr-plan__thought\">{plan.thought}</p>}\n {plan.steps.length > 0 && (\n <ol className=\"awr-plan__steps\">\n {plan.steps.map((step) => (\n <li key={step.id} className=\"awr-plan__step\">\n {step.description}\n </li>\n ))}\n </ol>\n )}\n </div>\n )\n}\n","import type { ToolApprovalMode } from '@dudko.dev/agent-web'\n\nexport interface ApprovalModeSwitchProps {\n mode: ToolApprovalMode\n onChange: (mode: ToolApprovalMode) => void\n /** Which modes to offer, in order (default: all four). */\n modes?: ToolApprovalMode[]\n /** Override the button labels. */\n labels?: Partial<Record<ToolApprovalMode, string>>\n disabled?: boolean\n className?: string\n}\n\nconst DEFAULT_LABELS: Record<ToolApprovalMode, string> = {\n autopilot: 'Autopilot',\n 'ask-writes': 'Ask before changes',\n 'ask-all': 'Ask always',\n 'read-only': 'Read-only',\n}\n\nconst HINTS: Record<ToolApprovalMode, string> = {\n autopilot: 'Run every tool without asking',\n 'ask-writes': 'Run read-only tools freely; ask before anything that may change state',\n 'ask-all': 'Ask before every tool call',\n 'read-only': 'Run read-only tools; refuse everything else without asking',\n}\n\n/**\n * A segmented control for the tool-consent policy — the \"autopilot\" switch.\n * Pair it with {@link useAgent}'s `approvalMode` / `setApprovalMode`.\n */\nexport const ApprovalModeSwitch = ({\n mode,\n onChange,\n modes = ['autopilot', 'ask-writes', 'ask-all', 'read-only'],\n labels,\n disabled,\n className,\n}: ApprovalModeSwitchProps) => (\n <div\n className={['awr-modeswitch', className].filter(Boolean).join(' ')}\n role=\"radiogroup\"\n aria-label=\"Tool consent\"\n >\n {modes.map((m) => (\n <button\n key={m}\n type=\"button\"\n role=\"radio\"\n aria-checked={mode === m}\n title={HINTS[m]}\n className={`awr-modeswitch__opt${mode === m ? ' is-active' : ''}`}\n onClick={() => onChange(m)}\n disabled={disabled}\n >\n {labels?.[m] ?? DEFAULT_LABELS[m]}\n </button>\n ))}\n </div>\n)\n","import { useEffect, useState } from 'react'\nimport type { UseCredentialsReturn } from '../hooks/use-credentials.js'\nimport { CheckIcon } from './icons.js'\n\nexport interface ApiKeyFormProps {\n /** The value returned by {@link useCredentials}. */\n credentials: UseCredentialsReturn\n /** The ref id under which the key is stored (matches your `credentialRef`). */\n credentialRef: string\n label?: string\n placeholder?: string\n /** Called after a key is saved or removed (e.g. to `reload()` the agent). */\n onChange?: (present: boolean) => void\n className?: string\n}\n\n/**\n * A BYOK key input that stores the key **encrypted at rest** via\n * {@link useCredentials}. Shows a \"saved\" state when a key already exists and\n * lets the user replace or remove it. The plaintext key never leaves the form.\n */\nexport const ApiKeyForm = ({\n credentials,\n credentialRef,\n label = 'API key',\n placeholder = 'sk-…',\n onChange,\n className,\n}: ApiKeyFormProps) => {\n const [value, setValue] = useState('')\n const [present, setPresent] = useState(false)\n const [busy, setBusy] = useState(false)\n\n useEffect(() => {\n let active = true\n credentials.hasKey(credentialRef).then((has) => {\n if (active) setPresent(has)\n })\n return () => {\n active = false\n }\n }, [credentials, credentialRef, credentials.version])\n\n const save = async () => {\n const key = value.trim()\n if (!key) return\n setBusy(true)\n try {\n await credentials.setKey(credentialRef, key)\n setValue('')\n setPresent(true)\n onChange?.(true)\n } finally {\n setBusy(false)\n }\n }\n\n const remove = async () => {\n setBusy(true)\n try {\n await credentials.removeKey(credentialRef)\n setPresent(false)\n onChange?.(false)\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <div className={['awr-keyform', className].filter(Boolean).join(' ')}>\n <label className=\"awr-keyform__label\">\n {label}\n {present && (\n <span className=\"awr-keyform__saved\">\n <CheckIcon size={12} /> stored, encrypted\n </span>\n )}\n </label>\n <div className=\"awr-keyform__row\">\n <input\n className=\"awr-keyform__input\"\n type=\"password\"\n autoComplete=\"off\"\n value={value}\n placeholder={present ? '•••••••• (replace)' : placeholder}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n void save()\n }\n }}\n disabled={busy}\n />\n <button\n type=\"button\"\n className=\"awr-keyform__btn\"\n onClick={() => void save()}\n disabled={busy || !value.trim()}\n >\n Save\n </button>\n {present && (\n <button\n type=\"button\"\n className=\"awr-keyform__btn awr-keyform__btn--ghost\"\n onClick={() => void remove()}\n disabled={busy}\n >\n Remove\n </button>\n )}\n </div>\n </div>\n )\n}\n","// ── Hooks ────────────────────────────────────────────────────────────────────\nexport { useAgent } from './hooks/use-agent.js'\nexport type {\n ApproveOptions,\n RunGoalOptions,\n UseAgentOptions,\n UseAgentReturn,\n} from './hooks/use-agent.js'\nexport { useChatHistory } from './hooks/use-chat-history.js'\nexport type { UseChatHistoryOptions, UseChatHistoryReturn } from './hooks/use-chat-history.js'\nexport { useVirtualFiles } from './hooks/use-virtual-files.js'\nexport type { UseVirtualFilesReturn } from './hooks/use-virtual-files.js'\nexport { useSpeechToText } from './hooks/use-speech-to-text.js'\nexport type {\n UseSpeechToTextOptions,\n UseSpeechToTextReturn,\n SpeechRecognizerLike,\n} from './hooks/use-speech-to-text.js'\nexport { useCredentials } from './hooks/use-credentials.js'\nexport type { UseCredentialsReturn } from './hooks/use-credentials.js'\nexport { createWebLLMEngine, useWebLLMModel } from './hooks/use-webllm-model.js'\nexport { useLocalModel } from './hooks/use-local-model.js'\nexport type {\n LocalModelEngine,\n LocalModelLoadContext,\n LocalModelProgress,\n UseLocalModelOptions,\n UseLocalModelReturn,\n} from './hooks/use-local-model.js'\nexport type {\n UseWebLLMModelReturn,\n UseWebLLMModelOptions,\n WebLLMModelFactory,\n} from './hooks/use-webllm-model.js'\n\n// ── Chat history, labels (i18n), composer helpers, images ────────────────────\nexport { ChatHistoryStore, chatTitle, newChatId } from './chat-history.js'\nexport type { ChatRecord, ChatSummary, ChatHistoryStoreOptions } from './chat-history.js'\nexport { AgentLabelsProvider, defaultLabels, mergeLabels, useLabels } from './labels.js'\nexport type { AgentLabels, AgentLabelsOverride, AgentLabelsProviderProps } from './labels.js'\nexport {\n parseSlash,\n filterCommands,\n attachmentKindOf,\n withAttachments,\n attachmentRefusal,\n formatElapsed,\n noticesOf,\n steerIntent,\n} from './composer.js'\nexport type {\n SlashCommand,\n ComposerAttachment,\n ComposerNotice,\n NoticeTexts,\n SteerIntent,\n} from './composer.js'\nexport { downscaleImage } from './image-resize.js'\nexport type { DownscaleOptions } from './image-resize.js'\n\n// ── Context ──────────────────────────────────────────────────────────────────\nexport { AgentProvider, useAgentContext, useOptionalAgentContext } from './context.js'\nexport type { AgentProviderProps } from './context.js'\n\n// ── Headless state (the pure event → UI reducer, for custom UIs) ─────────────\nexport { agentStateReducer, createInitialAgentState, lessonsOf } from './state.js'\nexport type { AgentAction } from './state.js'\nexport type {\n AgentUiState,\n AgentStatus,\n QueuedMessageView,\n UserNoteView,\n ApprovalView,\n BudgetView,\n ChatAttachment,\n ChatMessage,\n CompactionView,\n FetchView,\n LessonView,\n StepView,\n SubagentView,\n ToolCallView,\n ModelLoadState,\n ReplanState,\n} from './types.js'\n\n// ── Components (optional, pre-styled — import '@dudko.dev/agent-web-react/styles.css') ─\nexport { AgentChat } from './components/AgentChat.js'\nexport type {\n AgentChatProps,\n AgentChatSlots,\n AgentChatComponents,\n AgentChatClassNames,\n} from './components/AgentChat.js'\nexport { AgentComposer } from './components/AgentComposer.js'\nexport type {\n AgentComposerProps,\n ComposerModelChip,\n ComposerThinkingChip,\n ConvertedFile,\n} from './components/AgentComposer.js'\nexport { MessageList, AttachmentView, usageLine } from './components/MessageList.js'\nexport type { MessageListProps } from './components/MessageList.js'\nexport { ChatHistoryList } from './components/ChatHistoryList.js'\nexport type { ChatHistoryListProps } from './components/ChatHistoryList.js'\nexport { LearnedSkills } from './components/LearnedSkills.js'\nexport type { LearnedSkillsProps } from './components/LearnedSkills.js'\nexport { FilesPanel } from './components/FilesPanel.js'\nexport type { FilesPanelProps } from './components/FilesPanel.js'\nexport { Composer } from './components/Composer.js'\nexport type { ComposerProps } from './components/Composer.js'\nexport { PlanView } from './components/PlanView.js'\nexport type { PlanViewProps } from './components/PlanView.js'\nexport { StepList, SubagentRow, ToolCallRow, UserNoteRow } from './components/StepList.js'\nexport type { StepListProps, ToolCallRowProps, RenderToolCall } from './components/StepList.js'\nexport { ToolApprovalPrompt } from './components/ToolApprovalPrompt.js'\nexport type { ToolApprovalPromptProps } from './components/ToolApprovalPrompt.js'\nexport { ApprovalModeSwitch } from './components/ApprovalModeSwitch.js'\nexport type { ApprovalModeSwitchProps } from './components/ApprovalModeSwitch.js'\nexport { ContextMeter } from './components/ContextMeter.js'\nexport type { ContextMeterProps } from './components/ContextMeter.js'\nexport { ModelLoadBar } from './components/ModelLoadBar.js'\nexport type { ModelLoadBarProps } from './components/ModelLoadBar.js'\nexport { UsageBadge } from './components/UsageBadge.js'\nexport type { UsageBadgeProps } from './components/UsageBadge.js'\nexport { ApiKeyForm } from './components/ApiKeyForm.js'\nexport type { ApiKeyFormProps } from './components/ApiKeyForm.js'\n\n// ── Convenience re-exports from the core (a peer dep), so a React app can\n// import the agent primitives it needs from one place. ──────────────────────\nexport {\n createAgent,\n defineTool,\n defineSkill,\n parseSkillMarkdown,\n loadSkillFromUrl,\n createRunControl,\n createSubagentTool,\n serveSubagentWorker,\n markReadOnly,\n createWebLLMModel,\n preloadWebLLMModel,\n unloadWebLLMModel,\n isWebGPUAvailable,\n VaultCredentialStore,\n MemoryCredentialStore,\n MemoryStore,\n IndexedDBStore,\n VirtualFileSystem,\n createFileTools,\n MemorySkillStore,\n VfsSkillStore,\n AttachmentsNotSupportedError,\n ImagesNotSupportedError,\n supportsImages,\n supportsPdf,\n} from '@dudko.dev/agent-web'\nexport type {\n Agent,\n RunControl,\n RunOptions,\n RunResult,\n SubagentInfo,\n BrowserAgentConfig,\n AgentEvent,\n AgentEventHandler,\n AgentTool,\n AgentToolSet,\n CredentialStore,\n ProviderModelSpec,\n ProviderType,\n ModelInput,\n LogLevel,\n AgentLoggerSink,\n IPlan,\n IPlanStep,\n IStepResult,\n IToolCall,\n IUsage,\n Skill,\n SkillStore,\n LearningConfig,\n ThinkingSetting,\n ThinkingLevel,\n TokenLimits,\n CompactionConfig,\n CompactResult,\n ToolApprovalConfig,\n ToolApprovalMode,\n ToolApprovalRequest,\n SubagentToolOptions,\n SubagentWorkerConfig,\n RunFile,\n VirtualFile,\n VirtualFileInfo,\n FileToolsOptions,\n} from '@dudko.dev/agent-web'\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,YAAY,QAAQ,gBAAgB;AAErE;AAAA,EACE;AAAA,EACA;AAAA,OAYK;;;ACwCP,IAAM,eAAe,CAAC,UAA2B;AAC/C,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI;AACJ,MAAI;AACF,WAAO,OAAO,UAAU,WAAW,QAAS,KAAK,UAAU,KAAK,KAAK;AAAA,EACvE,QAAQ;AACN,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC;AAEA,IAAM,aAAa,OAAe;AAAA,EAChC,aAAa;AAAA,EACb,cAAc;AAAA,EACd,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,kBAAkB;AACpB;AAEA,IAAM,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;AAAA,EACE,eAAAI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,sBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["base","m","req","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect","useCallback","useEffect","useState","useCallback","useEffect","useRef","useState","useCallback","useMemo","useState","useCallback","useRef","useState","useState","useRef","model","useCallback","useMemo","base","useMemo","createContext","useContext","jsx","createContext","useContext","useEffect","useRef","useState","useEffect","useMemo","useRef","useState","jsx","jsx","jsx","jsxs","useEffect","useState","readDataUrl","useRef","useMemo","Fragment","jsx","jsxs","Fragment","jsx","jsxs","Fragment","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useEffect","Fragment","jsx","jsxs","Fragment","jsx","jsxs","jsx","jsxs","jsx","jsxs","jsxs","Fragment","jsx","jsxs","useState","useRef","useEffect","Composer","jsx","jsxs","useState","jsx","jsxs","useState","jsx","jsxs","jsx","useEffect","useState","jsx","jsxs","useState","useEffect","createAgent","createRunControl","createWebLLMModel","preloadWebLLMModel","unloadWebLLMModel","isWebGPUAvailable","VaultCredentialStore"]}