@dudko.dev/agent-web-react 0.0.29 → 0.0.31

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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/Media.tsx","../src/components/StepList.tsx","../src/components/SubagentTree.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"],"sourcesContent":["// ── 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, subagentTree } 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 DecisionView,\n FetchView,\n LessonView,\n MediaView,\n StepEscalationView,\n StepView,\n SubagentNode,\n SubagentView,\n ToolCallView,\n TranscriptView,\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, ToolCallRow, UserNoteRow, decisionNote } from './components/StepList.js'\nexport type { StepListProps, ToolCallRowProps, RenderToolCall } from './components/StepList.js'\nexport { SubagentRow, SubagentTree } from './components/SubagentTree.js'\nexport type {\n RenderSubagent,\n SubagentRowProps,\n SubagentTreeProps,\n} from './components/SubagentTree.js'\nexport { GeneratedMedia, TranscriptBlock, mediaFamilyOf } from './components/Media.js'\nexport type { GeneratedMediaProps, TranscriptBlockProps } from './components/Media.js'\nexport { webSearchOf } from './components/format.js'\nexport type { WebSearchResultView, WebSearchView } from './components/format.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","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 {\n isReplayedToolOutput,\n type AgentEvent,\n type IUsage,\n type Skill,\n} from '@dudko.dev/agent-web'\nimport type {\n AgentUiState,\n ApprovalView,\n ChatAttachment,\n ChatMessage,\n DecisionView,\n LessonView,\n MediaView,\n StepView,\n SubagentNode,\n SubagentView,\n ToolCallView,\n TranscriptView,\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\n// What a usage record counts besides tokens: calls to the media models and to the decision\n// model. Absent until there is one, so a run without them keeps the six-field shape.\nconst USAGE_COUNTS = [\n 'mediaCalls',\n 'imagesGenerated',\n 'speechCharacters',\n 'transcriptionSeconds',\n 'decisionCalls',\n] as const\n\nconst addUsage = (a: IUsage, b: IUsage): IUsage => {\n const sum: IUsage = {\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),\n cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),\n cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0),\n }\n for (const key of USAGE_COUNTS) {\n const n = (a[key] ?? 0) + (b[key] ?? 0)\n if (n) sum[key] = n\n }\n return sum\n}\n\n/**\n * The notebook view of the agent's own skills (`agent.listLearnedSkills()`): what the core stored\n * about each lesson, in the shape the UI keeps current from `skill.learned` events.\n */\nexport const lessonsOf = (skills: Skill[]): LessonView[] =>\n skills\n .filter((s) => s.origin?.kind === 'learned')\n .map((s) => ({\n name: s.name,\n description: s.description,\n revision: s.origin?.revision ?? 1,\n chars: s.content.length,\n sources: [...(s.origin?.sources ?? []), ...(s.origin?.fetched ?? [])],\n }))\n\n/** A fresh, empty view. */\nexport const createInitialAgentState = (): AgentUiState => ({\n status: 'idle',\n goal: undefined,\n plan: undefined,\n planThought: '',\n steps: [],\n finalText: '',\n finalReasoning: '',\n totalUsage: emptyUsage(),\n runStartedAt: undefined,\n runMessageId: undefined,\n approvals: [],\n subagents: [],\n queued: [],\n notes: [],\n undelivered: [],\n skills: [],\n learned: [],\n learnedNow: [],\n fetches: [],\n discoveredTools: [],\n compactions: [],\n budget: undefined,\n usage: emptyUsage(),\n modelLoad: undefined,\n replan: undefined,\n error: undefined,\n stopped: false,\n messages: [],\n events: [],\n seq: 0,\n})\n\n/** Clear only the per-run view; keep the transcript, totals, status and seq counter. */\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 // Known only when the child runs with model tiers.\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n }\n case 'step.escalated':\n return { ...view, tier: event.to, ...(event.model ? { model: event.model } : {}) }\n case 'step.tool-call':\n return { ...view, toolCalls: view.toolCalls + 1, activity: `→ ${event.name}` }\n case 'final.text-delta':\n return { ...view, text: view.text + event.delta, activity: 'writing the answer' }\n case 'final':\n return { ...view, text: event.text }\n case 'usage':\n return { ...view, usage: addUsage(view.usage, event.usage) }\n default:\n return view\n }\n}\n\n/** A subagent an event came through on its way up (a `subagent.event` envelope). */\ninterface Ancestor {\n id: string\n}\n\ntype SubagentStart = Extract<AgentEvent, { type: 'subagent.start' }>\n\n/**\n * The node `id`, created when it is not there yet. An event can arrive for a subagent whose\n * `subagent.start` was never seen (a capped log replayed, a host that joined late): it gets a\n * node from what the envelope says - its name, and where in the tree it is.\n */\nconst ensureSubagent = (\n state: AgentUiState,\n id: string,\n name: string,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n if (state.subagents.some((s) => s.id === id)) return state\n const parentId = ancestors[ancestors.length - 1]?.id\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id,\n name,\n task: '',\n ...(parentId ? { parentId } : {}),\n depth: ancestors.length + 1,\n status: 'running',\n ...(stepId ? { stepId } : {}),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** What a `subagent.start` says about its node (everything but the counters). */\nconst startSubagent = (\n state: AgentUiState,\n event: SubagentStart,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n // The envelopes around an event are its ancestry; a start that came bare says it itself\n // (`parentId` is then a subagent only below depth 1 - at depth 1 it is the run's id).\n const depth = Math.max(event.depth ?? 1, ancestors.length + 1)\n const parentId = ancestors[ancestors.length - 1]?.id ?? (depth > 1 ? event.parentId : undefined)\n const told = {\n name: event.name,\n task: event.task,\n depth,\n ...(parentId ? { parentId } : {}),\n ...(event.profile ? { profile: event.profile } : {}),\n ...(event.dynamic ? { dynamic: true as const } : {}),\n ...(event.role ? { role: event.role } : {}),\n ...(event.tools ? { tools: event.tools } : {}),\n }\n // Already there (its events arrived first): the start fills in what they could not say.\n if (state.subagents.some((s) => s.id === event.id)) {\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({ ...s, ...told })),\n }\n }\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n // A nested one belongs to the step that delegated its top-most ancestor.\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id: event.id,\n ...told,\n status: 'running',\n stepId,\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** How long a subagent ran, when both ends were stamped. */\nconst subagentDuration = (s: SubagentView, at?: number): Partial<SubagentView> =>\n at !== undefined && s.startedAt !== undefined ? { durationMs: Math.max(0, at - s.startedAt) } : {}\n\nconst addMedia = (state: AgentUiState, view: MediaView): AgentUiState => ({\n ...state,\n media: [...(state.media ?? []), view],\n ...(view.stepId\n ? {\n steps: patchStep(state.steps, view.stepId, (s) => ({\n ...s,\n media: [...(s.media ?? []), view],\n })),\n }\n : {}),\n})\n\nconst mediaOf = (\n event: Extract<AgentEvent, { type: 'media.generated' }>,\n withStep: boolean,\n): MediaView => ({\n kind: event.kind,\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n model: event.model,\n ...(withStep && event.step ? { stepId: event.step.id } : {}),\n})\n\nconst transcriptOf = (\n event: Extract<AgentEvent, { type: 'media.transcribed' }>,\n): TranscriptView => ({\n source: event.source,\n name: event.name,\n text: event.text,\n ...(event.language ? { language: event.language } : {}),\n ...(event.durationInSeconds !== undefined ? { durationInSeconds: event.durationInSeconds } : {}),\n model: event.model,\n})\n\n/**\n * Fold a `subagent.*` event into the tree. `ancestors` are the subagents it came up through\n * (outermost first): a subagent's own subagents arrive nested,\n * `subagent.event{ A, subagent.event{ G, event } }`, and each level lands on its own node.\n */\nconst applySubagent = (\n state: AgentUiState,\n event: Extract<\n AgentEvent,\n { type: 'subagent.start' | 'subagent.event' | 'subagent.complete' | 'subagent.error' }\n >,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n switch (event.type) {\n case 'subagent.start':\n return startSubagent(state, event, ancestors, ctx)\n\n case 'subagent.event': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n const inner = event.event\n switch (inner.type) {\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(known, inner, [...ancestors, { id: event.id }], ctx)\n\n // A helper the model started asks through the run's own consent gate (the event says\n // which helper): its request is the user's to answer, like the run's. A subagent with\n // a gate of its own (no `subagent` on the event) is its host's business.\n case 'tool.approval-requested': {\n if (!inner.subagent || known.approvals.some((a) => a.id === inner.id)) return known\n const node = known.subagents.find((s) => s.id === inner.subagent!.id)\n return {\n ...known,\n approvals: [\n ...known.approvals,\n {\n id: inner.id,\n name: inner.name,\n input: inner.input,\n readOnly: inner.readOnly,\n // The helper's own step ids mean nothing here: the step that delegated it does.\n stepId: node?.stepId,\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n status: 'pending',\n },\n ],\n }\n }\n case 'tool.approval-resolved':\n return known.approvals.some((a) => a.id === inner.id)\n ? {\n ...known,\n approvals: patchApproval(known.approvals, inner.id, (a) => ({\n ...a,\n status: inner.approved ? 'approved' : 'denied',\n reason: inner.reason,\n automatic: inner.automatic,\n })),\n }\n : known\n\n // What a subagent generated is in the same workspace: it shows in the turn (its step\n // ids are its own, so it is tied to no step here).\n case 'media.generated':\n return addMedia(known, mediaOf(inner, false))\n case 'media.transcribed':\n return { ...known, transcripts: [...(known.transcripts ?? []), transcriptOf(inner)] }\n\n default:\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) =>\n applySubagentEvent(s, inner),\n ),\n }\n }\n }\n\n case 'subagent.complete': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: 'done',\n activity: 'done',\n text: event.text,\n usage: event.usage,\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n\n case 'subagent.error': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: event.stopped ? 'stopped' : 'error',\n activity: event.stopped ? 'stopped' : 'failed',\n error: event.error,\n // A helper says what it had spent when it ended; a static subagent does not.\n ...(event.usage ? { usage: event.usage } : {}),\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n }\n}\n\n/**\n * The flat `subagents` list as a tree: each node with the subagents it started, in the order\n * they started. A node whose parent is not in the list (its start was never seen) is a root.\n */\nexport const subagentTree = (subagents: SubagentView[]): SubagentNode[] => {\n const nodes = new Map<string, SubagentNode>()\n for (const s of subagents) nodes.set(s.id, { ...s, children: [] })\n // A parent chain that comes back to the node is not a tree: such a node is a root.\n const loops = (node: SubagentNode): boolean => {\n let up = node.parentId\n for (let i = 0; up !== undefined && i <= nodes.size; i++) {\n if (up === node.id) return true\n up = nodes.get(up)?.parentId\n }\n return false\n }\n const roots: SubagentNode[] = []\n for (const node of nodes.values()) {\n const parent =\n node.parentId !== undefined && !loops(node) ? nodes.get(node.parentId) : undefined\n if (parent) parent.children.push(node)\n else roots.push(node)\n }\n return roots\n}\n\n/** Finalize the trailing pending assistant message with the given content. */\nconst finalizeAssistant = (\n messages: ChatMessage[],\n content: string,\n extra: Partial<ChatMessage> = {},\n): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content: content || m.content, pending: false, ...extra }\n return next\n }\n }\n return messages\n}\n\n/** Duration of the current run at `at`, when both ends are known. */\nconst runDuration = (state: AgentUiState, at?: number): Partial<ChatMessage> =>\n at !== undefined && state.runStartedAt !== undefined\n ? { durationMs: Math.max(0, at - state.runStartedAt) }\n : {}\n\n/** Update the trailing pending assistant message's streaming content. */\nconst streamAssistant = (messages: ChatMessage[], content: string): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content }\n return next\n }\n }\n return messages\n}\n\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 // Only with `config.executorTiers`: without it the view is what it always was.\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tierReason !== undefined ? { tierReason: event.tierReason } : {}),\n }\n return { ...state, steps: [...state.steps, view] }\n }\n\n case 'step.escalated':\n // The attempt on `from` is over and the step CONTINUES on `to`. What the failed attempt\n // wrote is not the next attempt's text: it moves onto the escalation. Its tool calls\n // happened (the core keeps them in the step's result and shows them to the stronger\n // model), so they stay, marked with the attempt they belong to.\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n const attempt = (s.escalations?.length ?? 0) + 1\n return {\n ...s,\n tier: event.to,\n ...(event.model ? { model: event.model } : {}),\n text: '',\n reasoning: '',\n toolCalls: s.toolCalls.map((c) => (c.attempt === undefined ? { ...c, attempt } : c)),\n escalations: [\n ...(s.escalations ?? []),\n {\n from: event.from,\n to: event.to,\n reason: event.reason,\n ...(event.model ? { model: event.model } : {}),\n ...(s.text.trim() ? { text: s.text } : {}),\n },\n ],\n }\n }),\n }\n\n case 'step.reasoning-delta':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n reasoning: s.reasoning + event.delta,\n })),\n }\n\n case 'step.text-delta':\n return {\n ...state,\n 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 ...(isReplayedToolOutput(event.output) ? { replayed: true } : {}),\n ...(ctx.at !== undefined && c.startedAt !== undefined\n ? { durationMs: Math.max(0, ctx.at - c.startedAt) }\n : {}),\n }\n }\n return c\n })\n .reverse()\n return { ...s, toolCalls }\n }),\n }\n\n case 'step.complete':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n status: 'done',\n summary: event.result.summary,\n // With tiers: where the step finished and how it got there. The result's list is the\n // authority; an escalation seen live keeps what only the event told (model, text).\n ...(event.result.tier !== undefined ? { tier: event.result.tier } : {}),\n ...(event.result.model !== undefined ? { model: event.result.model } : {}),\n ...(event.result.escalations?.length\n ? {\n escalations: event.result.escalations.map((e, i) => {\n const live = s.escalations?.[i]\n return live && live.from === e.from && live.to === e.to\n ? { ...live, reason: e.reason }\n : { from: e.from, to: e.to, reason: e.reason }\n }),\n }\n : {}),\n blocked: event.result.blocked,\n // The result carries the authoritative, ordered tool-call list; keep\n // the timing the streamed calls measured (matched in order per name).\n toolCalls: (() => {\n const seen = new Map<string, number>()\n return event.result.toolCalls.map((c) => {\n const nth = seen.get(c.name) ?? 0\n seen.set(c.name, nth + 1)\n const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth]\n return {\n name: c.name,\n input: c.input,\n output: c.output,\n ok: c.ok,\n status: 'done' as const,\n inputTokens: approxTokens(c.input),\n outputTokens: approxTokens(c.output),\n ...(streamed?.startedAt !== undefined ? { startedAt: streamed.startedAt } : {}),\n ...(streamed?.durationMs !== undefined ? { durationMs: streamed.durationMs } : {}),\n // With tiers the list holds every attempt's calls, in the order they were made.\n ...(streamed?.attempt !== undefined ? { attempt: streamed.attempt } : {}),\n ...(isReplayedToolOutput(c.output) ? { replayed: true } : {}),\n }\n })\n })(),\n })),\n }\n\n case 'replan.decision': {\n if (!event.failed) {\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n },\n }\n }\n // The replanner could not decide: `continue` is the fallback and the run goes on. The\n // failure itself came as the `error` event (phase 'replan') just before; it is pinned to\n // the step the replanner ran after, so the warning stays in that turn's activity.\n const error = state.replan?.failed ? state.replan.error : undefined\n const last = state.steps[state.steps.length - 1]\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n failed: true,\n ...(error ? { error } : {}),\n },\n steps: last\n ? patchStep(state.steps, last.id, (s) => ({\n ...s,\n replanFailed: error ?? event.reason,\n }))\n : state.steps,\n }\n }\n\n case 'decision': {\n // The decision model is asked after a step (continue / finish): the note belongs to it.\n const view: DecisionView = {\n point: event.point,\n accepted: event.accepted,\n ...(event.choice !== undefined ? { choice: event.choice } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n threshold: event.threshold,\n ...(event.reason ? { reason: event.reason } : {}),\n durationMs: event.durationMs,\n ...(event.model ? { model: event.model } : {}),\n }\n const last = state.steps[state.steps.length - 1]\n return last\n ? {\n ...state,\n steps: patchStep(state.steps, last.id, (s) => ({\n ...s,\n decisions: [...(s.decisions ?? []), view],\n })),\n }\n : { ...state, decisions: [...(state.decisions ?? []), view] }\n }\n\n case 'media.generated':\n return addMedia(state, mediaOf(event, true))\n\n case 'media.transcribed':\n return { ...state, transcripts: [...(state.transcripts ?? []), transcriptOf(event)] }\n\n case '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 ...(event.subagent ? { subagent: event.subagent } : {}),\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 case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(state, event, [], ctx)\n\n case 'skill.activated':\n return state.skills.includes(event.name)\n ? state\n : { ...state, skills: [...state.skills, event.name] }\n\n case 'skill.learned': {\n const before = state.learned.find((l) => l.name === event.name)\n const lesson: LessonView = {\n name: event.name,\n description: event.description,\n // A rewrite of a lesson we know goes up one; a lesson we never saw (an event for a store\n // loaded before this view existed) starts at 2 when the core says it is an update.\n revision: event.update ? (before?.revision ?? 1) + 1 : 1,\n chars: event.chars,\n sources: event.sources,\n }\n return {\n ...state,\n learned: before\n ? state.learned.map((l) => (l.name === event.name ? lesson : l))\n : [...state.learned, lesson],\n learnedNow: state.learnedNow.includes(event.name)\n ? state.learnedNow\n : [...state.learnedNow, event.name],\n }\n }\n\n case 'skill.forgotten':\n return { ...state, learned: state.learned.filter((l) => l.name !== event.name) }\n\n case 'egress.request':\n return {\n ...state,\n fetches: [\n ...state.fetches,\n {\n url: event.url,\n allowed: event.allowed,\n ...(event.status !== undefined ? { status: event.status } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n },\n ],\n }\n\n case 'tools.discovered':\n return {\n ...state,\n discoveredTools: [...new Set([...state.discoveredTools, ...event.names])],\n }\n\n case 'context.compacted':\n return {\n ...state,\n compactions: [\n ...state.compactions,\n { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens },\n ],\n }\n\n case 'budget.exceeded':\n return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } }\n\n case '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 // A replanner that failed is not an error of the run at all: the run continues with its\n // plan. It is held for the `replan.decision { failed }` that follows, never in `error`.\n if (event.phase === 'replan') {\n return {\n ...state,\n replan: { mode: 'continue', reason: '', failed: true, error: event.error },\n }\n }\n return event.phase === 'run'\n ? {\n ...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 (state.media && m.media !== state.media) patch.media = state.media\n if (state.transcripts && m.transcripts !== state.transcripts)\n patch.transcripts = state.transcripts\n if (\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 {\n DecisionFallbackReason,\n EscalationReason,\n ModelTier,\n TierReason,\n ToolApprovalMode,\n} from '@dudko.dev/agent-web'\nimport { defaultNoticeTexts, type NoticeTexts } from './composer.js'\nimport type { 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 // ── model tiers and escalation ─────────────────────────────────────────────\n /** The tier badge on a step. */\n tierNames: Record<ModelTier, string>\n /** The badge's tooltip: why the step started on its tier. */\n tierReasons: Record<TierReason, string>\n /** Why a step was retried on a stronger model. */\n escalationReasons: Record<EscalationReason, string>\n /** \"Escalated: light → strong (reported a blocker)\" - the names and the reason are already labels. */\n escalated: (from: string, to: string, reason: string) => string\n /** Opens what the failed attempt had written. */\n escalatedAttemptText: string\n /** \"1 escalation\" in the activity summary. */\n escalations: (n: number) => string\n /** On a tool call made by an attempt that was escalated. */\n attemptTag: (n: number) => string\n /** On a write the core did not run a second time (it succeeded in an earlier attempt). */\n replayed: string\n replayedTitle: string\n /** The replanner call failed; the run went on with the plan it had. */\n replanFailed: string\n\n // ── the subagent tree ──────────────────────────────────────────────────────\n /** The tag on a helper the model started itself (`spawn_subagent`). */\n subagentHelper: string\n /** A node's status, in words. */\n subagentStatus: Record<'running' | 'done' | 'error' | 'stopped', string>\n /** \"12k tokens\" - what was spent under a node; the number is already formatted. */\n subagentTokens: (tokens: string) => string\n /** \"tools: fs_read, web_fetch\" - what a helper was given. */\n subagentTools: (names: string) => string\n /** A helper that was given no tools at all (it only reasons). */\n subagentNoTools: string\n /** The consent prompt of a helper's call: `role` is what the model wrote for it, if anything. */\n approvalLeadHelper: (role: string | undefined, depth: number) => string\n\n // ── generated media and transcripts ────────────────────────────────────────\n /** Alt text of a generated image; `path` is where it is in the workspace. */\n mediaImage: (path: string) => string\n /** The accessible name of a generated audio player. */\n mediaAudio: (path: string) => string\n /** A generated file that cannot be shown here (no workspace, the file is gone, an unknown type). */\n mediaFile: (path: string) => string\n /** The summary of a transcript block. */\n transcriptOf: (name: string) => string\n /** Says whose words a transcript is: the content of the user's file, not the agent's. */\n transcriptNote: string\n\n // ── usage: calls that are not tokens ───────────────────────────────────────\n usageMedia: (n: number) => string\n usageDecisions: (n: number) => string\n\n // ── decision model ─────────────────────────────────────────────────────────\n /** \"decision model: continue (0.93)\" - its answer was used; the probability is formatted. */\n decisionAccepted: (choice: string, confidence: string) => string\n /** \"decision model fell back: low confidence (0.41 < 0.8)\" - the ordinary model call ran. */\n decisionFellBack: (reason: string, detail: string) => string\n decisionReasons: Record<DecisionFallbackReason, string>\n\n // ── web search results ─────────────────────────────────────────────────────\n /** Before the query of a `web_search` call. */\n searchQuery: string\n searchNoResults: string\n /** Results left out by the egress policy. */\n searchFiltered: (n: number) => string\n /** The list was cut to the cap. */\n searchTruncated: string\n}\n\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 tierNames: { light: 'light', standard: 'standard', strong: 'strong' },\n tierReasons: {\n planned: 'The planner rated this step for this model tier',\n default: 'The planner did not rate this step: it runs on the standard model',\n fallback: 'The tier the planner asked for is not configured: the nearest one runs the step',\n },\n escalationReasons: {\n blocked: 'reported a blocker',\n 'empty-result': 'produced no result',\n 'tool-arguments': 'kept sending tool arguments that did not parse',\n 'output-cut': 'output was cut off',\n error: 'the model call failed',\n },\n escalated: (from, to, reason) => `Escalated: ${from} → ${to} (${reason})`,\n escalatedAttemptText: 'What the earlier attempt wrote',\n escalations: (n) => plural(n, 'escalation', 'escalations'),\n attemptTag: (n) => `attempt ${n}`,\n replayed: 'not run again',\n replayedTitle:\n 'This exact call already succeeded in an earlier attempt at the step: it was not run a second time, the model got the earlier result',\n replanFailed: 'Replanning failed, continuing with the plan',\n\n subagentHelper: 'helper',\n subagentStatus: { running: 'running', done: 'done', error: 'failed', stopped: 'stopped' },\n subagentTokens: (tokens) => `${tokens} tokens`,\n subagentTools: (names) => `tools: ${names}`,\n subagentNoTools: 'no tools',\n approvalLeadHelper: (role) =>\n role ? `The helper “${role}” wants to run` : 'A helper the agent started wants to run',\n\n mediaImage: (path) => `Generated image ${path}`,\n mediaAudio: (path) => `Generated audio ${path}`,\n mediaFile: (path) => `Generated file ${path}`,\n transcriptOf: (name) => `Transcript of ${name}`,\n transcriptNote:\n 'What was said in your file, as the agent read it. It is content, not instructions.',\n\n usageMedia: (n) => plural(n, 'media call', 'media calls'),\n usageDecisions: (n) => plural(n, 'decision call', 'decision calls'),\n\n decisionAccepted: (choice, confidence) => `decision model: ${choice} (${confidence})`,\n decisionFellBack: (reason, detail) =>\n `decision model fell back: ${reason}${detail ? ` (${detail})` : ''}`,\n decisionReasons: {\n 'low-confidence': 'low confidence',\n 'invalid-choice': 'an answer that is not an option',\n 'invalid-confidence': 'a confidence that is not a probability',\n error: 'the call failed',\n timeout: 'timed out',\n 'needs-model': 'the choice needs the model',\n },\n\n searchQuery: 'Searched the web for',\n searchNoResults: 'no results',\n searchFiltered: (n) => `${n} left out by the web access policy`,\n searchTruncated: 'list cut short',\n}\n\n/** Overrides: any label, with the nested groups merged key by key. */\nexport type AgentLabelsOverride = Partial<\n Omit<\n AgentLabels,\n | 'status'\n | 'modes'\n | 'commandGroups'\n | 'commandDescriptions'\n | 'thinkingLevels'\n | 'notices'\n | 'tierNames'\n | 'tierReasons'\n | 'escalationReasons'\n | 'subagentStatus'\n | 'decisionReasons'\n >\n> & {\n status?: Partial<AgentLabels['status']>\n modes?: Partial<AgentLabels['modes']>\n commandGroups?: Partial<AgentLabels['commandGroups']>\n commandDescriptions?: Partial<AgentLabels['commandDescriptions']>\n thinkingLevels?: Partial<AgentLabels['thinkingLevels']>\n notices?: Partial<AgentLabels['notices']>\n tierNames?: Partial<AgentLabels['tierNames']>\n tierReasons?: Partial<AgentLabels['tierReasons']>\n escalationReasons?: Partial<AgentLabels['escalationReasons']>\n subagentStatus?: Partial<AgentLabels['subagentStatus']>\n decisionReasons?: Partial<AgentLabels['decisionReasons']>\n}\n\nconst NESTED = [\n 'status',\n 'modes',\n 'commandGroups',\n 'commandDescriptions',\n 'thinkingLevels',\n 'noteAt',\n 'tierNames',\n 'tierReasons',\n 'escalationReasons',\n 'subagentStatus',\n 'decisionReasons',\n] 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 { decisionNote, type RenderToolCall } from './StepList.js'\nimport type { RenderSubagent } from './SubagentTree.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 /**\n * Model tiers (`executorTiers`): the tier / model badge on a step, the \"escalated\" line and\n * the escalation count (default true; nothing shows when tiers are off).\n */\n showTiers?: boolean\n /** The \"replanning failed, continuing with the plan\" warning (default true). */\n showReplanFailed?: boolean\n /**\n * The decision model's note under the step it was asked after - \"decision model: continue\n * (0.93)\" (default true; nothing shows without `decisionModel`).\n */\n showDecisions?: boolean\n /** A `web_search` call's results as a short list under its row (default true). */\n showSearchResults?: boolean\n /**\n * The subagent tree - static subagents and the helpers the model started - under the step\n * that started them (default true).\n */\n showSubagents?: boolean\n /**\n * What a run generated (`config.media`): images inline in the answer, audio as a player, and\n * the transcripts of audio files, folded (default true). The bytes are read from `files`.\n */\n showMedia?: 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 /** A node of the subagent tree. */\n renderSubagent?: RenderSubagent\n /** A generated image / audio file. */\n renderMedia?: MessageListProps['renderMedia']\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 showTiers = true,\n showReplanFailed = true,\n showDecisions = true,\n showSearchResults = true,\n showSubagents = true,\n showMedia = 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 renderSubagent,\n renderMedia,\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 // A replanner that failed before any step exists has no step to hang its warning on.\n const replanFailedEarly =\n showReplanFailed && agent.replan?.failed === true && agent.steps.length === 0\n // A decision made before any step exists has no step to sit under either.\n const earlyDecisions = showDecisions ? (agent.decisions ?? []) : []\n const liveExtra =\n agent.planThought.trim() || showReplan || replanFailedEarly || earlyDecisions.length > 0 ? (\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 {replanFailedEarly && (\n <p className=\"awr-step__warn\" title={agent.replan!.error}>\n <AlertIcon size={12} /> {L.replanFailed}\n </p>\n )}\n {earlyDecisions.map((d, i) => (\n <p\n key={i}\n className={`awr-step__decision${d.accepted ? '' : ' awr-step__decision--fallback'}`}\n >\n {decisionNote(d, L)}\n </p>\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 showTiers={showTiers}\n showReplanFailed={showReplanFailed}\n showDecisions={showDecisions}\n showSearchResults={showSearchResults}\n showSubagents={showSubagents}\n showMedia={showMedia}\n files={files}\n renderMedia={renderMedia}\n renderSubagent={renderSubagent}\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 ArrowUpIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 19V5\" />\n <path d=\"m5 12 7-7 7 7\" />\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\n/** One result of the core's `web_search` tool, as far as a UI shows it. */\nexport interface WebSearchResultView {\n title: string\n /** An http(s) address - anything else is left out. */\n url: string\n /** The host of `url`, for the line under the title. */\n host: string\n snippet: string\n date?: string\n}\n\nexport interface WebSearchView {\n query: string\n results: WebSearchResultView[]\n /** Results the egress policy left out. */\n filtered: number\n truncated: boolean\n}\n\nconst text = (v: unknown, max: number): string =>\n typeof v === 'string' ? v.replace(/\\s+/g, ' ').trim().slice(0, max) : ''\n\n/**\n * The result of the core's `web_search` tool (`{ query, results: [{ title, url, snippet, date? }],\n * filtered?, truncated?, untrusted: true }`), or undefined when `output` is not one. Titles and\n * snippets are third-party text: they come back as plain strings, to be rendered as text. A\n * result whose `url` is not http(s) is dropped, so a link can never be a `javascript:` one.\n */\nexport const webSearchOf = (output: unknown): WebSearchView | undefined => {\n let value = output\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const o = value as Record<string, unknown>\n if (typeof o.query !== 'string' || !Array.isArray(o.results)) return undefined\n const results: WebSearchResultView[] = []\n for (const r of o.results.slice(0, 10)) {\n if (!r || typeof r !== 'object') continue\n const item = r as Record<string, unknown>\n if (typeof item.url !== 'string') continue\n let url: URL\n try {\n url = new URL(item.url)\n } catch {\n continue\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') continue\n const date = text(item.date, 40)\n results.push({\n title: text(item.title, 200) || url.host,\n url: url.href,\n host: url.host,\n snippet: text(item.snippet, 400),\n ...(date ? { date } : {}),\n })\n }\n return {\n query: text(o.query, 300),\n results,\n filtered: typeof o.filtered === 'number' && o.filtered > 0 ? o.filtered : 0,\n truncated: o.truncated === true,\n }\n}\n\n/** 0.934 → \"0.93\", 0.8 → \"0.8\", 1 → \"1\". */\nexport const formatProbability = (p: number): string => String(Math.round(p * 100) / 100)\n","import type { 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 { useEffect, useState } from 'react'\nimport { MEDIA_AUDIO_TYPES, MEDIA_IMAGE_TYPES, type VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { MediaView, TranscriptView } from '../types.js'\nimport { FileIcon } from './icons.js'\n\n/**\n * How a generated file may be shown: only the types the core's media tools accept\n * (PNG / JPEG / GIF / WebP, and its audio list). Anything else - SVG included - is a file chip.\n */\nexport const mediaFamilyOf = (mediaType: string): 'image' | 'audio' | undefined => {\n const type = mediaType.toLowerCase().split(';')[0].trim()\n if (Object.hasOwn(MEDIA_IMAGE_TYPES, type)) return 'image'\n if (Object.hasOwn(MEDIA_AUDIO_TYPES, type)) return 'audio'\n return undefined\n}\n\nconst bytesOf = (content: string, encoding: string): Uint8Array<ArrayBuffer> => {\n if (encoding !== 'base64') return new TextEncoder().encode(content)\n const binary = atob(content)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\n/**\n * An object URL of a workspace file, typed as `mediaType` (never as whatever the file says it\n * is), revoked when the file, the workspace or the component goes away.\n */\nconst useFileUrl = (\n files: VirtualFileSystem | undefined,\n path: string,\n mediaType: string | undefined,\n): string | undefined => {\n const [url, setUrl] = useState<string | undefined>(undefined)\n useEffect(() => {\n if (!files || !mediaType) return\n let made: string | undefined\n let gone = false\n files\n .read(path)\n .then((file) => {\n if (gone || !file) return\n made = URL.createObjectURL(\n new Blob([bytesOf(file.content, file.encoding)], { type: mediaType }),\n )\n setUrl(made)\n })\n .catch(() => {\n /* the chip stays */\n })\n return () => {\n gone = true\n if (made) URL.revokeObjectURL(made)\n setUrl(undefined)\n }\n }, [files, path, mediaType])\n return url\n}\n\nexport interface GeneratedMediaProps {\n media: MediaView\n /** The workspace the file is in (the core's `VirtualFileSystem`). Without it: a file chip. */\n files?: VirtualFileSystem\n labels?: AgentLabelsOverride\n}\n\n/**\n * A file a media tool wrote, read from the workspace: an image inline, audio as a native\n * player. A type the core does not generate, a missing file or no workspace gives a chip with\n * the path.\n */\nexport const GeneratedMedia = ({ media, files, labels }: GeneratedMediaProps) => {\n const L = useLabels(labels)\n const family = mediaFamilyOf(media.mediaType)\n const type = family ? media.mediaType.toLowerCase().split(';')[0].trim() : undefined\n const url = useFileUrl(files, media.path, type)\n if (url && family === 'image') {\n return (\n <a\n className=\"awr-media awr-media--image\"\n href={url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n title={media.path}\n >\n <img className=\"awr-media__img\" src={url} alt={L.mediaImage(media.path)} />\n </a>\n )\n }\n if (url && family === 'audio') {\n return (\n <span className=\"awr-media awr-media--audio\" title={media.path}>\n <audio\n className=\"awr-media__audio\"\n controls\n preload=\"metadata\"\n src={url}\n aria-label={L.mediaAudio(media.path)}\n />\n </span>\n )\n }\n return (\n <span className=\"awr-chip awr-file awr-media awr-media--file\" title={L.mediaFile(media.path)}>\n <FileIcon size={13} /> {media.path}\n </span>\n )\n}\n\nexport interface TranscriptBlockProps {\n transcript: TranscriptView\n labels?: AgentLabelsOverride\n}\n\n/**\n * What an audio file said, folded: \"Transcript of memo.mp3\". The text is the content of the\n * user's file - shown as plain text and marked as such.\n */\nexport const TranscriptBlock = ({ transcript, labels }: TranscriptBlockProps) => {\n const L = useLabels(labels)\n return (\n <details className=\"awr-transcript\">\n <summary className=\"awr-transcript__summary\">\n <FileIcon size={13} /> {L.transcriptOf(transcript.name)}\n </summary>\n <p className=\"awr-transcript__note\">{L.transcriptNote}</p>\n <blockquote className=\"awr-transcript__text\">{transcript.text}</blockquote>\n </details>\n )\n}\n","import { Fragment } from 'react'\nimport type { ReactNode } from 'react'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type {\n ApprovalView,\n DecisionView,\n StepView,\n SubagentView,\n ToolCallView,\n UserNoteView,\n} from '../types.js'\nimport {\n formatDuration,\n formatProbability,\n formatTokens,\n imagesInOutput,\n previewValue,\n webSearchOf,\n} from './format.js'\nimport {\n AlertIcon,\n ArrowUpIcon,\n BrainIcon,\n CheckIcon,\n GlobeIcon,\n SendIcon,\n ShieldIcon,\n SpinnerIcon,\n ToolIcon,\n} from './icons.js'\nimport { SubagentTree, type RenderSubagent } from './SubagentTree.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 /**\n * Mark a call of an escalated attempt (\"attempt 1\") and a write that was not run a second\n * time (default true). Nothing shows without model tiers.\n */\n showTiers?: boolean\n /**\n * A `web_search` call's results as a short list under the row: the query, then title + host\n * of each result as a link and its snippet as plain text (default true).\n */\n showSearchResults?: boolean\n labels?: AgentLabelsOverride\n}\n\n/** The name of the core's search tool (its `WEB_SEARCH_TOOL`). */\nconst WEB_SEARCH = 'web_search'\n\n/**\n * One tool call: name, arguments, status — and optionally its cost, any images it returned and,\n * for a web search, what it found.\n */\nexport const ToolCallRow = ({\n call,\n showUsage = true,\n showTiers = true,\n showSearchResults = true,\n labels,\n}: 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 search =\n showSearchResults && call.name === WEB_SEARCH && call.status === 'done' && call.ok !== false\n ? webSearchOf(call.output)\n : undefined\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\n className={`awr-tool awr-tool--${state}${showTiers && call.attempt !== undefined ? ' awr-tool--earlier' : ''}`}\n >\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 {showTiers && call.replayed && (\n <span className=\"awr-tool__tag\" title={L.replayedTitle}>\n {L.replayed}\n </span>\n )}\n {showTiers && call.attempt !== undefined && (\n <span className=\"awr-tool__tag\">{L.attemptTag(call.attempt)}</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 {search && (\n <div className=\"awr-search\">\n <p className=\"awr-search__query\">\n <GlobeIcon size={12} /> {L.searchQuery} <q>{search.query}</q>\n </p>\n {search.results.length > 0 ? (\n <ol className=\"awr-search__results\">\n {search.results.map((r, i) => (\n <li key={i} className=\"awr-search__result\">\n {/* Third-party text: React text nodes only, never markup. */}\n <a\n className=\"awr-search__title\"\n href={r.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {r.title}\n </a>{' '}\n <span className=\"awr-search__host\">\n {r.host}\n {r.date ? ` · ${r.date}` : ''}\n </span>\n {r.snippet && <p className=\"awr-search__snippet\">{r.snippet}</p>}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"awr-search__note\">{L.searchNoResults}</p>\n )}\n {(search.filtered > 0 || search.truncated) && (\n <p className=\"awr-search__note\">\n {[\n search.filtered > 0 ? L.searchFiltered(search.filtered) : '',\n search.truncated ? L.searchTruncated : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </p>\n )}\n </div>\n )}\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\n/** \"decision model: continue (0.93)\" / \"decision model fell back: low confidence (0.41 < 0.8)\". */\nexport const decisionNote = (d: DecisionView, L: AgentLabels): string => {\n if (d.accepted) {\n return L.decisionAccepted(\n d.choice ?? '',\n d.confidence !== undefined ? formatProbability(d.confidence) : '',\n )\n }\n const detail =\n d.reason === 'low-confidence' && d.confidence !== undefined\n ? `${formatProbability(d.confidence)} < ${formatProbability(d.threshold)}`\n : ''\n return L.decisionFellBack(d.reason ? L.decisionReasons[d.reason] : '', detail)\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 showTiers: boolean\n showReplanFailed: boolean\n showDecisions: boolean\n showSearchResults: boolean\n showSubagents: boolean\n renderToolCall?: RenderToolCall\n renderSubagent?: RenderSubagent\n L: AgentLabels\n}\n\nconst StepItem = ({\n step,\n subagents,\n approvals,\n notes,\n onStopSubagent,\n showToolCalls,\n showUsage,\n showThoughts,\n showTiers,\n showReplanFailed,\n showDecisions,\n showSearchResults,\n showSubagents,\n renderToolCall,\n renderSubagent,\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 {showTiers && step.tier && (\n <div className=\"awr-step__meta\">\n <span\n className={`awr-step__tier awr-step__tier--${step.tier}`}\n title={step.tierReason ? L.tierReasons[step.tierReason] : undefined}\n >\n {L.tierNames[step.tier]}\n </span>\n {step.model && <span className=\"awr-step__model\">{step.model}</span>}\n </div>\n )}\n {showTiers &&\n step.escalations?.map((e, i) => (\n <div key={i} className=\"awr-step__escalated\">\n <p className=\"awr-step__escalated-line\">\n <ArrowUpIcon size={12} />\n <span>\n {L.escalated(L.tierNames[e.from], L.tierNames[e.to], L.escalationReasons[e.reason])}\n </span>\n </p>\n {e.text?.trim() && (\n <details className=\"awr-step__attempt\">\n <summary>{L.escalatedAttemptText}</summary>\n <p className=\"awr-step__text\">{e.text.trim()}</p>\n </details>\n )}\n </div>\n ))}\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 = (\n <ToolCallRow\n key={i}\n call={call}\n showUsage={showUsage}\n showTiers={showTiers}\n showSearchResults={showSearchResults}\n />\n )\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 {a.subagent && <span className=\"awr-tool__tag\">{L.subagentHelper}</span>}\n </li>\n ))}\n </ul>\n )}\n {showSubagents && (\n <SubagentTree\n subagents={subagents}\n onStop={onStopSubagent}\n showUsage={showUsage}\n renderSubagent={renderSubagent}\n />\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 {showReplanFailed && step.replanFailed && (\n <p className=\"awr-step__warn\" title={step.replanFailed}>\n <AlertIcon size={12} /> {L.replanFailed}\n </p>\n )}\n {showDecisions &&\n step.decisions?.map((d, i) => (\n <p\n key={i}\n className={`awr-step__decision${d.accepted ? '' : ' awr-step__decision--fallback'}`}\n title={d.model}\n >\n {decisionNote(d, L)}\n </p>\n ))}\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 /** The subagent tree under the step that started it (default true). */\n showSubagents?: boolean\n /** Render a node of the subagent tree yourself (gets the built-in `<li>` as `fallback`). */\n renderSubagent?: RenderSubagent\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 /**\n * Model tiers: the tier / model badge on a step, its \"escalated: light → strong\" line and the\n * marks on the earlier attempt's tool calls (default true; nothing shows when tiers are off).\n */\n showTiers?: boolean\n /** The \"replanning failed, continuing with the plan\" warning under a step (default true). */\n showReplanFailed?: boolean\n /**\n * The decision model's note under the step it was asked after - \"decision model: continue\n * (0.93)\" (default true; nothing shows without `decisionModel`).\n */\n showDecisions?: boolean\n /** A `web_search` call's results as a list under its row (default true). */\n showSearchResults?: 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 showTiers = true,\n showReplanFailed = true,\n showDecisions = true,\n showSearchResults = true,\n showSubagents = true,\n renderToolCall,\n renderSubagent,\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 // A subagent is drawn under the step that delegated it (its own subagents come with it: they\n // carry the same step). One whose step is not known is drawn at the end rather than lost.\n const loose = showSubagents ? subagents.filter((s) => !s.stepId || !known.has(s.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 showTiers={showTiers}\n showReplanFailed={showReplanFailed}\n showDecisions={showDecisions}\n showSearchResults={showSearchResults}\n showSubagents={showSubagents}\n renderToolCall={renderToolCall}\n renderSubagent={renderSubagent}\n L={L}\n />\n ))}\n {loose.length > 0 && (\n <li className=\"awr-step awr-step--subagents\">\n <SubagentTree\n subagents={loose}\n onStop={onStopSubagent}\n showUsage={showUsage}\n renderSubagent={renderSubagent}\n />\n </li>\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 { Fragment, useEffect, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { subagentTree } from '../state.js'\nimport type { SubagentNode, SubagentView } from '../types.js'\nimport { formatDuration, formatTokens, previewValue } from './format.js'\nimport { AlertIcon, BotIcon, SpinnerIcon, StopIcon } from './icons.js'\n\n/** Render a node yourself; `fallback` is the built-in `<li>` (with its children) — return it, or your own `<li>`. */\nexport type RenderSubagent = (node: SubagentNode, fallback: ReactNode) => ReactNode\n\n/** Seconds a running node has been going, ticking; nothing without a start time. */\nconst useElapsed = (startedAt: number | undefined, running: boolean): number | undefined => {\n const [now, setNow] = useState<number | undefined>(undefined)\n useEffect(() => {\n if (!running || startedAt === undefined) return\n setNow(Date.now())\n const timer = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(timer)\n }, [running, startedAt])\n return running && startedAt !== undefined && now !== undefined\n ? Math.max(0, now - startedAt)\n : undefined\n}\n\nexport interface SubagentRowProps {\n sub: SubagentView\n /** Stop this subagent (`useAgent().stopSubagent`); the button shows while it runs. */\n onStop?: (id: string) => void\n /** Its status line: status, model, tokens, tool calls, time (default true). */\n showUsage?: boolean\n /** The tools a helper was given (default true). */\n showTools?: boolean\n labels?: AgentLabelsOverride\n /** The subagents this one started (the tree puts them here). */\n children?: ReactNode\n}\n\n/**\n * One subagent - a static one or a helper the model started: who it is, its task, its status\n * with the model, tokens and time, what it is doing, and its answer when done. With `onStop`,\n * a running one gets a stop button (the run and its siblings go on).\n */\nexport const SubagentRow = ({\n sub,\n onStop,\n showUsage = true,\n showTools = true,\n labels,\n children,\n}: SubagentRowProps) => {\n const L = useLabels(labels)\n const running = sub.status === 'running'\n const elapsed = useElapsed(sub.startedAt, running)\n const time = sub.durationMs ?? elapsed\n // A helper's role is what the model wrote for it: plain text, shown as its name.\n const role = sub.dynamic ? previewValue(sub.role ?? '', 48) : ''\n const meta = [\n sub.model ?? '',\n sub.tier ? L.tierNames[sub.tier] : '',\n sub.usage.totalTokens > 0 ? L.subagentTokens(formatTokens(sub.usage.totalTokens)) : '',\n sub.toolCalls > 0 ? L.toolCalls(sub.toolCalls) : '',\n time !== undefined ? formatDuration(time) : '',\n ].filter(Boolean)\n return (\n <li\n className={`awr-subagent awr-subagent--${sub.status}${sub.dynamic ? ' awr-subagent--dynamic' : ''}`}\n data-depth={sub.depth}\n >\n <div className=\"awr-subagent__head\">\n <span className=\"awr-subagent__icon\">\n {running ? (\n <SpinnerIcon size={13} />\n ) : sub.status === 'done' ? (\n <BotIcon size={13} />\n ) : sub.status === 'stopped' ? (\n <StopIcon size={13} />\n ) : (\n <AlertIcon size={13} />\n )}\n </span>\n <span className=\"awr-subagent__name\" title={sub.role}>\n {role || (sub.dynamic ? L.subagentHelper : sub.name)}\n </span>\n {sub.dynamic && role && <span className=\"awr-subagent__profile\">{L.subagentHelper}</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 {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 {showUsage && (\n <div className=\"awr-subagent__meta\">\n <span className=\"awr-subagent__status\">{L.subagentStatus[sub.status]}</span>\n {meta.map((part, i) => (\n <span key={i} className=\"awr-subagent__metaitem\">\n {part}\n </span>\n ))}\n </div>\n )}\n {showTools && sub.tools && (\n <div className=\"awr-subagent__tools\">\n {sub.tools.length > 0 ? L.subagentTools(sub.tools.join(', ')) : L.subagentNoTools}\n </div>\n )}\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}${!showUsage && sub.toolCalls ? ` · ${L.toolCalls(sub.toolCalls)}` : ''}`}\n </div>\n {children}\n </li>\n )\n}\n\nexport interface SubagentTreeProps {\n /**\n * The subagents to draw (`agent.subagents`, or a message's): static subagents and the helpers\n * the model started, at any depth. The flat list is nested by `parentId`.\n */\n subagents: SubagentView[]\n /** Give each running node a stop button (`useAgent().stopSubagent`). */\n onStop?: (id: string) => void\n /** Each node's status line: status, model, tokens, tool calls, time (default true). */\n showUsage?: boolean\n /** The tools each helper was given (default true). */\n showTools?: boolean\n /** Render a node yourself (gets the built-in `<li>` as `fallback`). */\n renderSubagent?: RenderSubagent\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * The run's subagents as an indented tree: each node with its status, model, tokens and time,\n * what it is doing, and - while it runs - a stop button. A helper's own helpers sit under it.\n * Renders nothing when there are none.\n */\nexport const SubagentTree = ({\n subagents,\n onStop,\n showUsage = true,\n showTools = true,\n renderSubagent,\n labels,\n className,\n}: SubagentTreeProps) => {\n if (subagents.length === 0) return null\n const branch = (nodes: SubagentNode[], nested: boolean): ReactNode => (\n <ul\n className={['awr-subagents', nested ? 'awr-subagents--nested' : className]\n .filter(Boolean)\n .join(' ')}\n >\n {nodes.map((node) => {\n const row = (\n <SubagentRow\n key={node.id}\n sub={node}\n onStop={onStop}\n showUsage={showUsage}\n showTools={showTools}\n labels={labels}\n >\n {node.children.length > 0 ? branch(node.children, true) : null}\n </SubagentRow>\n )\n return renderSubagent ? <Fragment key={node.id}>{renderSubagent(node, row)}</Fragment> : row\n })}\n </ul>\n )\n return branch(subagentTree(subagents), false)\n}\n","import type { ReactNode } from 'react'\nimport type { IUsage, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ChatAttachment, ChatMessage, MediaView } from '../types.js'\nimport { formatDuration, formatTokens } from './format.js'\nimport { BookIcon, BrainIcon, FileIcon, GlobeIcon, SpinnerIcon } from './icons.js'\nimport { GeneratedMedia, TranscriptBlock } from './Media.js'\nimport { StepList, type RenderToolCall } from './StepList.js'\nimport type { RenderSubagent } from './SubagentTree.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 /** Model tiers: the tier badges, escalation lines and the escalation count (default true). */\n showTiers?: boolean\n /** The \"replanning failed, continuing with the plan\" warning under a step (default true). */\n showReplanFailed?: boolean\n /** The decision model's note under a step (default true; nothing shows without one). */\n showDecisions?: boolean\n /** A `web_search` call's results as a list under its row (default true). */\n showSearchResults?: boolean\n /** The subagent tree under the step that started it (default true). */\n showSubagents?: boolean\n /**\n * What the run generated, in the answer: images inline, audio as a player - and the\n * transcripts of audio files, folded (default true). Needs `files` to show the bytes.\n */\n showMedia?: boolean\n /** The workspace generated files are read from (the core's `VirtualFileSystem`). */\n files?: VirtualFileSystem\n /** A generated file; `fallback` is the built-in image / player / chip. */\n renderMedia?: (media: MediaView, message: ChatMessage, fallback: ReactNode) => ReactNode\n /** A node of the subagent tree (gets the built-in `<li>` as `fallback`). */\n renderSubagent?: RenderSubagent\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 showTiers: 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 const escalations = steps.reduce((n, s) => n + (s.escalations?.length ?? 0), 0)\n if (showTiers && escalations > 0) parts.push(L.escalations(escalations))\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 showTiers = true,\n showReplanFailed = true,\n showDecisions = true,\n showSearchResults = true,\n showSubagents = true,\n showMedia = true,\n files,\n renderMedia,\n renderSubagent,\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, showTiers, 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 showTiers={showTiers}\n showReplanFailed={showReplanFailed}\n showDecisions={showDecisions}\n showSearchResults={showSearchResults}\n showSubagents={showSubagents}\n renderToolCall={renderToolCall}\n renderSubagent={renderSubagent}\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 {showMedia && m.transcripts?.length ? (\n <div className=\"awr-msg__transcripts\">\n {m.transcripts.map((t, i) => (\n <TranscriptBlock key={i} transcript={t} labels={labels} />\n ))}\n </div>\n ) : null}\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 {showMedia && m.media?.length ? (\n <div className=\"awr-msg__media\">\n {m.media.map((item, i) => {\n const built = (\n <GeneratedMedia key={i} media={item} files={files} labels={labels} />\n )\n return renderMedia ? (\n <span key={i} className=\"awr-msg__mediaitem\">\n {renderMedia(item, m, built)}\n </span>\n ) : (\n built\n )\n })}\n </div>\n ) : null}\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 /** Say which helper is asking when the call is a helper's, not the run's own (default true). */\n showHelper?: 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 showHelper = 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 // A helper's role is text the model wrote: shown as plain text, shortened.\n const helper = showHelper ? a.subagent : undefined\n const card = (\n <div\n key={a.id}\n className={`awr-approval${helper ? ' awr-approval--helper' : ''}`}\n data-subagent={helper?.id}\n >\n <div className=\"awr-approval__head\">\n <ShieldIcon size={14} className=\"awr-approval__icon\" />\n <span>\n {helper\n ? L.approvalLeadHelper(\n previewValue(helper.role ?? '', 60) || undefined,\n helper.depth,\n )\n : L.approvalLead}{' '}\n <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 { useLabels, type AgentLabelsOverride } from '../labels.js'\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 /**\n * Calls that are not tokens - to the media models and to the decision model - when there were\n * any (default true).\n */\n showCalls?: boolean\n labels?: AgentLabelsOverride\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, and the media / decision calls when the run made\n * some. The full breakdown is on hover.\n */\nexport const UsageBadge = ({\n usage,\n compact = false,\n showCalls = true,\n labels,\n className,\n}: UsageBadgeProps) => {\n const L = useLabels(labels)\n const media = showCalls ? (usage.mediaCalls ?? 0) : 0\n const decisions = showCalls ? (usage.decisionCalls ?? 0) : 0\n if (usage.totalTokens === 0 && media === 0 && decisions === 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 media ? L.usageMedia(media) : '',\n decisions ? L.usageDecisions(decisions) : '',\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 {!compact && media > 0 && ` · ${L.usageMedia(media)}`}\n {!compact && decisions > 0 && ` · ${L.usageDecisions(decisions)}`}\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqE;AAErE,IAAAA,oBAcO;;;AChBP,uBAKO;AA4DP,IAAM,eAAe,CAAC,UAA2B;AAC/C,MAAI,UAAU,OAAW,QAAO;AAChC,MAAIC;AACJ,MAAI;AACF,IAAAA,QAAO,OAAO,UAAU,WAAW,QAAS,KAAK,UAAU,KAAK,KAAK;AAAA,EACvE,QAAQ;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ACA,aAAa,UAAU,+DAAuB;AAAA,UAC9C,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,UACxC,WAAW,CAAC,MAAM;AAChB,gBAAI,EAAE,QAAQ,SAAS;AACrB,gBAAE,eAAe;AACjB,mBAAK,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,UACA,UAAU;AAAA;AAAA,MACZ;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,OAAO;AAAA,UAC3B,UAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OAEJ;AAAA,KACF;AAEJ;;;AjC8BA,IAAAC,oBA0BO;","names":["import_agent_web","text","base","m","req","text","import_react","import_react","text","import_react","import_react","import_agent_web","import_agent_web","import_react","model","import_react","text","base","import_react","import_jsx_runtime","import_react","import_react","import_jsx_runtime","import_jsx_runtime","readDataUrl","text","import_react","import_jsx_runtime","text","import_jsx_runtime","import_react","import_jsx_runtime","text","import_react","import_agent_web","import_jsx_runtime","import_react","import_react","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","Composer","import_jsx_runtime","import_react","import_jsx_runtime","text","import_jsx_runtime","import_jsx_runtime","import_react","import_jsx_runtime","import_agent_web"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/hooks/use-agent.ts","../src/approval-queue.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/elicitation.ts","../src/components/AgentChat.tsx","../src/hooks/use-mcp-app-host.ts","../src/mcp-app.ts","../src/html-preview.ts","../src/mcp-app-policy.ts","../src/components/icons.tsx","../src/components/AppRequestPrompt.tsx","../src/components/McpAppFrame.tsx","../src/components/AgentComposer.tsx","../src/components/ChatHistoryList.tsx","../src/components/format.ts","../src/components/ContextMeter.tsx","../src/components/ElicitationPrompt.tsx","../src/components/FilesPanel.tsx","../src/components/FileChips.tsx","../src/file-kinds.ts","../src/components/Media.tsx","../src/components/SandboxedFrame.tsx","../src/components/StepList.tsx","../src/components/SubagentTree.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"],"sourcesContent":["// ── 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, subagentTree } from './state.js'\nexport type { AgentAction } from './state.js'\n// The form inside an `ElicitationView` (types only: the MCP hooks are the `./mcp` entry).\nexport type {\n McpElicitationFieldSchema,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './mcp-types.js'\n// The prompt's pure half: a form's fields, the answer and its checks, a link, the countdown.\nexport {\n elicitationFields,\n elicitationFormAnswer,\n elicitationInitialDraft,\n elicitationLink,\n formatCountdown,\n} from './elicitation.js'\nexport type {\n ElicitationControl,\n ElicitationDraft,\n ElicitationDraftValue,\n ElicitationField,\n ElicitationFormOutcome,\n ElicitationIssue,\n ElicitationIssueKind,\n ElicitationLink,\n ElicitationOption,\n ElicitationOutcomeReason,\n PendingElicitation,\n} from './elicitation.js'\nexport type {\n AgentUiState,\n AgentStatus,\n QueuedMessageView,\n UserNoteView,\n ApprovalView,\n SkillConsentView,\n ElicitationView,\n BudgetView,\n ChatAttachment,\n ChatMessage,\n CompactionView,\n DecisionView,\n FetchView,\n LessonView,\n MediaView,\n StepEscalationView,\n StepView,\n SubagentNode,\n SubagentView,\n ToolCallView,\n TranscriptView,\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, ToolCallRow, UserNoteRow, decisionNote } from './components/StepList.js'\nexport type { StepListProps, ToolCallRowProps, RenderToolCall } from './components/StepList.js'\nexport { SubagentRow, SubagentTree } from './components/SubagentTree.js'\nexport type {\n RenderSubagent,\n SubagentRowProps,\n SubagentTreeProps,\n} from './components/SubagentTree.js'\nexport { GeneratedMedia, TranscriptBlock, mediaFamilyOf } from './components/Media.js'\nexport type { GeneratedMediaProps, TranscriptBlockProps } from './components/Media.js'\nexport { FileChip, FileChips, SourceView, FILE_PREVIEW_CHARS } from './components/FileChips.js'\nexport type {\n FileChipProps,\n FileChipsProps,\n HtmlPreviewOptions,\n SourceViewProps,\n} from './components/FileChips.js'\nexport {\n SandboxedFrame,\n clampFrameHeight,\n FRAME_MAX_HEIGHT,\n FRAME_MIN_HEIGHT,\n} from './components/SandboxedFrame.js'\nexport type { SandboxedFrameProps } from './components/SandboxedFrame.js'\nexport {\n buildSandboxedDocument,\n escapeAttribute,\n linkedFilesOf,\n sandboxedCsp,\n sandboxTokens,\n tokenizeHtml,\n withCspFirst,\n withPolicyFirst,\n HTML_PREVIEW_MAX_CHARS,\n} from './html-preview.js'\nexport type { SandboxedDocumentOptions, SourceToken } from './html-preview.js'\nexport { fileKindOf, fileNameOf } from './file-kinds.js'\nexport type { FileKind } from './file-kinds.js'\nexport { webSearchOf } from './components/format.js'\nexport type { WebSearchResultView, WebSearchView } from './components/format.js'\nexport { ToolApprovalPrompt } from './components/ToolApprovalPrompt.js'\nexport type { ToolApprovalPromptProps } from './components/ToolApprovalPrompt.js'\nexport { createApprovalQueue } from './approval-queue.js'\nexport type { ApprovalQueue } from './approval-queue.js'\nexport { ElicitationPrompt } from './components/ElicitationPrompt.js'\nexport type { ElicitationPromptProps } from './components/ElicitationPrompt.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 ToolApprovalContext,\n ToolApprovalMode,\n ToolApprovalRequest,\n SubagentToolOptions,\n SubagentWorkerConfig,\n RunFile,\n VirtualFile,\n VirtualFileInfo,\n FileToolsOptions,\n} from '@dudko.dev/agent-web'\n\n// ── MCP Apps (an app a server's tool came with, in a sandboxed frame) ───────\nexport { McpAppFrame, McpAppLine } from './components/McpAppFrame.js'\nexport type { McpAppFrameProps, McpAppLineProps } from './components/McpAppFrame.js'\nexport { AppRequestPrompt } from './components/AppRequestPrompt.js'\nexport type { AppRequestPromptProps } from './components/AppRequestPrompt.js'\nexport { useMcpAppHost } from './hooks/use-mcp-app-host.js'\nexport type {\n AppDownloadView,\n AppRequestAnswerOptions,\n AppRequestView,\n McpAppHost,\n McpAppsConnectionLike,\n UseMcpAppHostOptions,\n} from './hooks/use-mcp-app-host.js'\nexport {\n APP_DEFAULT_HEIGHT,\n APP_MAX_HEIGHT,\n APP_MIN_HEIGHT,\n appDisplayModeAllowed,\n appDownloadOf,\n appDownloadRefusal,\n appFileExtensionOf,\n appFileNameOf,\n appGestureOf,\n appLinkOf,\n appMessageTextOf,\n appMimeTypeOf,\n appSamplingErrorOf,\n buildMcpAppDocument,\n clampAppHeight,\n grantedAppCsp,\n MCP_APP_DISPLAY_MODES,\n MCP_APP_MAX_ARGS_CHARS,\n MCP_APP_MAX_DOWNLOAD_BYTES,\n MCP_APP_MAX_FILE_NAME_CHARS,\n MCP_APP_MAX_IN_FLIGHT,\n MCP_APP_MAX_MESSAGE_CHARS,\n MCP_APP_MAX_URL_CHARS,\n MCP_APP_NOTIFICATIONS,\n MCP_APP_OPTIONAL_REQUESTS,\n MCP_APP_PROTOCOL_VERSION,\n MCP_APP_REFUSED,\n MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS,\n MCP_APP_REFUSED_DOWNLOAD_TYPES,\n MCP_APP_RELAY,\n MCP_APP_REQUESTS,\n MCP_APP_SANDBOX_FRAME_TOKENS,\n MCP_APP_SANDBOX_GRACE_MS,\n MCP_APP_SANDBOX_SERVER,\n MCP_APP_SANDBOX_TIMEOUT_MS,\n McpAppBridge,\n mcpAppCsp,\n mcpAppHostCapabilities,\n McpAppRpcError,\n resolveAppDownload,\n saveAppFile,\n // An app on an origin of its own (the sandbox proxy; the page itself is `./mcp-app-sandbox`).\n buildMcpAppSandboxShell,\n McpAppSandboxLink,\n mcpAppSandboxProxyUrl,\n mcpAppSandboxShellCsp,\n mcpAppSandboxTarget,\n} from './mcp-app.js'\nexport type {\n AppDownload,\n AppFileSaverEnv,\n AppLink,\n AppReadyDownload,\n AppResourceReader,\n McpAppBridgeHandlers,\n McpAppDisplayMode,\n McpAppBridgeOptions,\n McpAppRpcMessage,\n McpAppSandboxInput,\n McpAppSandboxLinkOptions,\n McpAppSandboxOptions,\n McpAppSandboxReason,\n McpAppSandboxTarget,\n} from './mcp-app.js'\nexport {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n mcpAppPolicyToken,\n} from './mcp-app-policy.js'\nexport type { AppView } from './types.js'\nexport type {\n AppToolCallRequest,\n McpAppCsp,\n McpAppResource,\n McpAppToolResult,\n} from '@dudko.dev/agent-web'\n","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 AppSamplingRequest,\n type AppSamplingResult,\n type AppSamplingView,\n type AppToolCallRequest,\n type BrowserAgentConfig,\n type CompactResult,\n type RunControl,\n type RunFile,\n type RunResult,\n type ToolApprovalContext,\n type ToolApprovalDecision,\n type ToolApprovalMode,\n type ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\nimport { createApprovalQueue } from '../approval-queue.js'\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 /**\n * Ask the agent's consent gate about a tool call an MCP App wants to make (the core's\n * `Agent.approveAppToolCall`: the same rules and modes, never silent for a write, \"always\n * allow\" kept apart from the model's). The request joins `pendingApprovals` with `app` set,\n * and waits across runs - a run ending or `stop()` does not answer it; `signal` does (the\n * app's frame going away). Resolves when the call may go; throws when it may not.\n */\n approveAppToolCall: (call: AppToolCallRequest, signal?: AbortSignal) => Promise<void>\n /**\n * Answer a completion an MCP App asks for (its `sampling/createMessage`) with the agent's model:\n * the core's `Agent.sampleForApp` - checked, rate-limited per app, put to `approve` (shown\n * exactly what the model gets), then sent with no tools and none of the conversation. The\n * tokens count in `totalUsage` (a `usage` event of phase `'app'`, never the run's); the answer\n * is returned to the caller and never reaches the transcript, the memory or the model's context.\n * Throws the core's `AppSamplingError` (its `rpcCode` is what the app is told).\n */\n sampleForApp: (\n request: AppSamplingRequest,\n approve: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ) => Promise<AppSamplingResult>\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. One the core stops waiting\n // for (its timeoutMs ran out, the run stopped) leaves its queue by its signal. An MCP App's are\n // kept in a queue of their own: they are not the run's, so a run ending (or stopped) does not\n // answer them.\n const [approvals] = useState(createApprovalQueue)\n const [appApprovals] = useState(createApprovalQueue)\n const settleAll = useCallback(\n (decision: ToolApprovalDecision) => approvals.settleAll(decision),\n [approvals],\n )\n const uiOnRequest = useCallback(\n (req: ToolApprovalRequest, ctx?: ToolApprovalContext) =>\n (req.app ? appApprovals : approvals).handler(req, ctx),\n [approvals, appApprovals],\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 appApprovals.settleAll({ approved: false, reason: 'the view was closed' })\n },\n [settleAll, appApprovals],\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 // The waiting request with this id - the run's or an app's.\n const approve = useCallback(\n (id: string, opts?: ApproveOptions) => {\n if (!approvals.approve(id, { remember: opts?.remember })) {\n appApprovals.approve(id, { remember: opts?.remember })\n }\n },\n [approvals, appApprovals],\n )\n\n const deny = useCallback(\n (id: string, reason?: string) => {\n if (!approvals.deny(id, reason)) appApprovals.deny(id, reason)\n },\n [approvals, appApprovals],\n )\n\n const approveAppToolCall = useCallback(\n async (call: AppToolCallRequest, signal?: AbortSignal): Promise<void> => {\n const agent = agentRef.current\n if (!agent) throw new Error('The agent is not ready')\n // An older core has no gate for apps: refuse rather than let the call through.\n if (typeof agent.approveAppToolCall !== 'function') {\n throw new Error('This version of @dudko.dev/agent-web cannot ask about an app’s calls')\n }\n await agent.approveAppToolCall(\n call,\n (event) => {\n // Decided (or given up on): nothing waits on the answer any more. The queue drops a\n // request whose signal aborted; this also covers a core that sends no signal.\n if (event.type === 'tool.approval-resolved')\n appApprovals.deny(event.id, 'no longer asked')\n dispatch({\n type: 'event',\n event,\n maxEvents: optionsRef.current.maxEvents,\n at: Date.now(),\n })\n },\n signal,\n )\n },\n [],\n )\n\n const sampleForApp = useCallback(\n async (\n request: AppSamplingRequest,\n approve: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ): Promise<AppSamplingResult> => {\n const agent = agentRef.current\n if (!agent) throw new Error('The agent is not ready')\n // An older core cannot: refuse rather than answer without the core's checks.\n if (typeof agent.sampleForApp !== 'function') {\n throw new Error('This version of @dudko.dev/agent-web cannot answer an app’s sampling')\n }\n return agent.sampleForApp(request, {\n approve,\n ...(signal ? { signal } : {}),\n sessionId: sessionRef.current,\n // The only event: its tokens (phase 'app'). The answer is never dispatched.\n onEvent: (event) =>\n dispatch({\n type: 'event',\n event,\n maxEvents: optionsRef.current.maxEvents,\n at: Date.now(),\n }),\n })\n },\n [],\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 approveAppToolCall,\n sampleForApp,\n compact,\n sessionId,\n loadChat,\n }\n}\n","import type {\n ToolApprovalContext,\n ToolApprovalDecision,\n ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\n\n/** The consent requests waiting for a person, by request id. */\nexport interface ApprovalQueue {\n /**\n * The core's `toolApproval.onRequest`: resolves when `approve` / `deny` is called. A request\n * the core stops waiting for (`ctx.signal`: its `timeoutMs` ran out, the run stopped) leaves\n * the queue at once, so no stale answer is kept for it.\n */\n handler: (req: ToolApprovalRequest, ctx?: ToolApprovalContext) => Promise<ToolApprovalDecision>\n /** Allow one. False when no such request is waiting (answered, expired, settled). */\n approve: (id: string, options?: { remember?: boolean }) => boolean\n /** Deny one. False when no such request is waiting. */\n deny: (id: string, reason?: string) => boolean\n /** Answer every waiting request with `decision` (the run ended, the view closed). */\n settleAll: (decision: ToolApprovalDecision) => void\n /** The ids of the requests waiting, oldest first. */\n pending: () => string[]\n}\n\n/**\n * The queue behind `useAgent`'s `approve` / `deny`: `request.id → resolver`. A request leaves it\n * exactly once - answered, settled by `settleAll`, or dropped when the core no longer wants the\n * answer (its signal aborted; the core has already denied the call and said so in its event).\n */\nexport const createApprovalQueue = (): ApprovalQueue => {\n const waiting = new Map<string, (decision: ToolApprovalDecision) => void>()\n\n const handler: ApprovalQueue['handler'] = (req, ctx) =>\n new Promise<ToolApprovalDecision>((resolve) => {\n const signal = ctx?.signal\n if (signal?.aborted) {\n resolve({ approved: false, reason: 'no longer asked' })\n return\n }\n const onAbort = (): void => {\n if (waiting.get(req.id) !== settle) return\n settle({ approved: false, reason: 'no longer asked' })\n }\n // Called only for the request in the map (every caller looks it up first): exactly once.\n const settle = (decision: ToolApprovalDecision): void => {\n waiting.delete(req.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(decision)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n waiting.set(req.id, settle)\n })\n\n const answer = (id: string, decision: ToolApprovalDecision): boolean => {\n const settle = waiting.get(id)\n if (!settle) return false\n settle(decision)\n return true\n }\n\n return {\n handler,\n approve: (id, options) => answer(id, { approved: true, remember: options?.remember }),\n deny: (id, reason) => answer(id, { approved: false, reason }),\n settleAll: (decision) => {\n for (const settle of [...waiting.values()]) settle(decision)\n },\n pending: () => [...waiting.keys()],\n }\n}\n","import {\n isReplayedToolOutput,\n type AgentEvent,\n type IUsage,\n type Skill,\n} from '@dudko.dev/agent-web'\nimport type {\n AppView,\n WrittenFileView,\n AgentUiState,\n ApprovalView,\n ElicitationView,\n ChatAttachment,\n ChatMessage,\n DecisionView,\n LessonView,\n MediaView,\n StepView,\n SubagentNode,\n SubagentView,\n ToolCallView,\n TranscriptView,\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\n// What a usage record counts besides tokens: calls to the media models and to the decision\n// model. Absent until there is one, so a run without them keeps the six-field shape.\nconst USAGE_COUNTS = [\n 'mediaCalls',\n 'imagesGenerated',\n 'speechCharacters',\n 'transcriptionSeconds',\n 'decisionCalls',\n] as const\n\nconst addUsage = (a: IUsage, b: IUsage): IUsage => {\n const sum: IUsage = {\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),\n cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),\n cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0),\n }\n for (const key of USAGE_COUNTS) {\n const n = (a[key] ?? 0) + (b[key] ?? 0)\n if (n) sum[key] = n\n }\n return sum\n}\n\n/**\n * The notebook view of the agent's own skills (`agent.listLearnedSkills()`): what the core stored\n * about each lesson, in the shape the UI keeps current from `skill.learned` events.\n */\nexport const lessonsOf = (skills: Skill[]): LessonView[] =>\n skills\n .filter((s) => s.origin?.kind === 'learned')\n .map((s) => ({\n name: s.name,\n description: s.description,\n revision: s.origin?.revision ?? 1,\n chars: s.content.length,\n sources: [...(s.origin?.sources ?? []), ...(s.origin?.fetched ?? [])],\n }))\n\n/** A fresh, empty view. */\nexport const createInitialAgentState = (): AgentUiState => ({\n status: 'idle',\n goal: undefined,\n plan: undefined,\n planThought: '',\n steps: [],\n finalText: '',\n finalReasoning: '',\n totalUsage: emptyUsage(),\n runStartedAt: undefined,\n runMessageId: undefined,\n approvals: [],\n subagents: [],\n queued: [],\n notes: [],\n undelivered: [],\n skills: [],\n learned: [],\n learnedNow: [],\n fetches: [],\n discoveredTools: [],\n compactions: [],\n budget: undefined,\n usage: emptyUsage(),\n modelLoad: undefined,\n replan: undefined,\n error: undefined,\n stopped: false,\n messages: [],\n events: [],\n seq: 0,\n})\n\n/** Clear only the per-run view; keep the transcript, totals, status and seq counter. */\nconst resetRun = (state: AgentUiState): AgentUiState => ({\n ...createInitialAgentState(),\n status: state.status,\n messages: state.messages,\n totalUsage: state.totalUsage,\n seq: state.seq,\n learned: state.learned,\n // An MCP App's request is the user's, not the run's: it waits across runs.\n approvals: state.approvals.filter((a) => a.app && a.status === 'pending'),\n})\n\n/** Apply `fn` to the step whose id matches, leaving the rest untouched. */\nconst patchStep = (steps: StepView[], id: string, fn: (s: StepView) => StepView): StepView[] =>\n steps.map((s) => (s.id === id ? fn(s) : s))\n\n/**\n * A decided request about an MCP server's skill keeps who and what - not the server's text: the\n * preview was for the decision, and a saved conversation must not hold a server's instructions.\n */\nconst withoutSkillBody = (a: ApprovalView): ApprovalView => {\n if (!a.skill || a.skill.body === undefined) return a\n const { body: _body, ...skill } = a.skill\n return { ...a, skill }\n}\n\nconst patchApproval = (\n approvals: ApprovalView[],\n id: string,\n fn: (a: ApprovalView) => ApprovalView,\n): ApprovalView[] => approvals.map((a) => (a.id === id ? fn(a) : a))\n\nconst STATUS_OF_ACTION = {\n accept: 'accepted',\n decline: 'declined',\n cancel: 'cancelled',\n} as const\n\n/** A server's question (MCP elicitation) joins the run's view, once. */\nconst addElicitation = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'mcp.elicitation-requested' }>,\n extra: Pick<ElicitationView, 'stepId' | 'subagent'>,\n): AgentUiState =>\n state.elicitations?.some((e) => e.id === event.id)\n ? state\n : {\n ...state,\n elicitations: [\n ...(state.elicitations ?? []),\n {\n id: event.id,\n server: event.server,\n tool: event.tool,\n mode: event.mode,\n message: event.message,\n ...(event.requestedSchema ? { requestedSchema: event.requestedSchema } : {}),\n ...(event.url ? { url: event.url } : {}),\n ...(extra.stepId ? { stepId: extra.stepId } : {}),\n ...(extra.subagent ? { subagent: extra.subagent } : {}),\n status: 'pending',\n },\n ],\n }\n\n/** The question was answered; one that was refused before it could be shown is recorded too. */\nconst answerElicitation = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'mcp.elicitation-answered' }>,\n stepId: string | undefined,\n): AgentUiState => {\n const answered = (e: ElicitationView): ElicitationView => ({\n ...e,\n status: STATUS_OF_ACTION[event.action],\n automatic: event.automatic,\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.fields ? { fields: event.fields } : {}),\n })\n const list = state.elicitations ?? []\n return {\n ...state,\n elicitations: list.some((e) => e.id === event.id)\n ? list.map((e) => (e.id === event.id ? answered(e) : e))\n : [\n ...list,\n answered({\n id: event.id,\n server: event.server,\n tool: event.tool,\n message: '',\n ...(stepId ? { stepId } : {}),\n status: 'pending',\n }),\n ],\n }\n}\n\nconst patchSubagent = (\n subagents: SubagentView[],\n id: string,\n fn: (s: SubagentView) => SubagentView,\n): SubagentView[] => subagents.map((s) => (s.id === id ? fn(s) : s))\n\n/** The step currently executing (the last one still running). */\nconst runningStepId = (steps: StepView[]): string | undefined =>\n [...steps].reverse().find((s) => s.status === 'running')?.id\n\n/** Fold one of a subagent's own events into its compact view. */\nconst applySubagentEvent = (view: SubagentView, event: AgentEvent): SubagentView => {\n switch (event.type) {\n case 'step.start':\n return {\n ...view,\n steps: view.steps + 1,\n activity: `step ${event.index}/${event.total}: ${event.step.description}`,\n // Known only when the child runs with model tiers.\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n }\n case 'step.escalated':\n return { ...view, tier: event.to, ...(event.model ? { model: event.model } : {}) }\n case 'step.tool-call':\n return { ...view, toolCalls: view.toolCalls + 1, activity: `→ ${event.name}` }\n case 'final.text-delta':\n return { ...view, text: view.text + event.delta, activity: 'writing the answer' }\n case 'final':\n return { ...view, text: event.text }\n case 'usage':\n return { ...view, usage: addUsage(view.usage, event.usage) }\n default:\n return view\n }\n}\n\n/** A subagent an event came through on its way up (a `subagent.event` envelope). */\ninterface Ancestor {\n id: string\n}\n\ntype SubagentStart = Extract<AgentEvent, { type: 'subagent.start' }>\n\n/**\n * The node `id`, created when it is not there yet. An event can arrive for a subagent whose\n * `subagent.start` was never seen (a capped log replayed, a host that joined late): it gets a\n * node from what the envelope says - its name, and where in the tree it is.\n */\nconst ensureSubagent = (\n state: AgentUiState,\n id: string,\n name: string,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n if (state.subagents.some((s) => s.id === id)) return state\n const parentId = ancestors[ancestors.length - 1]?.id\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id,\n name,\n task: '',\n ...(parentId ? { parentId } : {}),\n depth: ancestors.length + 1,\n status: 'running',\n ...(stepId ? { stepId } : {}),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** What a `subagent.start` says about its node (everything but the counters). */\nconst startSubagent = (\n state: AgentUiState,\n event: SubagentStart,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n // The envelopes around an event are its ancestry; a start that came bare says it itself\n // (`parentId` is then a subagent only below depth 1 - at depth 1 it is the run's id).\n const depth = Math.max(event.depth ?? 1, ancestors.length + 1)\n const parentId = ancestors[ancestors.length - 1]?.id ?? (depth > 1 ? event.parentId : undefined)\n const told = {\n name: event.name,\n task: event.task,\n depth,\n ...(parentId ? { parentId } : {}),\n ...(event.profile ? { profile: event.profile } : {}),\n ...(event.dynamic ? { dynamic: true as const } : {}),\n ...(event.role ? { role: event.role } : {}),\n ...(event.tools ? { tools: event.tools } : {}),\n }\n // Already there (its events arrived first): the start fills in what they could not say.\n if (state.subagents.some((s) => s.id === event.id)) {\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({ ...s, ...told })),\n }\n }\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n // A nested one belongs to the step that delegated its top-most ancestor.\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id: event.id,\n ...told,\n status: 'running',\n stepId,\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** How long a subagent ran, when both ends were stamped. */\nconst subagentDuration = (s: SubagentView, at?: number): Partial<SubagentView> =>\n at !== undefined && s.startedAt !== undefined ? { durationMs: Math.max(0, at - s.startedAt) } : {}\n\nconst addMedia = (state: AgentUiState, view: MediaView): AgentUiState => ({\n ...state,\n media: [...(state.media ?? []), view],\n ...(view.stepId\n ? {\n steps: patchStep(state.steps, view.stepId, (s) => ({\n ...s,\n media: [...(s.media ?? []), view],\n })),\n }\n : {}),\n})\n\nconst mediaOf = (\n event: Extract<AgentEvent, { type: 'media.generated' }>,\n withStep: boolean,\n): MediaView => ({\n kind: event.kind,\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n model: event.model,\n ...(withStep && event.step ? { stepId: event.step.id } : {}),\n})\n\ntype McpAppEvent = Extract<AgentEvent, { type: 'mcp.app' }>\n\n/**\n * An MCP App joins the run's view, once, and the tool call it came with is tagged. `by` is the\n * subagent the call came through (its step ids are its own: no step then).\n */\nconst addApp = (state: AgentUiState, event: McpAppEvent, by?: AppView['by']): AgentUiState => {\n if (state.apps?.some((a) => a.id === event.id)) return state\n const view: AppView = {\n id: event.id,\n server: event.server,\n tool: event.tool,\n toolName: event.toolName,\n resourceUri: event.resourceUri,\n input: event.input,\n ...(event.result ? { result: event.result } : {}),\n ...(!by && event.step ? { stepId: event.step.id } : {}),\n ...(by ? { by } : {}),\n }\n const steps =\n !by && event.step\n ? patchStep(state.steps, event.step.id, (s) => {\n // The event comes while its call is still running: the newest untagged call of it.\n let i = s.toolCalls.length - 1\n while (i >= 0 && !(s.toolCalls[i].name === event.tool && !s.toolCalls[i].app)) i -= 1\n if (i < 0) return s\n const toolCalls = s.toolCalls.slice()\n toolCalls[i] = { ...toolCalls[i], app: event.id }\n return { ...s, toolCalls }\n })\n : state.steps\n return { ...state, steps, apps: [...(state.apps ?? []), view] }\n}\n\ntype FileWritten = Extract<AgentEvent, { type: 'file.written' }>\n\n/**\n * A file the run wrote: one entry per path (a second write updates it in place), newest size\n * and type. `by` is the subagent it came through; its step ids are its own, so no step then.\n */\nconst fileWritten = (\n state: AgentUiState,\n event: FileWritten,\n by?: WrittenFileView['by'],\n): AgentUiState => {\n const files = state.writtenFiles ?? []\n const i = files.findIndex((f) => f.path === event.path)\n const view: WrittenFileView = {\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n writes: (i >= 0 ? files[i].writes : 0) + 1,\n ...(!by && event.step ? { stepId: event.step.id } : {}),\n ...(by ? { by } : {}),\n }\n return {\n ...state,\n writtenFiles: i >= 0 ? files.map((f, k) => (k === i ? view : f)) : [...files, view],\n }\n}\n\n/** A file deleted later in the run is not one of its files any more. */\nconst fileDeleted = (state: AgentUiState, path: string): AgentUiState =>\n state.writtenFiles?.some((f) => f.path === path)\n ? { ...state, writtenFiles: state.writtenFiles.filter((f) => f.path !== path) }\n : state\n\nconst transcriptOf = (\n event: Extract<AgentEvent, { type: 'media.transcribed' }>,\n): TranscriptView => ({\n source: event.source,\n name: event.name,\n text: event.text,\n ...(event.language ? { language: event.language } : {}),\n ...(event.durationInSeconds !== undefined ? { durationInSeconds: event.durationInSeconds } : {}),\n model: event.model,\n})\n\n/**\n * Fold a `subagent.*` event into the tree. `ancestors` are the subagents it came up through\n * (outermost first): a subagent's own subagents arrive nested,\n * `subagent.event{ A, subagent.event{ G, event } }`, and each level lands on its own node.\n */\nconst applySubagent = (\n state: AgentUiState,\n event: Extract<\n AgentEvent,\n { type: 'subagent.start' | 'subagent.event' | 'subagent.complete' | 'subagent.error' }\n >,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n switch (event.type) {\n case 'subagent.start':\n return startSubagent(state, event, ancestors, ctx)\n\n case 'subagent.event': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n const inner = event.event\n switch (inner.type) {\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(known, inner, [...ancestors, { id: event.id }], ctx)\n\n // A helper the model started asks through the run's own consent gate (the event says\n // which helper): its request is the user's to answer, like the run's. A subagent with\n // a gate of its own (no `subagent` on the event) is its host's business.\n case 'tool.approval-requested': {\n if (!inner.subagent || known.approvals.some((a) => a.id === inner.id)) return known\n const node = known.subagents.find((s) => s.id === inner.subagent!.id)\n return {\n ...known,\n approvals: [\n ...known.approvals,\n {\n id: inner.id,\n name: inner.name,\n input: inner.input,\n readOnly: inner.readOnly,\n // The helper's own step ids mean nothing here: the step that delegated it does.\n stepId: node?.stepId,\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n ...(inner.skill ? { skill: inner.skill } : {}),\n status: 'pending',\n },\n ],\n }\n }\n case 'tool.approval-resolved':\n return known.approvals.some((a) => a.id === inner.id)\n ? {\n ...known,\n approvals: patchApproval(known.approvals, inner.id, (a) =>\n withoutSkillBody({\n ...a,\n status: inner.approved ? 'approved' : 'denied',\n reason: inner.reason,\n automatic: inner.automatic,\n }),\n ),\n }\n : known\n\n // A server asks the user during a subagent's tool call (the connection lets helpers\n // ask): the question is the user's to answer, like the run's own.\n case 'mcp.elicitation-requested': {\n const node = inner.subagent\n ? known.subagents.find((s) => s.id === inner.subagent!.id)\n : undefined\n return addElicitation(known, inner, {\n // The subagent's own step ids mean nothing here: the step that delegated it does.\n stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,\n ...(inner.subagent\n ? {\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n }\n : {}),\n })\n }\n case 'mcp.elicitation-answered':\n return answerElicitation(\n known,\n inner,\n known.subagents.find((s) => s.id === event.id)?.stepId,\n )\n\n // What a subagent generated is in the same workspace: it shows in the turn (its step\n // ids are its own, so it is tied to no step here).\n case 'media.generated':\n return addMedia(known, mediaOf(inner, false))\n case 'media.transcribed':\n return { ...known, transcripts: [...(known.transcripts ?? []), transcriptOf(inner)] }\n\n // A subagent works in the same workspace: what it wrote belongs to the turn, and says\n // who wrote it.\n case 'file.written': {\n const node = known.subagents.find((s) => s.id === event.id)\n return fileWritten(known, inner, {\n id: event.id,\n name: node?.name ?? event.name,\n ...(node?.role ? { role: node.role } : {}),\n })\n }\n case 'file.deleted':\n return fileDeleted(known, inner.path)\n // An app a subagent's call came with is shown in the turn too, and says whose call it was.\n case 'mcp.app': {\n const node = known.subagents.find((s) => s.id === event.id)\n return addApp(known, inner, {\n id: event.id,\n name: node?.name ?? event.name,\n ...(node?.role ? { role: node.role } : {}),\n })\n }\n\n default:\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) =>\n applySubagentEvent(s, inner),\n ),\n }\n }\n }\n\n case 'subagent.complete': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: 'done',\n activity: 'done',\n text: event.text,\n usage: event.usage,\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n\n case 'subagent.error': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: event.stopped ? 'stopped' : 'error',\n activity: event.stopped ? 'stopped' : 'failed',\n error: event.error,\n // A helper says what it had spent when it ended; a static subagent does not.\n ...(event.usage ? { usage: event.usage } : {}),\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n }\n}\n\n/**\n * The flat `subagents` list as a tree: each node with the subagents it started, in the order\n * they started. A node whose parent is not in the list (its start was never seen) is a root.\n */\nexport const subagentTree = (subagents: SubagentView[]): SubagentNode[] => {\n const nodes = new Map<string, SubagentNode>()\n for (const s of subagents) nodes.set(s.id, { ...s, children: [] })\n // A parent chain that comes back to the node is not a tree: such a node is a root.\n const loops = (node: SubagentNode): boolean => {\n let up = node.parentId\n for (let i = 0; up !== undefined && i <= nodes.size; i++) {\n if (up === node.id) return true\n up = nodes.get(up)?.parentId\n }\n return false\n }\n const roots: SubagentNode[] = []\n for (const node of nodes.values()) {\n const parent =\n node.parentId !== undefined && !loops(node) ? nodes.get(node.parentId) : undefined\n if (parent) parent.children.push(node)\n else roots.push(node)\n }\n return roots\n}\n\n/** Finalize the trailing pending assistant message with the given content. */\nconst finalizeAssistant = (\n messages: ChatMessage[],\n content: string,\n extra: Partial<ChatMessage> = {},\n): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content: content || m.content, pending: false, ...extra }\n return next\n }\n }\n return messages\n}\n\n/** Duration of the current run at `at`, when both ends are known. */\nconst runDuration = (state: AgentUiState, at?: number): Partial<ChatMessage> =>\n at !== undefined && state.runStartedAt !== undefined\n ? { durationMs: Math.max(0, at - state.runStartedAt) }\n : {}\n\n/** Update the trailing pending assistant message's streaming content. */\nconst streamAssistant = (messages: ChatMessage[], content: string): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content }\n return next\n }\n }\n return messages\n}\n\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 // Only with `config.executorTiers`: without it the view is what it always was.\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tierReason !== undefined ? { tierReason: event.tierReason } : {}),\n }\n return { ...state, steps: [...state.steps, view] }\n }\n\n case 'step.escalated':\n // The attempt on `from` is over and the step CONTINUES on `to`. What the failed attempt\n // wrote is not the next attempt's text: it moves onto the escalation. Its tool calls\n // happened (the core keeps them in the step's result and shows them to the stronger\n // model), so they stay, marked with the attempt they belong to.\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n const attempt = (s.escalations?.length ?? 0) + 1\n return {\n ...s,\n tier: event.to,\n ...(event.model ? { model: event.model } : {}),\n text: '',\n reasoning: '',\n toolCalls: s.toolCalls.map((c) => (c.attempt === undefined ? { ...c, attempt } : c)),\n escalations: [\n ...(s.escalations ?? []),\n {\n from: event.from,\n to: event.to,\n reason: event.reason,\n ...(event.model ? { model: event.model } : {}),\n ...(s.text.trim() ? { text: s.text } : {}),\n },\n ],\n }\n }),\n }\n\n case 'step.reasoning-delta':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n reasoning: s.reasoning + event.delta,\n })),\n }\n\n case 'step.text-delta':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({ ...s, text: s.text + event.delta })),\n }\n\n case 'step.tool-call': {\n // An app can be told before its call is (the tool runs while the stream is read): the\n // call then takes the app of this step and tool that no call has yet.\n const tagged = new Set(\n state.steps.flatMap((s) => s.toolCalls.map((c) => c.app).filter(Boolean)),\n )\n const early = state.apps?.find(\n (a) => a.stepId === event.step.id && a.tool === event.name && !tagged.has(a.id),\n )\n const call: ToolCallView = {\n name: event.name,\n input: event.input,\n status: 'calling',\n inputTokens: approxTokens(event.input),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n ...(early ? { app: early.id } : {}),\n }\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n toolCalls: [...s.toolCalls, call],\n })),\n }\n }\n\n case 'step.tool-result':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n // Match the last still-calling entry for this tool name.\n let done = false\n const toolCalls = s.toolCalls\n .slice()\n .reverse()\n .map((c) => {\n if (!done && c.status === 'calling' && c.name === event.name) {\n done = true\n return {\n ...c,\n output: event.output,\n ok: event.ok,\n status: 'done' as const,\n outputTokens: approxTokens(event.output),\n ...(isReplayedToolOutput(event.output) ? { replayed: true } : {}),\n ...(ctx.at !== undefined && c.startedAt !== undefined\n ? { durationMs: Math.max(0, ctx.at - c.startedAt) }\n : {}),\n }\n }\n return c\n })\n .reverse()\n return { ...s, toolCalls }\n }),\n }\n\n case 'step.complete':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n status: 'done',\n summary: event.result.summary,\n // With tiers: where the step finished and how it got there. The result's list is the\n // authority; an escalation seen live keeps what only the event told (model, text).\n ...(event.result.tier !== undefined ? { tier: event.result.tier } : {}),\n ...(event.result.model !== undefined ? { model: event.result.model } : {}),\n ...(event.result.escalations?.length\n ? {\n escalations: event.result.escalations.map((e, i) => {\n const live = s.escalations?.[i]\n return live && live.from === e.from && live.to === e.to\n ? { ...live, reason: e.reason }\n : { from: e.from, to: e.to, reason: e.reason }\n }),\n }\n : {}),\n blocked: event.result.blocked,\n // The result carries the authoritative, ordered tool-call list; keep\n // the timing the streamed calls measured (matched in order per name).\n toolCalls: (() => {\n const seen = new Map<string, number>()\n return event.result.toolCalls.map((c) => {\n const nth = seen.get(c.name) ?? 0\n seen.set(c.name, nth + 1)\n const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth]\n return {\n name: c.name,\n input: c.input,\n output: c.output,\n ok: c.ok,\n status: 'done' as const,\n inputTokens: approxTokens(c.input),\n outputTokens: approxTokens(c.output),\n ...(streamed?.startedAt !== undefined ? { startedAt: streamed.startedAt } : {}),\n ...(streamed?.durationMs !== undefined ? { durationMs: streamed.durationMs } : {}),\n // With tiers the list holds every attempt's calls, in the order they were made.\n ...(streamed?.attempt !== undefined ? { attempt: streamed.attempt } : {}),\n ...(isReplayedToolOutput(c.output) ? { replayed: true } : {}),\n // The MCP App the call came with (only the stream told it).\n ...(streamed?.app !== undefined ? { app: streamed.app } : {}),\n }\n })\n })(),\n })),\n }\n\n case 'replan.decision': {\n if (!event.failed) {\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n },\n }\n }\n // The replanner could not decide: `continue` is the fallback and the run goes on. The\n // failure itself came as the `error` event (phase 'replan') just before; it is pinned to\n // the step the replanner ran after, so the warning stays in that turn's activity.\n const error = state.replan?.failed ? state.replan.error : undefined\n const last = state.steps[state.steps.length - 1]\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n failed: true,\n ...(error ? { error } : {}),\n },\n steps: last\n ? patchStep(state.steps, last.id, (s) => ({\n ...s,\n replanFailed: error ?? event.reason,\n }))\n : state.steps,\n }\n }\n\n case 'decision': {\n // The decision model is asked after a step (continue / finish): the note belongs to it.\n const view: DecisionView = {\n point: event.point,\n accepted: event.accepted,\n ...(event.choice !== undefined ? { choice: event.choice } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n threshold: event.threshold,\n ...(event.reason ? { reason: event.reason } : {}),\n durationMs: event.durationMs,\n ...(event.model ? { model: event.model } : {}),\n }\n const last = state.steps[state.steps.length - 1]\n return last\n ? {\n ...state,\n steps: patchStep(state.steps, last.id, (s) => ({\n ...s,\n decisions: [...(s.decisions ?? []), view],\n })),\n }\n : { ...state, decisions: [...(state.decisions ?? []), view] }\n }\n\n case 'media.generated':\n return addMedia(state, mediaOf(event, true))\n\n case 'media.transcribed':\n return { ...state, transcripts: [...(state.transcripts ?? []), transcriptOf(event)] }\n\n case 'file.written':\n return fileWritten(state, event)\n\n case 'file.deleted':\n return fileDeleted(state, event.path)\n\n case 'mcp.app':\n return addApp(state, event)\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 // An app's sampling is no run's: it counts in the conversation's total only, never in a\n // run's usage (nor, through it, on an answer).\n if (event.phase === 'app') {\n return { ...state, totalUsage: addUsage(state.totalUsage, event.usage) }\n }\n return {\n ...state,\n usage: addUsage(state.usage, event.usage),\n totalUsage: addUsage(state.totalUsage, event.usage),\n }\n\n case 'mcp.elicitation-requested':\n return addElicitation(state, event, {\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n })\n\n case 'mcp.elicitation-answered':\n return answerElicitation(state, event, runningStepId(state.steps))\n\n case 'tool.approval-requested':\n return {\n ...state,\n approvals: [\n ...state.approvals,\n {\n id: event.id,\n name: event.name,\n input: event.input,\n readOnly: event.readOnly,\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n ...(event.app ? { app: event.app } : {}),\n ...(event.skill ? { skill: event.skill } : {}),\n status: 'pending',\n },\n ],\n }\n\n case 'tool.approval-resolved': {\n const known = state.approvals.some((a) => a.id === event.id)\n const decided = (a: ApprovalView): ApprovalView =>\n withoutSkillBody({\n ...a,\n status: event.approved ? 'approved' : 'denied',\n reason: event.reason,\n automatic: event.automatic,\n })\n return {\n ...state,\n approvals: known\n ? patchApproval(state.approvals, event.id, decided)\n : // A policy denial arrives without a request: record it too.\n [\n ...state.approvals,\n decided({\n id: event.id,\n name: event.name,\n input: undefined,\n readOnly: false,\n stepId: runningStepId(state.steps),\n status: 'pending',\n }),\n ],\n }\n }\n\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(state, event, [], ctx)\n\n case 'skill.activated':\n return state.skills.includes(event.name)\n ? state\n : { ...state, skills: [...state.skills, event.name] }\n\n case 'skill.learned': {\n const before = state.learned.find((l) => l.name === event.name)\n const lesson: LessonView = {\n name: event.name,\n description: event.description,\n // A rewrite of a lesson we know goes up one; a lesson we never saw (an event for a store\n // loaded before this view existed) starts at 2 when the core says it is an update.\n revision: event.update ? (before?.revision ?? 1) + 1 : 1,\n chars: event.chars,\n sources: event.sources,\n }\n return {\n ...state,\n learned: before\n ? state.learned.map((l) => (l.name === event.name ? lesson : l))\n : [...state.learned, lesson],\n learnedNow: state.learnedNow.includes(event.name)\n ? state.learnedNow\n : [...state.learnedNow, event.name],\n }\n }\n\n case 'skill.forgotten':\n return { ...state, learned: state.learned.filter((l) => l.name !== event.name) }\n\n case 'egress.request':\n return {\n ...state,\n fetches: [\n ...state.fetches,\n {\n url: event.url,\n allowed: event.allowed,\n ...(event.status !== undefined ? { status: event.status } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n },\n ],\n }\n\n case 'tools.discovered':\n return {\n ...state,\n discoveredTools: [...new Set([...state.discoveredTools, ...event.names])],\n }\n\n case 'context.compacted':\n return {\n ...state,\n compactions: [\n ...state.compactions,\n { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens },\n ],\n }\n\n case 'budget.exceeded':\n return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } }\n\n case 'stopped':\n return {\n ...state,\n stopped: true,\n // Nothing of the run is waiting any more once it has stopped (an app's request is not\n // the run's).\n approvals: state.approvals.map((a) =>\n a.status === 'pending' && !a.app\n ? withoutSkillBody({ ...a, status: 'denied' as const, reason: 'stopped' })\n : a,\n ),\n ...(state.elicitations\n ? {\n elicitations: state.elicitations.map((e) =>\n e.status === 'pending'\n ? { ...e, status: 'cancelled' as const, automatic: true, reason: 'stopped' }\n : e,\n ),\n }\n : {}),\n 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 // A replanner that failed is not an error of the run at all: the run continues with its\n // plan. It is held for the `replan.decision { failed }` that follows, never in `error`.\n if (event.phase === 'replan') {\n return {\n ...state,\n replan: { mode: 'continue', reason: '', failed: true, error: event.error },\n }\n }\n return event.phase === 'run'\n ? {\n ...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 // An app's requests are not the run's decisions: they are never kept on its message.\n const decided = state.approvals.filter((a) => a.status !== 'pending' && !a.app)\n const patch: Partial<ChatMessage> = {}\n if (m.steps !== state.steps) patch.steps = state.steps\n if (m.subagents !== state.subagents) patch.subagents = state.subagents\n if (state.notes.length > 0 && m.notes !== state.notes) patch.notes = state.notes\n if (m.usage !== state.usage) patch.usage = state.usage\n if ((m.reasoning ?? '') !== state.finalReasoning) patch.reasoning = state.finalReasoning\n if (m.skills !== state.skills) patch.skills = state.skills\n if (state.learnedNow.length > 0 && m.learned !== state.learnedNow)\n patch.learned = state.learnedNow\n if (state.fetches.length > 0 && m.fetches !== state.fetches) patch.fetches = state.fetches\n if (state.media && m.media !== state.media) patch.media = state.media\n if (state.transcripts && m.transcripts !== state.transcripts)\n patch.transcripts = state.transcripts\n if (state.writtenFiles && m.writtenFiles !== state.writtenFiles)\n patch.writtenFiles = state.writtenFiles\n if (state.apps && m.apps !== state.apps) patch.apps = state.apps\n if (\n (m.approvals?.length ?? 0) !== decided.length ||\n decided.some((a, k) => m.approvals?.[k] !== a)\n ) {\n patch.approvals = decided\n }\n if (Object.keys(patch).length === 0) return state\n const messages = state.messages.slice()\n messages[i] = { ...m, ...patch }\n return { ...state, messages }\n}\n\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 {\n DecisionFallbackReason,\n EscalationReason,\n ModelTier,\n TierReason,\n ToolApprovalMode,\n} from '@dudko.dev/agent-web'\nimport { defaultNoticeTexts, type NoticeTexts } from './composer.js'\nimport type { ElicitationIssueKind, ElicitationOutcomeReason } from './elicitation.js'\nimport type { FileKind } from './file-kinds.js'\nimport type { McpAppSandboxReason } from './mcp-app.js'\nimport type { 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 // ── model tiers and escalation ─────────────────────────────────────────────\n /** The tier badge on a step. */\n tierNames: Record<ModelTier, string>\n /** The badge's tooltip: why the step started on its tier. */\n tierReasons: Record<TierReason, string>\n /** Why a step was retried on a stronger model. */\n escalationReasons: Record<EscalationReason, string>\n /** \"Escalated: light → strong (reported a blocker)\" - the names and the reason are already labels. */\n escalated: (from: string, to: string, reason: string) => string\n /** Opens what the failed attempt had written. */\n escalatedAttemptText: string\n /** \"1 escalation\" in the activity summary. */\n escalations: (n: number) => string\n /** On a tool call made by an attempt that was escalated. */\n attemptTag: (n: number) => string\n /** On a write the core did not run a second time (it succeeded in an earlier attempt). */\n replayed: string\n replayedTitle: string\n /** The replanner call failed; the run went on with the plan it had. */\n replanFailed: string\n\n // ── the subagent tree ──────────────────────────────────────────────────────\n /** The tag on a helper the model started itself (`spawn_subagent`). */\n subagentHelper: string\n /** A node's status, in words. */\n subagentStatus: Record<'running' | 'done' | 'error' | 'stopped', string>\n /** \"12k tokens\" - what was spent under a node; the number is already formatted. */\n subagentTokens: (tokens: string) => string\n /** \"tools: fs_read, web_fetch\" - what a helper was given. */\n subagentTools: (names: string) => string\n /** A helper that was given no tools at all (it only reasons). */\n subagentNoTools: string\n /** The consent prompt of a helper's call: `role` is what the model wrote for it, if anything. */\n approvalLeadHelper: (role: string | undefined, depth: number) => string\n\n // ── generated media and transcripts ────────────────────────────────────────\n /** Alt text of a generated image; `path` is where it is in the workspace. */\n mediaImage: (path: string) => string\n /** The accessible name of a generated audio player. */\n mediaAudio: (path: string) => string\n /** A generated file that cannot be shown here (no workspace, the file is gone, an unknown type). */\n mediaFile: (path: string) => string\n /** The summary of a transcript block. */\n transcriptOf: (name: string) => string\n /** Says whose words a transcript is: the content of the user's file, not the agent's. */\n transcriptNote: string\n\n // ── files written in a turn ────────────────────────────────────────────────\n /** Above the chips: \"3 files written in this turn\". */\n filesWritten: (n: number) => string\n /** In the activity summary: \"3 files\". */\n filesCount: (n: number) => string\n /** The link that opens the Files panel. */\n showInFiles: string\n /** What a file is, on its chip. */\n fileKinds: Record<FileKind, string>\n /** The open button of a chip (accessible name); `name` is the file's name. */\n fileOpen: (name: string) => string\n /** The same button while the preview is open. */\n fileClose: (name: string) => string\n /** The download button of a chip (accessible name). */\n fileDownload: (name: string) => string\n /** On a chip: the subagent that wrote the file. */\n fileBy: (name: string) => string\n /** On a chip whose file is not in the workspace any more. */\n fileGone: string\n /** In the preview of a file that cannot be shown as text or as an image. */\n fileNoPreview: string\n /** Under a preview that shows only the first `chars` characters. */\n fileCut: (chars: number) => string\n /** Unfold / fold a long text preview. */\n fileShowRest: string\n fileShowLess: string\n /** The two views of a text file the host can render (Markdown). */\n fileRendered: string\n fileSource: string\n closePreview: string\n /** Under a source view: \"64 lines\". */\n fileLines: (n: number) => string\n\n // ── HTML preview (the sandboxed frame) ─────────────────────────────────────\n /** The host's label on the frame of an HTML file. */\n htmlFrameTitle: string\n /** The two badges under it, while the page is shown. */\n htmlSandboxed: string\n htmlNoNetwork: string\n /** In their place, while the source is shown. */\n htmlSourceNote: string\n /** In the frame's footer. */\n htmlScripts: (on: boolean) => string\n /** The files the page links to that the preview does not load. */\n htmlLinkedFiles: (names: string) => string\n /** A page too large to frame. */\n htmlTooLarge: string\n /** The button that makes the frame taller / back. */\n htmlTaller: string\n htmlShorter: string\n /** The accessible name of the frame itself. */\n htmlFrameName: (path: string) => string\n\n // ── usage: calls that are not tokens ───────────────────────────────────────\n usageMedia: (n: number) => string\n usageDecisions: (n: number) => string\n\n // ── decision model ─────────────────────────────────────────────────────────\n /** \"decision model: continue (0.93)\" - its answer was used; the probability is formatted. */\n decisionAccepted: (choice: string, confidence: string) => string\n /** \"decision model fell back: low confidence (0.41 < 0.8)\" - the ordinary model call ran. */\n decisionFellBack: (reason: string, detail: string) => string\n decisionReasons: Record<DecisionFallbackReason, string>\n\n // ── web search results ─────────────────────────────────────────────────────\n /** Before the query of a `web_search` call. */\n searchQuery: string\n searchNoResults: string\n /** Results left out by the egress policy. */\n searchFiltered: (n: number) => string\n /** The list was cut to the cap. */\n searchTruncated: string\n\n // ── a question from an MCP server (elicitation) ────────────────────────────\n /** The accessible name of the prompt. */\n elicitationTitle: string\n /** The host's own line: which server asks. */\n elicitationLead: (server: string) => string\n /** The same when the call that asks is a helper's; `role` is what the model wrote for it. */\n elicitationLeadHelper: (server: string, role: string | undefined) => string\n /** Before the tool's name: \"during\". */\n elicitationDuring: string\n /** \"1 of 3\" - several questions are waiting. */\n elicitationCount: (index: number, total: number) => string\n /** The caption over the server's own words. */\n elicitationFrom: (server: string) => string\n /** The meaning of the mark on a required field. */\n elicitationRequired: string\n /** The empty choice of a select. */\n elicitationChoose: string\n elicitationSubmit: string\n elicitationDecline: string\n elicitationCancel: string\n /** Why a field's value does not fit; `field` is its label, `limit` the rule's number. */\n elicitationErrors: Record<ElicitationIssueKind, (field: string, limit?: number) => string>\n /** Over the buttons, after a submit that was refused. */\n elicitationFix: (n: number) => string\n /** The host's line of a link request; the host name follows. */\n elicitationUrlLead: (server: string) => string\n /** The caption over the whole address. */\n elicitationUrlFull: string\n elicitationOpen: string\n /** After the link was opened. */\n elicitationOpened: string\n /** \"I have finished there\" - the accept of a link request. */\n elicitationUrlDone: string\n /** A link that will not be opened from here. */\n elicitationUrlRefused: string\n /** \"Expires in 4:05\". */\n elicitationExpiresIn: (time: string) => string\n /** The same note when the time left is not known. */\n elicitationExpires: string\n /** A question nobody answered: the server, and why (one of `elicitationReasons`). */\n elicitationAutomatic: (server: string, reason: string) => string\n /** Why a question was answered without anybody deciding, by the core's reason (+ `stopped`). */\n elicitationReasons: Record<ElicitationOutcomeReason, string>\n elicitationDismiss: string\n\n // ── MCP Apps (an app a server's tool came with) ────────────────────────────\n /** The host's label on an app's frame: \"App from server “travel”\". */\n appFrom: (server: string) => string\n /** The badge beside it. */\n appSandboxed: string\n /** The badge when the app runs on an origin of its own (the sandbox page answered). */\n appSandboxedOrigin: string\n /** The note (menu, badge title) for that: the sandbox origin. */\n appSandboxOrigin: (origin: string) => string\n /** A sandbox URL is set, and the app runs in the opaque frame all the same: why. */\n appSandboxFallback: (reason: string) => string\n /** The reasons, by `McpAppSandboxReason`. */\n appSandboxReasons: Record<McpAppSandboxReason, string>\n /** The app loaded its sandbox page again (navigated it) and was stopped. */\n appSandboxBroken: string\n /** The badge while a request of the app waits for the user. */\n appWaiting: string\n /** The tag on the tool call an app came with, and the activity summary's count. */\n appTag: string\n appsCount: (n: number) => string\n appLoading: string\n /** The app could not be read or is refused (`reason` is the core's message). */\n appFailed: (reason: string) => string\n /** No connection to its server (not connected any more, or apps are off). */\n appUnavailable: (server: string) => string\n /** The folded line: \"App from server “travel” · hidden [Show]\". */\n appHidden: string\n appShow: string\n /** The app's menu and what is in it. */\n appMenu: string\n appReload: string\n appOpenPanel: string\n appHide: string\n /** The note at the bottom of the menu. */\n appServedBy: (server: string, uri: string) => string\n /** The line left in the transcript while the app is in the panel, and its button. */\n appInPanel: string\n appBringBack: string\n appClosePanel: string\n /** The panel's footer. */\n appPanelNote: (server: string) => string\n /** The accessible name of the app's frame. */\n appFrameName: (server: string) => string\n /** Under the frame: the tools the app called, and the ones that were refused. */\n appRan: (names: string) => string\n appRefused: string\n /** A tool call the app asks for (`<ToolApprovalPrompt>`): the lead and the note. */\n approvalLeadApp: (server: string) => string\n approvalFromApp: (server: string, readOnly: boolean) => string\n /** A link the app asks to open (`<AppRequestPrompt>`). */\n appLinkLead: (server: string) => string\n appLinkNote: string\n appLinkOpen: string\n appCancel: string\n /** A message the app asks to put in the chat. */\n appMessageLead: (server: string) => string\n appMessageNote: string\n appMessageAccept: string\n appMessageDiscard: string\n /** The app shown full screen (`<McpAppFrame allowFullscreen>`): the badge, the way back. */\n appFullscreenBadge: string\n appFullscreenExit: string\n /** The key that exits too, shown on the button. */\n appFullscreenKey: string\n /** A file the app asks to save (`<AppRequestPrompt>`). */\n appDownloadLead: (server: string) => string\n /** Name · type · size. */\n appDownloadType: (mimeType: string | undefined) => string\n appDownloadSize: (bytes: number) => string\n /** Where the bytes came from: the request itself, or read from the app's server. */\n appDownloadSource: (source: 'embedded' | 'link', server: string) => string\n appDownloadNote: string\n appDownloadSave: string\n /** The app asks the agent's model for an answer (`sampling/createMessage`). */\n appSamplingLead: (server: string) => string\n appSamplingSystem: string\n appSamplingRole: (role: 'user' | 'assistant') => string\n appSamplingImages: (count: number) => string\n appSamplingTokens: (tokens: number, asked: number) => string\n appSamplingNote: string\n appSamplingAllow: string\n appSamplingAlways: string\n appSamplingDeny: string\n /**\n * An MCP server's skill about to enter the model's context (`<ToolApprovalPrompt>`, a request\n * with `approval.skill`): the lead, its size and files, how it was found, the body preview.\n */\n skillConsentLead: (server: string, skill: string) => string\n /** The size of its SKILL.md, and how many more files it bundles. */\n skillConsentSize: (bytes: number, files: number) => string\n /** It was named by its address (`skills/get`), not in the server's list. */\n skillConsentByUri: string\n /** It sits inside another skill of the same server. */\n skillConsentNested: (enclosing: string) => string\n /**\n * A generated skill (`skill.dynamic`): the server publishes no checksums - the person approves\n * the copy the agent just read, and only that copy is used.\n */\n skillConsentDynamic: string\n /** (with `skillConsentDynamic`) The server cannot list the skill's files: SKILL.md alone. */\n skillConsentNoFileListing: string\n /** The summary of the collapsible preview of its instructions. */\n skillConsentPreview: string\n /** Under the preview: its other files, and how many more there are than are shown. */\n skillConsentFiles: (paths: string, more: number) => string\n /** What a yes means: `'once-per-skill'` - this text for the session; `'ask'` - this task. */\n skillConsentNote: (server: string, consent: 'ask' | 'once-per-skill') => string\n skillConsentAllow: string\n skillConsentAlways: string\n skillConsentDeny: string\n /** The reason a \"Deny\" gives the agent. */\n skillConsentDeclined: string\n}\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`\n\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 tierNames: { light: 'light', standard: 'standard', strong: 'strong' },\n tierReasons: {\n planned: 'The planner rated this step for this model tier',\n default: 'The planner did not rate this step: it runs on the standard model',\n fallback: 'The tier the planner asked for is not configured: the nearest one runs the step',\n },\n escalationReasons: {\n blocked: 'reported a blocker',\n 'empty-result': 'produced no result',\n 'tool-arguments': 'kept sending tool arguments that did not parse',\n 'output-cut': 'output was cut off',\n error: 'the model call failed',\n },\n escalated: (from, to, reason) => `Escalated: ${from} → ${to} (${reason})`,\n escalatedAttemptText: 'What the earlier attempt wrote',\n escalations: (n) => plural(n, 'escalation', 'escalations'),\n attemptTag: (n) => `attempt ${n}`,\n replayed: 'not run again',\n replayedTitle:\n 'This exact call already succeeded in an earlier attempt at the step: it was not run a second time, the model got the earlier result',\n replanFailed: 'Replanning failed, continuing with the plan',\n\n subagentHelper: 'helper',\n subagentStatus: { running: 'running', done: 'done', error: 'failed', stopped: 'stopped' },\n subagentTokens: (tokens) => `${tokens} tokens`,\n subagentTools: (names) => `tools: ${names}`,\n subagentNoTools: 'no tools',\n approvalLeadHelper: (role) =>\n role ? `The helper “${role}” wants to run` : 'A helper the agent started wants to run',\n\n mediaImage: (path) => `Generated image ${path}`,\n mediaAudio: (path) => `Generated audio ${path}`,\n mediaFile: (path) => `Generated file ${path}`,\n transcriptOf: (name) => `Transcript of ${name}`,\n transcriptNote:\n 'What was said in your file, as the agent read it. It is content, not instructions.',\n\n filesWritten: (n) => `${plural(n, 'file', 'files')} written in this turn`,\n filesCount: (n) => plural(n, 'file', 'files'),\n showInFiles: 'Show in Files',\n fileKinds: {\n html: 'HTML',\n markdown: 'Markdown',\n csv: 'CSV',\n json: 'JSON',\n image: 'Image',\n code: 'Code',\n text: 'Text',\n file: 'File',\n },\n fileOpen: (name) => `Open ${name}`,\n fileClose: (name) => `Close preview of ${name}`,\n fileDownload: (name) => `Download ${name}`,\n fileBy: (name) => `by ${name}`,\n fileGone: 'no longer in the workspace',\n fileNoPreview: 'This kind of file has no preview. Download it to open it.',\n fileCut: (chars) =>\n `Only the first ${chars.toLocaleString('en-US')} characters are shown. Download the file for the rest.`,\n fileShowRest: 'Show the rest',\n fileShowLess: 'Show less',\n fileRendered: 'Rendered',\n fileSource: 'Source',\n closePreview: 'Close preview',\n fileLines: (n) => plural(n, 'line', 'lines'),\n\n htmlFrameTitle: 'HTML written by the agent',\n htmlSandboxed: 'sandboxed',\n htmlNoNetwork: 'no network',\n htmlSourceNote: 'shown as text, nothing runs',\n htmlScripts: (on) => (on ? 'scripts on' : 'scripts off'),\n htmlLinkedFiles: (names) => `linked files are not loaded: ${names}`,\n htmlTooLarge: 'This page is too large to preview. It is shown as source.',\n htmlTaller: 'Make the preview taller',\n htmlShorter: 'Make the preview shorter',\n htmlFrameName: (path) => `Preview of ${path}`,\n\n usageMedia: (n) => plural(n, 'media call', 'media calls'),\n usageDecisions: (n) => plural(n, 'decision call', 'decision calls'),\n\n decisionAccepted: (choice, confidence) => `decision model: ${choice} (${confidence})`,\n decisionFellBack: (reason, detail) =>\n `decision model fell back: ${reason}${detail ? ` (${detail})` : ''}`,\n decisionReasons: {\n 'low-confidence': 'low confidence',\n 'invalid-choice': 'an answer that is not an option',\n 'invalid-confidence': 'a confidence that is not a probability',\n error: 'the call failed',\n timeout: 'timed out',\n 'needs-model': 'the choice needs the model',\n },\n\n searchQuery: 'Searched the web for',\n searchNoResults: 'no results',\n searchFiltered: (n) => `${n} left out by the web access policy`,\n searchTruncated: 'list cut short',\n\n elicitationTitle: 'A question from an MCP server',\n elicitationLead: (server) => `The MCP server “${server}” asks for your input`,\n elicitationLeadHelper: (server, role) =>\n role\n ? `The MCP server “${server}” asks for your input (a call by the helper “${role}”)`\n : `The MCP server “${server}” asks for your input (a call by a helper)`,\n elicitationDuring: 'during',\n elicitationCount: (index, total) => `${index} of ${total}`,\n elicitationFrom: (server) => `From the server “${server}”`,\n elicitationRequired: 'required',\n elicitationChoose: 'Choose…',\n elicitationSubmit: 'Submit',\n elicitationDecline: 'Decline',\n elicitationCancel: 'Cancel',\n elicitationErrors: {\n required: (field) => `${field} is required.`,\n tooShort: (field, limit) => `${field} must be at least ${limit} characters.`,\n tooLong: (field, limit) => `${field} must be at most ${limit} characters.`,\n email: (field) => `${field} must be an email address.`,\n uri: (field) => `${field} must be a full address, such as https://example.com.`,\n date: (field) => `${field} must be a date.`,\n dateTime: (field) => `${field} must be a date and a time.`,\n notNumber: (field) => `${field} must be a number.`,\n notInteger: (field) => `${field} must be a whole number.`,\n belowMinimum: (field, limit) => `${field} must be ${limit} or more.`,\n aboveMaximum: (field, limit) => `${field} must be ${limit} or less.`,\n notAnOption: (field) => `${field} must be one of the options.`,\n tooFew: (field, limit) => `${field}: choose at least ${limit}.`,\n tooMany: (field, limit) => `${field}: choose at most ${limit}.`,\n },\n elicitationFix: (n) => `${plural(n, 'field needs', 'fields need')} a correction.`,\n elicitationUrlLead: (server) => `The MCP server “${server}” asks you to open a page on`,\n elicitationUrlFull: 'Full address',\n elicitationOpen: 'Open in a new tab',\n elicitationOpened: 'Opened in a new tab. Finish there, then confirm here.',\n elicitationUrlDone: 'I have finished there',\n elicitationUrlRefused:\n 'This link is not a secure (https) address, so it is not opened from here.',\n elicitationExpiresIn: (time) => `Cancelled automatically in ${time}`,\n elicitationExpires: 'Cancelled automatically if it is left unanswered',\n elicitationAutomatic: (server, reason) =>\n `A question from the MCP server “${server}” was answered automatically, and its tool call did not finish: ${reason}.`,\n elicitationReasons: {\n timeout: 'nobody answered in time',\n 'step-timeout': 'the step ran out of time while the question was waiting',\n aborted: 'the run was stopped',\n stopped: 'the run was stopped',\n 'cap-per-call': 'the tool call had already asked too many questions',\n 'cap-per-run': 'too many questions had already been asked in this run',\n 'unsupported-schema': 'the form it sent cannot be shown',\n 'unsupported-mode': 'it asked in a way this app does not offer',\n 'insecure-url': 'the link it sent was refused',\n 'invalid-request': 'its request was malformed',\n subagent: 'a helper is not allowed to ask you',\n 'handler-error': 'the question could not be shown',\n 'invalid-answer': 'the answer did not fit the form and was not sent',\n 'after-failure': 'an earlier question of the same call had already failed',\n 'no-tool-call': 'no tool call was in progress',\n },\n elicitationDismiss: 'Dismiss',\n\n appFrom: (server) => `App from server “${server}”`,\n appSandboxed: 'sandboxed',\n appSandboxedOrigin: 'sandboxed on its own origin',\n appSandboxOrigin: (origin) =>\n `Runs on its own origin, ${origin}: its storage is its own, never this page's.`,\n appSandboxFallback: (reason) =>\n `Not on an origin of its own (${reason}): it runs in an opaque sandbox, with no storage of its own.`,\n appSandboxReasons: {\n invalid: 'the sandbox URL is not valid',\n insecure: 'the sandbox URL is not https',\n 'same-origin': \"the sandbox URL is on this page's origin\",\n 'no-page-origin': 'this page has no origin of its own',\n 'server-name': \"the server's name is not a DNS label\",\n 'too-many-origins': 'it declares too many origins',\n 'no-answer': 'the sandbox page did not answer',\n },\n appSandboxBroken: 'The app reloaded its frame, so it was stopped. Reload it to start again.',\n appWaiting: 'waiting for you',\n appTag: 'app',\n appsCount: (n) => plural(n, 'app', 'apps'),\n appLoading: 'Loading the app…',\n appFailed: (reason) => `The app could not be shown: ${reason}`,\n appUnavailable: (server) =>\n `The server “${server}” is not connected, so its app cannot be shown.`,\n appHidden: 'hidden',\n appShow: 'Show',\n appMenu: 'App menu',\n appReload: 'Reload app',\n appOpenPanel: 'Open in panel',\n appHide: 'Hide app',\n appServedBy: (server, uri) =>\n `Served by ${server} as ${uri}. It cannot read this chat, your keys or your files.`,\n appInPanel: 'open in the panel',\n appBringBack: 'Bring back',\n appClosePanel: 'Close the panel',\n appPanelNote: (server) =>\n `Content from the server “${server}”. It cannot read this chat, your keys or your files.`,\n appFrameName: (server) => `App from server ${server}`,\n appRan: (names) => `The app ran ${names}`,\n appRefused: 'refused',\n approvalLeadApp: (server) => `The app “${server}” wants to run`,\n approvalFromApp: (server, readOnly) =>\n `Asked by the app, not by the agent. This tool ${readOnly ? 'only reads' : 'changes'} data on the server “${server}”.`,\n appLinkLead: (server) => `The app “${server}” wants to open a link. Open it?`,\n appLinkNote: 'Opens in a new tab, outside this chat. Check the site name before you continue.',\n appLinkOpen: 'Open',\n appCancel: 'Cancel',\n appMessageLead: (server) => `The app “${server}” wants to put a message in your message box`,\n appMessageNote:\n 'Nothing is sent until you send it yourself, and you can change it first. It is the app’s text, not yours.',\n appMessageAccept: 'Put in the message box',\n appMessageDiscard: 'Discard',\n appFullscreenBadge: 'full screen',\n appFullscreenExit: 'Exit full screen',\n appFullscreenKey: 'Esc',\n appDownloadLead: (server) => `The app “${server}” wants to save a file to your device`,\n appDownloadType: (mimeType) => mimeType ?? 'type not given',\n appDownloadSize: kb,\n appDownloadSource: (source, server) =>\n source === 'link'\n ? `Read from the server “${server}” for the app.`\n : 'Made by the app inside its frame.',\n appDownloadNote:\n 'This page saves it, not the app. Programs, scripts and web pages are never saved; check the name before you save.',\n appDownloadSave: 'Save file',\n appSamplingLead: (server) => `The app “${server}” asks the agent’s model for an answer`,\n appSamplingSystem: 'Its instructions',\n appSamplingRole: (role) => (role === 'user' ? 'Asks' : 'Earlier answer'),\n appSamplingImages: (count) => plural(count, 'image', 'images'),\n appSamplingTokens: (tokens, asked) =>\n tokens < asked\n ? `Up to ${tokens} tokens (the app asked for ${asked}).`\n : `Up to ${tokens} tokens.`,\n appSamplingNote:\n 'Only this text is sent - not your chat. The answer goes to the app only, and its tokens count in your total.',\n appSamplingAllow: 'Allow once',\n appSamplingAlways: 'Always for this app',\n appSamplingDeny: 'Deny',\n skillConsentLead: (server, skill) => `The server “${server}” offers the skill “${skill}”`,\n skillConsentSize: (bytes, files) =>\n `SKILL.md ${kb(bytes)}${files ? ` · ${plural(files, 'more file', 'more files')}` : ''}`,\n skillConsentByUri: 'Not in the server’s list: the agent asked for it by its address.',\n skillConsentNested: (enclosing) =>\n `It sits inside the skill “${enclosing}”: allowing that one did not allow this one.`,\n skillConsentDynamic:\n 'This server publishes no checksums for this skill: you approve the copy the agent just read, and only that copy is used.',\n skillConsentNoFileListing:\n 'The server cannot list this skill’s files: that copy is its SKILL.md alone.',\n skillConsentPreview: 'Show what the agent would read',\n skillConsentFiles: (paths, more) =>\n `Its files, read as text and never run: ${paths}${more ? ` and ${more} more` : ''}`,\n skillConsentNote: (server, consent) =>\n `Instructions written by the server “${server}”, not by you. They reach the agent only if you allow it${\n consent === 'ask'\n ? ', and you are asked again in every task that loads them.'\n : ' - you are asked again if the server changes them.'\n } They cannot change the agent’s rules or approvals.`,\n skillConsentAllow: 'Allow once',\n skillConsentAlways: 'Always for this server',\n skillConsentDeny: 'Deny',\n skillConsentDeclined: 'the user declined the skill',\n}\n\n/** Overrides: any label, with the nested groups merged key by key. */\nexport type AgentLabelsOverride = Partial<\n Omit<\n AgentLabels,\n | 'status'\n | 'modes'\n | 'commandGroups'\n | 'commandDescriptions'\n | 'thinkingLevels'\n | 'notices'\n | 'tierNames'\n | 'tierReasons'\n | 'escalationReasons'\n | 'subagentStatus'\n | 'decisionReasons'\n | 'elicitationErrors'\n | 'elicitationReasons'\n | 'fileKinds'\n | 'appSandboxReasons'\n >\n> & {\n status?: Partial<AgentLabels['status']>\n modes?: Partial<AgentLabels['modes']>\n commandGroups?: Partial<AgentLabels['commandGroups']>\n commandDescriptions?: Partial<AgentLabels['commandDescriptions']>\n thinkingLevels?: Partial<AgentLabels['thinkingLevels']>\n notices?: Partial<AgentLabels['notices']>\n tierNames?: Partial<AgentLabels['tierNames']>\n tierReasons?: Partial<AgentLabels['tierReasons']>\n escalationReasons?: Partial<AgentLabels['escalationReasons']>\n subagentStatus?: Partial<AgentLabels['subagentStatus']>\n decisionReasons?: Partial<AgentLabels['decisionReasons']>\n elicitationErrors?: Partial<AgentLabels['elicitationErrors']>\n elicitationReasons?: Partial<AgentLabels['elicitationReasons']>\n fileKinds?: Partial<AgentLabels['fileKinds']>\n appSandboxReasons?: Partial<AgentLabels['appSandboxReasons']>\n}\n\nconst NESTED = [\n 'status',\n 'modes',\n 'commandGroups',\n 'commandDescriptions',\n 'thinkingLevels',\n 'noteAt',\n 'tierNames',\n 'tierReasons',\n 'escalationReasons',\n 'subagentStatus',\n 'decisionReasons',\n 'elicitationErrors',\n 'elicitationReasons',\n 'fileKinds',\n 'appSandboxReasons',\n] as const\n\n/** `base` with `over` applied (nested groups merged, not replaced). */\nexport const mergeLabels = (base: AgentLabels, over?: AgentLabelsOverride): AgentLabels => {\n if (!over) return base\n const out = { ...base, ...over } as AgentLabels\n for (const key of NESTED) {\n if (over[key]) (out as unknown as Record<string, unknown>)[key] = { ...base[key], ...over[key] }\n }\n return out\n}\n\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 type {\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './mcp-types.js'\n\n/**\n * MCP elicitation, the part of it that is not React: what a field of a server's form is drawn\n * as, what the user typed turned into the answer, the checks an answer must pass before it is\n * sent (the core's own rules, so the form says what is wrong instead of the tool call failing),\n * what a link may be opened as, and the queue of questions waiting for the user.\n *\n * Pure, and free of the MCP SDK and of the core's `./mcp` subpath: the prompt is in the main\n * entry of this package, the hooks that fill the queue are in `./mcp`.\n *\n * Nothing here keeps, logs or returns a value the user entered except to the one caller that\n * hands it to the server: an issue names the field and the rule, never the value.\n */\n\n// ── a question waiting for the user ──────────────────────────────────────\n\n/**\n * A question waiting for the user: the core's request (every string in it is the SERVER's\n * text), and when the core will stop waiting for the answer.\n */\nexport interface PendingElicitation extends McpElicitationRequest {\n /** Epoch ms after which the core cancels the question by itself; absent when it has no limit. */\n expiresAt?: number\n}\n\n/** The core's default for `elicitation.timeoutMs` (`MCP_ELICITATION_TIMEOUT_MS`). */\nexport const ELICITATION_TIMEOUT_MS = 300_000\n\n/**\n * The hooks' `elicitation` option as the core's settings, or `undefined` when it is off - and\n * then NOTHING is passed to the core: no capability is declared and the wire is what it was.\n */\nexport const elicitationSettings = (\n option: boolean | McpElicitationOptions | undefined | null,\n): McpElicitationOptions | undefined => {\n if (option === true) return {}\n if (typeof option === 'object' && option !== null) return { ...option }\n return undefined\n}\n\n/**\n * What the hooks add to the options of the core's `connectMcpHttp`: the handler and the\n * settings when elicitation is on, and NOTHING - not even the keys - when it is off.\n */\nexport const elicitationConnectOptions = (\n option: boolean | McpElicitationOptions | undefined | null,\n handler: McpElicitationHandler,\n): { onElicitation?: McpElicitationHandler; elicitation?: McpElicitationOptions } => {\n const settings = elicitationSettings(option)\n return settings ? { onElicitation: handler, elicitation: settings } : {}\n}\n\n/** The longest wait a timer holds (2^31 - 1 ms); the core takes a longer `timeoutMs` as none. */\nconst TIMER_MAX_MS = 2_147_483_647\n\n/**\n * How long the core waits for an answer with these settings; `undefined` = no limit of its own\n * (`0`, `Infinity`, more than a timer holds - the core's own rules).\n */\nexport const elicitationTimeoutOf = (settings: McpElicitationOptions): number | undefined => {\n const raw = settings.timeoutMs\n if (raw === undefined || raw === null) return ELICITATION_TIMEOUT_MS\n if (typeof raw !== 'number' || !(raw > 0) || raw > TIMER_MAX_MS) return undefined\n return Math.max(1, Math.floor(raw))\n}\n\nexport interface ElicitationQueueOptions {\n /**\n * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read\n * when a question arrives (the settings of the connection that is open then).\n */\n timeoutMs?: number | (() => number | undefined)\n /** Called whenever the list of pending questions changed. */\n onChange?: (pending: PendingElicitation[]) => void\n /** The clock (tests). */\n now?: () => number\n}\n\nexport interface ElicitationQueue {\n /** The core's `onElicitation`: resolves when the user answers, or as `cancel`. */\n handler: McpElicitationHandler\n /** The questions waiting, oldest first. */\n pending: () => PendingElicitation[]\n /** Answer one. False when no such question is waiting (answered, expired, cancelled). */\n answer: (id: string, result: McpElicitationResult) => boolean\n /** Cancel the waiting questions - all of them, or those `match` picks (one server's). */\n cancel: (match?: (request: PendingElicitation) => boolean) => void\n /** Cancel everything and stop reporting: the owner is gone. A later question is cancelled at once. */\n dispose: () => void\n}\n\n/**\n * The questions MCP servers are waiting on: `request.id → resolver`. A question leaves the queue\n * exactly once - answered by the user, cancelled because the core no longer wants the answer\n * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (a disconnect, an\n * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.\n */\nexport const createElicitationQueue = (options: ElicitationQueueOptions = {}): ElicitationQueue => {\n const now = options.now ?? Date.now\n const waiting = new Map<\n string,\n { request: PendingElicitation; settle: (result: McpElicitationResult) => void }\n >()\n let disposed = false\n\n const list = (): PendingElicitation[] => [...waiting.values()].map((w) => w.request)\n const changed = (): void => {\n if (!disposed) options.onChange?.(list())\n }\n\n const handler: McpElicitationHandler = (request, ctx) =>\n new Promise<McpElicitationResult>((resolve) => {\n const signal = ctx?.signal\n // Nobody to ask, or nobody wants the answer any more.\n if (disposed || signal?.aborted || waiting.has(request.id)) {\n resolve({ action: 'cancel' })\n return\n }\n // The core no longer wants the answer: its time ran out, or the run stopped.\n const onAbort = (): void => {\n if (waiting.get(request.id)?.settle !== settle) return\n settle({ action: 'cancel' })\n changed()\n }\n const settle = (result: McpElicitationResult): void => {\n // Exactly once: a second answer to the same question finds nothing to resolve.\n if (waiting.get(request.id)?.settle !== settle) return\n waiting.delete(request.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(result)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n const timeoutMs =\n typeof options.timeoutMs === 'function' ? options.timeoutMs() : options.timeoutMs\n waiting.set(request.id, {\n request: {\n ...request,\n ...(timeoutMs !== undefined ? { expiresAt: now() + timeoutMs } : {}),\n },\n settle,\n })\n changed()\n })\n\n return {\n handler,\n pending: list,\n answer: (id, result) => {\n const entry = waiting.get(id)\n if (!entry) return false\n entry.settle(result)\n changed()\n return true\n },\n cancel: (match) => {\n let any = false\n for (const entry of [...waiting.values()]) {\n if (match && !match(entry.request)) continue\n entry.settle({ action: 'cancel' })\n any = true\n }\n if (any) changed()\n },\n dispose: () => {\n disposed = true\n for (const entry of [...waiting.values()]) entry.settle({ action: 'cancel' })\n },\n }\n}\n\n// ── a form: fields, values, the answer ───────────────────────────────────\n\n/** What a field is drawn as. */\nexport type ElicitationControl =\n 'text' | 'email' | 'url' | 'date' | 'datetime' | 'number' | 'checkbox' | 'select' | 'multiselect'\n\nexport interface ElicitationOption {\n /** What goes back to the server, verbatim. */\n value: string\n /** What the user reads (the option's title, or the value). */\n label: string\n}\n\n/** One field of a form, ready to draw. `label`, `description` and option labels are the server's text. */\nexport interface ElicitationField {\n name: string\n label: string\n description?: string\n required: boolean\n control: ElicitationControl\n /** `select` / `multiselect`. */\n options?: ElicitationOption[]\n schema: McpElicitationFieldSchema\n}\n\n/** What the form holds while it is being filled in: text as typed, a tick, the ticked options. */\nexport type ElicitationDraftValue = string | boolean | string[]\nexport type ElicitationDraft = Record<string, ElicitationDraftValue>\n\nconst titled = (options: { const: string; title: string }[]): ElicitationOption[] =>\n options.map((o) => ({ value: o.const, label: o.title || o.const }))\n\n/** The options of a select, in the three forms the core lets through. */\nconst optionsOf = (schema: McpElicitationFieldSchema): ElicitationOption[] | undefined => {\n if (schema.type === 'array') {\n const items = schema.items\n if (items?.anyOf) return titled(items.anyOf)\n return (items?.enum ?? []).map((value) => ({ value, label: value }))\n }\n if (schema.type !== 'string') return undefined\n if (schema.oneOf) return titled(schema.oneOf)\n if (schema.enum) {\n const names = schema.enumNames\n return schema.enum.map((value, i) => ({ value, label: names?.[i] || value }))\n }\n return undefined\n}\n\nconst controlOf = (schema: McpElicitationFieldSchema): ElicitationControl => {\n switch (schema.type) {\n case 'boolean':\n return 'checkbox'\n case 'number':\n case 'integer':\n return 'number'\n case 'array':\n return 'multiselect'\n default:\n if (schema.enum || schema.oneOf) return 'select'\n switch (schema.format) {\n case 'email':\n return 'email'\n case 'uri':\n return 'url'\n case 'date':\n return 'date'\n case 'date-time':\n return 'datetime'\n default:\n return 'text'\n }\n }\n}\n\n/**\n * The fields of a form in the order the server listed them - exactly the set the core's schema\n * guard lets through: a text (plain, email, uri, date, date-time), a number / integer, a\n * boolean, a single select (`enum`, `enum` + `enumNames`, `oneOf`) and a multi-select (an array\n * of `enum` or `anyOf` options).\n */\nexport const elicitationFields = (schema: McpElicitationSchema | undefined): ElicitationField[] => {\n const required = new Set(schema?.required ?? [])\n return Object.entries(schema?.properties ?? {}).map(([name, field]) => {\n const options = optionsOf(field)\n return {\n name,\n label: field.title || name,\n ...(field.description ? { description: field.description } : {}),\n required: required.has(name),\n control: controlOf(field),\n ...(options ? { options } : {}),\n schema: field,\n }\n })\n}\n\nconst pad = (n: number): string => String(n).padStart(2, '0')\n\n// A date-time default as `<input type=\"datetime-local\">` wants it (local time, to the minute).\nconst toLocalInput = (value: string): string => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return ''\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/** What the form starts with: the schema's defaults (the core dropped the ones that do not fit). */\nexport const elicitationInitialDraft = (\n schema: McpElicitationSchema | undefined,\n): ElicitationDraft => {\n const draft: ElicitationDraft = {}\n for (const field of elicitationFields(schema)) {\n const preset = field.schema.default\n switch (field.control) {\n case 'checkbox':\n draft[field.name] = preset === true\n break\n case 'multiselect':\n draft[field.name] = Array.isArray(preset) ? [...preset] : []\n break\n case 'number':\n draft[field.name] = typeof preset === 'number' ? String(preset) : ''\n break\n case 'datetime':\n draft[field.name] = typeof preset === 'string' ? toLocalInput(preset) : ''\n break\n default:\n draft[field.name] = typeof preset === 'string' ? preset : ''\n }\n }\n return draft\n}\n\n/** The rules an answer can break. An issue never carries the value. */\nexport type ElicitationIssueKind =\n | 'required'\n | 'tooShort'\n | 'tooLong'\n | 'email'\n | 'uri'\n | 'date'\n | 'dateTime'\n | 'notNumber'\n | 'notInteger'\n | 'belowMinimum'\n | 'aboveMaximum'\n | 'notAnOption'\n | 'tooFew'\n | 'tooMany'\n\nexport interface ElicitationIssue {\n kind: ElicitationIssueKind\n /** The limit the rule states (a length, a bound, a count), when it has one. */\n limit?: number\n}\n\n/** The longest text a field without its own `maxLength` takes (the core's cap). */\nexport const ELICITATION_VALUE_MAX_CHARS = 10_000\n/** The most options one multi-select may be answered with (the core's cap). */\nexport const ELICITATION_MAX_OPTIONS = 100\n\n// A number as a person types it: digits, a sign, a decimal point, an exponent. `Number('')` is\n// 0 and `Number(' 1 ')` is 1, so the text is checked first.\nconst NUMBER = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)(e[+-]?\\d+)?$/i\n\nconst numberOf = (text: string): number | undefined => {\n const trimmed = text.trim()\n if (!NUMBER.test(trimmed)) return undefined\n const n = Number(trimmed)\n return Number.isFinite(n) ? n : undefined\n}\n\n// The core's `validFormat`, rule for rule.\nconst formatIssue = (\n format: McpElicitationFieldSchema['format'],\n value: string,\n): ElicitationIssueKind | undefined => {\n switch (format) {\n case 'email':\n return /^[^@\\s]+@[^@\\s]+$/.test(value) ? undefined : 'email'\n case 'uri':\n try {\n return new URL(value) ? undefined : 'uri'\n } catch {\n return 'uri'\n }\n case 'date':\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'date'\n case 'date-time':\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'dateTime'\n default:\n return undefined\n }\n}\n\n// A date-time goes back as RFC 3339 with its offset (UTC): the input's value is local time\n// without one, which a server could read as any zone.\nconst dateTimeOf = (value: string): string => {\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? value : date.toISOString()\n}\n\ntype FieldAnswer =\n { issue: ElicitationIssue } | { value: string | number | boolean | string[] } | { empty: true }\n\n// One field: its value as the server gets it, why it does not fit, or \"left empty\".\nconst answerOf = (field: ElicitationField, raw: ElicitationDraftValue | undefined): FieldAnswer => {\n const { schema } = field\n switch (field.control) {\n case 'checkbox':\n // A tick box always has a value: unticked is `false`, which is an answer.\n return { value: raw === true }\n case 'multiselect': {\n const picked = Array.isArray(raw) ? raw : []\n // Nothing ticked in an optional list is \"not answered\", as an empty text is.\n if (picked.length === 0 && !field.required) return { empty: true }\n const allowed = new Set((field.options ?? []).map((o) => o.value))\n if (!picked.every((item) => allowed.has(item))) return { issue: { kind: 'notAnOption' } }\n if (schema.minItems !== undefined && picked.length < schema.minItems) {\n return { issue: { kind: 'tooFew', limit: schema.minItems } }\n }\n const max = Math.min(schema.maxItems ?? ELICITATION_MAX_OPTIONS, ELICITATION_MAX_OPTIONS)\n if (picked.length > max) return { issue: { kind: 'tooMany', limit: max } }\n return { value: [...picked] }\n }\n case 'number': {\n const text = typeof raw === 'string' ? raw.trim() : ''\n if (!text) return { empty: true }\n const n = numberOf(text)\n if (n === undefined) return { issue: { kind: 'notNumber' } }\n if (schema.type === 'integer' && !Number.isInteger(n)) {\n return { issue: { kind: 'notInteger' } }\n }\n if (schema.minimum !== undefined && n < schema.minimum) {\n return { issue: { kind: 'belowMinimum', limit: schema.minimum } }\n }\n if (schema.maximum !== undefined && n > schema.maximum) {\n return { issue: { kind: 'aboveMaximum', limit: schema.maximum } }\n }\n return { value: n }\n }\n case 'select': {\n const text = typeof raw === 'string' ? raw : ''\n if (!text) return { empty: true }\n return (field.options ?? []).some((o) => o.value === text)\n ? { value: text }\n : { issue: { kind: 'notAnOption' } }\n }\n default: {\n const typed = typeof raw === 'string' ? raw : ''\n if (!typed) return { empty: true }\n const text = field.control === 'datetime' ? dateTimeOf(typed) : typed\n const max = schema.maxLength ?? ELICITATION_VALUE_MAX_CHARS\n if (text.length > max) return { issue: { kind: 'tooLong', limit: max } }\n if (schema.minLength !== undefined && text.length < schema.minLength) {\n return { issue: { kind: 'tooShort', limit: schema.minLength } }\n }\n const format = formatIssue(schema.format, text)\n return format ? { issue: { kind: format } } : { value: text }\n }\n }\n}\n\nexport type ElicitationFormOutcome =\n | { ok: true; content: Record<string, string | number | boolean | string[]> }\n | { ok: false; issues: Record<string, ElicitationIssue> }\n\n/**\n * A filled-in form as the answer the core will accept, or what is wrong with it, per field. The\n * rules are the core's (`validateMcpElicitationContent`): a required field is there, every\n * value is of its field's type and within its limits, and nothing the form did not ask for is\n * sent. A field left empty is left out, not sent as an empty text.\n */\nexport const elicitationFormAnswer = (\n schema: McpElicitationSchema | undefined,\n draft: ElicitationDraft,\n): ElicitationFormOutcome => {\n const content: Record<string, string | number | boolean | string[]> = {}\n const issues: Record<string, ElicitationIssue> = {}\n for (const field of elicitationFields(schema)) {\n const answer = answerOf(field, Object.hasOwn(draft, field.name) ? draft[field.name] : undefined)\n if ('issue' in answer) {\n issues[field.name] = answer.issue\n } else if ('empty' in answer) {\n if (field.required) issues[field.name] = { kind: 'required' }\n } else {\n content[field.name] = answer.value\n }\n }\n return Object.keys(issues).length > 0 ? { ok: false, issues } : { ok: true, content }\n}\n\n// ── a link ───────────────────────────────────────────────────────────────\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\nexport interface ElicitationLink {\n /** The host the link leads to (with its port), as the browser will resolve it; '' if unparseable. */\n host: string\n /** The whole link as text: the parsed form when it parses, what the server sent otherwise. */\n href: string\n /** Whether an \"Open\" action may exist for it: https, or http on a loopback host, no credentials. */\n openable: boolean\n}\n\n/**\n * A link a server wants the user to open, as the prompt may show it. The core already refuses\n * anything but https (http on loopback); this is the same rule applied again where the link is\n * about to be opened, because a host may hand the prompt a request the core never checked.\n */\nexport const elicitationLink = (raw: unknown): ElicitationLink => {\n const text = typeof raw === 'string' ? raw : ''\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return { host: '', href: text, openable: false }\n }\n const secure =\n url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n return {\n host: url.host,\n href: url.href,\n openable: secure && !url.username && !url.password && !/\\s/.test(text),\n }\n}\n\n// ── an answer nobody gave ────────────────────────────────────────────────\n\n/**\n * Why a question was answered without anybody deciding: the core's reasons\n * (`mcp.elicitation-answered` with `automatic: true`), and `stopped`, which the reducer sets on\n * whatever was still waiting when the run stopped.\n */\nexport type ElicitationOutcomeReason =\n | 'timeout'\n | 'step-timeout'\n | 'aborted'\n | 'stopped'\n | 'cap-per-call'\n | 'cap-per-run'\n | 'unsupported-schema'\n | 'unsupported-mode'\n | 'insecure-url'\n | 'invalid-request'\n | 'subagent'\n | 'handler-error'\n | 'invalid-answer'\n | 'after-failure'\n | 'no-tool-call'\n\n/** \"4:05\" - what is left of a question's time. */\nexport const formatCountdown = (ms: number): string => {\n const total = Math.max(0, Math.ceil(ms / 1000))\n return `${Math.floor(total / 60)}:${pad(total % 60)}`\n}\n","import { useEffect, useRef, useState } from 'react'\nimport type { ComponentType, CSSProperties, ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\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 {\n useMcpAppHost,\n type AppRequestView,\n type McpAppsConnectionLike,\n} from '../hooks/use-mcp-app-host.js'\nimport type { McpAppSandboxOptions } from '../mcp-app.js'\nimport type { AppView, ChatMessage } from '../types.js'\nimport { AppRequestPrompt } from './AppRequestPrompt.js'\nimport { McpAppFrame, McpAppLine } from './McpAppFrame.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 { ElicitationPrompt, type ElicitationPromptProps } from './ElicitationPrompt.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 { decisionNote, type RenderToolCall } from './StepList.js'\nimport type { RenderSubagent } from './SubagentTree.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 ElicitationPrompt?: ComponentType<ElicitationPromptProps>\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 /**\n * Model tiers (`executorTiers`): the tier / model badge on a step, the \"escalated\" line and\n * the escalation count (default true; nothing shows when tiers are off).\n */\n showTiers?: boolean\n /** The \"replanning failed, continuing with the plan\" warning (default true). */\n showReplanFailed?: boolean\n /**\n * The decision model's note under the step it was asked after - \"decision model: continue\n * (0.93)\" (default true; nothing shows without `decisionModel`).\n */\n showDecisions?: boolean\n /** A `web_search` call's results as a short list under its row (default true). */\n showSearchResults?: boolean\n /**\n * The subagent tree - static subagents and the helpers the model started - under the step\n * that started them (default true).\n */\n showSubagents?: boolean\n /**\n * What a run generated (`config.media`): images inline in the answer, audio as a player, and\n * the transcripts of audio files, folded (default true). The bytes are read from `files`.\n */\n showMedia?: boolean\n /**\n * The files an answer wrote to the workspace (`files`), as chips under it: name, kind, size,\n * open (an inline preview - an `.html` file in a sandboxed frame) and download (default true).\n */\n showFileChips?: boolean\n /**\n * How an `.html` file is previewed: sandboxed, no network, scripts off by default;\n * `{ scripts: true }` lets its inline scripts run; `false` shows HTML as source only.\n */\n htmlPreview?: MessageListProps['htmlPreview']\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 * Questions MCP servers put to the user (MCP elicitation), beside the consent prompts\n * (default true). Shown once `elicitations` and `onElicitationAnswer` are given.\n */\n showElicitation?: boolean\n /**\n * In the consent card of an MCP server's skill: the collapsible preview of the instructions\n * the agent would read (default true; `<ToolApprovalPrompt showSkillPreview>`).\n */\n showSkillPreview?: 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 * The questions MCP servers are waiting on: `pendingElicitations` of `useMcp` /\n * `useMcpServers` (from `@dudko.dev/agent-web-react/mcp`, with their `elicitation` option on).\n */\n elicitations?: ElicitationPromptProps['elicitations']\n /** The user's answer to one of them: the hook's `answerElicitation`. */\n onElicitationAnswer?: ElicitationPromptProps['onAnswer']\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 /** A node of the subagent tree. */\n renderSubagent?: RenderSubagent\n /** A generated image / audio file. */\n renderMedia?: MessageListProps['renderMedia']\n /** A file chip of an answer. */\n renderFile?: MessageListProps['renderFile']\n /** A written text file rendered your way (Markdown); `undefined` = shown as source. */\n renderFileContent?: MessageListProps['renderFileContent']\n renderApproval?: ToolApprovalPromptProps['renderApproval']\n /** A server's question (gets the built-in card as `fallback`, and `answer`). */\n renderElicitation?: ElicitationPromptProps['renderElicitation']\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 // ── MCP Apps ───────────────────────────────────────────────────────────────\n /**\n * MCP Apps: the connection that reads an app and makes the calls it asks for -\n * `useMcpServers({ apps: true }).apps` (or `useMcp`'s, or the core's `ConnectedMcp.apps`).\n * With it, an answer whose tool call came with an app shows the app in a sandboxed frame under\n * the answer, and everything the app asks for - a tool call, a link, a message - is put to the\n * user here, labelled as the app's. Without it no app is drawn.\n */\n mcpApps?: McpAppsConnectionLike\n /** Draw MCP Apps (default true; needs `mcpApps`). */\n showApps?: boolean\n /**\n * Run apps on an origin of their own: `{ url }` of a sandbox page you serve on ANOTHER origin\n * (`@dudko.dev/agent-web-react/mcp-app-sandbox`), e.g.\n * `{ url: 'https://apps.example.com/sandbox/v1' }` - or `'https://{server}.apps.example.com/…'`\n * for one origin per server. Default: none - apps run in an opaque frame (no storage of their\n * own). A URL on this page's origin, or not https, is refused (opaque); so is a page that does\n * not answer in `timeoutMs`.\n */\n appSandbox?: McpAppSandboxOptions\n /**\n * Let an app be shown full screen (`ui/request-display-mode`): over the chat panel, or the\n * viewport on a phone, in the host's chrome with Exit full screen and Esc. Granted only to\n * an app that declared it, right after a click or a key inside its frame. Default false.\n */\n appFullscreen?: boolean\n /**\n * Let an app hand the user a file to save (`ui/download-file`): a prompt with its name, type\n * and size, saved by this page on \"Save file\". Programs, scripts and web pages are refused; a\n * linked file is read from the app's own server only. Default false.\n */\n appDownloads?: boolean\n /**\n * Let an app ask the agent's model for an answer (`sampling/createMessage`, no tools): a\n * prompt with exactly what the model would get; \"Allow once\", \"Always for this app\" (until a\n * reload) or \"Deny\". The answer goes to the app only; its tokens count in the total. Default\n * false. Needs a controller with `sampleForApp` (`useAgent`).\n */\n appSampling?: boolean\n /** Start every app folded to one line (default false). */\n appsCollapsed?: boolean\n /**\n * Where an app opened \"in panel\" goes: `'auto'` (default) - beside the chat when it is wide,\n * a bottom sheet when it is narrow (`narrowWidth`); `'sheet'` - always the sheet; an element -\n * rendered into it (a column of your page); `false` - no panel.\n */\n appPanel?: 'auto' | 'sheet' | HTMLElement | null | false\n /** Told when an app goes into the panel (`app`) or leaves it (`undefined`). */\n onAppPanel?: (app: AppView | undefined) => void\n /** An app yourself: `fallback` is the built-in frame. */\n renderApp?: (app: AppView, message: ChatMessage, fallback: ReactNode) => ReactNode\n /** A link / message an app asks for, yourself: `fallback` is the built-in card. */\n renderAppRequest?: (request: AppRequestView, fallback: ReactNode) => ReactNode\n}\n\n/** Follows the OS colour scheme (for `theme=\"auto\"`): what an app is told. */\nconst usePrefersDark = (): boolean => {\n const query = '(prefers-color-scheme: dark)'\n const [dark, setDark] = useState(\n () => typeof matchMedia === 'function' && matchMedia(query).matches,\n )\n useEffect(() => {\n if (typeof matchMedia !== 'function') return\n const mq = matchMedia(query)\n const on = () => setDark(mq.matches)\n mq.addEventListener?.('change', on)\n return () => mq.removeEventListener?.('change', on)\n }, [])\n return dark\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 showTiers = true,\n showReplanFailed = true,\n showDecisions = true,\n showSearchResults = true,\n showSubagents = true,\n showMedia = true,\n showFileChips = true,\n htmlPreview,\n stoppableSubagents = true,\n showTotalUsage = true,\n showStatus = true,\n showApprovalMode = true,\n showContext = false,\n activityOpen = false,\n showElicitation = true,\n showSkillPreview = true,\n elicitations,\n onElicitationAnswer,\n renderElicitation,\n history,\n defaultHistoryOpen,\n files,\n defaultFilesOpen = false,\n narrowWidth = 760,\n composer,\n renderContent,\n renderMessage,\n renderAttachment,\n renderToolCall,\n renderSubagent,\n renderMedia,\n renderFile,\n renderFileContent,\n renderApproval,\n slots = {},\n components = {},\n theme = 'auto',\n classNames = {},\n className,\n style,\n mcpApps,\n appSandbox,\n appFullscreen = false,\n appDownloads = false,\n appSampling = false,\n showApps = true,\n appsCollapsed = false,\n appPanel = 'auto',\n onAppPanel,\n renderApp,\n renderAppRequest,\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 const showFiles = () => {\n setFilesOpen(true)\n if (narrow) 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 }, [\n agent.messages,\n agent.steps,\n agent.finalText,\n agent.modelLoad,\n agent.pendingApprovals,\n elicitations,\n ])\n\n // MCP Apps: the host (reads, consent), the theme they are told, the one in the panel.\n const appHost = useMcpAppHost({\n connection: mcpApps,\n approve: agent.approveAppToolCall,\n approvals: agent.pendingApprovals,\n sandbox: appSandbox,\n downloads: appDownloads,\n sampling: appSampling,\n ...(agent.sampleForApp ? { sample: agent.sampleForApp } : {}),\n })\n const prefersDark = usePrefersDark()\n const appTheme: 'light' | 'dark' = theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme\n const [panelApp, setPanelAppState] = useState<AppView | undefined>()\n const setPanelApp = (app: AppView | undefined) => {\n setPanelAppState(app)\n onAppPanel?.(app)\n }\n const appsOn = showApps && Boolean(mcpApps)\n const panelAllowed = appPanel !== false && appPanel !== null\n const panelTarget = typeof appPanel === 'object' && appPanel ? appPanel : undefined\n const asSheet = !panelTarget && (appPanel === 'sheet' || Boolean(narrow))\n // An app whose message is gone (a new chat, a reset) leaves the panel.\n useEffect(() => {\n if (panelApp && !agent.messages.some((m) => m.apps?.some((a) => a.id === panelApp.id))) {\n setPanelAppState(undefined)\n onAppPanel?.(undefined)\n }\n }, [agent.messages, panelApp, onAppPanel])\n const drawApp = (app: AppView, message: ChatMessage): ReactNode => {\n const built =\n panelApp?.id === app.id ? (\n <McpAppLine\n app={app}\n note={L.appInPanel}\n action={L.appBringBack}\n onAction={() => setPanelApp(undefined)}\n />\n ) : (\n <McpAppFrame\n app={app}\n host={appHost}\n theme={appTheme}\n defaultCollapsed={appsCollapsed}\n onOpenPanel={panelAllowed ? () => setPanelApp(app) : undefined}\n allowFullscreen={appFullscreen}\n />\n )\n return renderApp ? renderApp(app, message, built) : built\n }\n const appPanelNode =\n appsOn && panelApp ? (\n <McpAppFrame\n key={panelApp.id}\n app={panelApp}\n host={appHost}\n theme={appTheme}\n variant=\"panel\"\n onClosePanel={() => setPanelApp(undefined)}\n allowFullscreen={appFullscreen}\n />\n ) : null\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 const Elicitations = components.ElicitationPrompt ?? ElicitationPrompt\n\n const loading = agent.modelLoad && agent.modelLoad.progress < 1\n const showReplan = agent.replan && agent.replan.mode !== 'continue'\n // A replanner that failed before any step exists has no step to hang its warning on.\n const replanFailedEarly =\n showReplanFailed && agent.replan?.failed === true && agent.steps.length === 0\n // A decision made before any step exists has no step to sit under either.\n const earlyDecisions = showDecisions ? (agent.decisions ?? []) : []\n const liveExtra =\n agent.planThought.trim() || showReplan || replanFailedEarly || earlyDecisions.length > 0 ? (\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 {replanFailedEarly && (\n <p className=\"awr-step__warn\" title={agent.replan!.error}>\n <AlertIcon size={12} /> {L.replanFailed}\n </p>\n )}\n {earlyDecisions.map((d, i) => (\n <p\n key={i}\n className={`awr-step__decision${d.accepted ? '' : ' awr-step__decision--fallback'}`}\n >\n {decisionNote(d, L)}\n </p>\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 showTiers={showTiers}\n showReplanFailed={showReplanFailed}\n showDecisions={showDecisions}\n showSearchResults={showSearchResults}\n showSubagents={showSubagents}\n showMedia={showMedia}\n showFileChips={showFileChips}\n files={files}\n htmlPreview={htmlPreview}\n onShowFiles={files ? showFiles : undefined}\n renderFile={renderFile}\n renderFileContent={renderFileContent}\n renderMedia={renderMedia}\n renderSubagent={renderSubagent}\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 showApps={appsOn}\n renderApp={appsOn ? drawApp : undefined}\n />\n <Approvals\n approvals={agent.pendingApprovals}\n onApprove={agent.approve}\n onDeny={agent.deny}\n showSkillPreview={showSkillPreview}\n renderApproval={renderApproval}\n />\n {/* Asked of the user, in this order: tool calls (the agent's and an app's), what an\n app asks besides (a link, a message), then a server's questions. */}\n {appsOn && (\n <AppRequestPrompt\n requests={appHost.requests}\n onAnswer={appHost.answer}\n renderRequest={renderAppRequest}\n />\n )}\n {showElicitation && elicitations && onElicitationAnswer && (\n <Elicitations\n elicitations={elicitations}\n onAnswer={onElicitationAnswer}\n outcomes={agent.elicitations}\n renderElicitation={renderElicitation}\n />\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 {...(appHost.draft ? { draft: appHost.draft } : {})}\n {...(placeholder ? { placeholder } : {})}\n {...composer}\n />\n )}\n </div>\n </div>\n\n {appPanelNode &&\n (panelTarget ? (\n // Outside the chat: the theme tokens come with it.\n createPortal(\n <div\n className=\"awr-theme awr-apppanel\"\n data-awr-theme={theme === 'auto' ? undefined : theme}\n >\n {appPanelNode}\n </div>,\n panelTarget,\n )\n ) : asSheet ? (\n <>\n <div className=\"awr-sheet__scrim\" onClick={() => setPanelApp(undefined)} />\n <aside\n className=\"awr-chat__appsheet\"\n role=\"dialog\"\n aria-label={L.appFrom(panelApp!.server)}\n >\n <div className=\"awr-sheet__grab\" />\n {appPanelNode}\n </aside>\n </>\n ) : (\n <aside className=\"awr-chat__apppanel\">{appPanelNode}</aside>\n ))}\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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type {\n AppSamplingRequest,\n AppSamplingResult,\n AppSamplingView,\n AppToolCallRequest,\n McpAppResource,\n McpAppToolResult,\n} from '@dudko.dev/agent-web'\nimport {\n appSamplingErrorOf,\n MCP_APP_REFUSED,\n McpAppRpcError,\n resolveAppDownload,\n saveAppFile,\n type AppDownload,\n type AppLink,\n type McpAppSandboxOptions,\n} from '../mcp-app.js'\nimport type { AppView, ApprovalView } from '../types.js'\n\n/**\n * The connection's side of MCP Apps, structurally: the core's `ConnectedMcp.apps` (`./mcp`,\n * `apps: true`), or the one `useMcp` / `useMcpServers` return. Every method names the server,\n * and the host always passes the app's OWN server: an app reads and calls only what its server\n * declared.\n */\nexport interface McpAppsConnectionLike {\n readUiResource: (\n server: string,\n uri: string,\n options?: { signal?: AbortSignal },\n ) => Promise<McpAppResource>\n appTool: (\n server: string,\n name: string,\n ) => { key: string; readOnly: boolean; description?: string; inputSchema?: unknown } | undefined\n callAppTool: (\n server: string,\n name: string,\n args: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n ) => Promise<McpAppToolResult>\n /**\n * A resource of that server for a file its app asks to save (a `resource_link`): the core's\n * `ConnectedMcp.apps.readResource` - `resources/read` on that server, never a fetch. Older\n * cores have none: a linked file is then refused.\n */\n readResource?: (\n server: string,\n uri: string,\n options?: { signal?: AbortSignal; maxBytes?: number },\n ) => Promise<{ uri: string; mimeType?: string; bytes: Uint8Array }>\n}\n\n/** A file an app asks to save, as the prompt shows it (the bytes stay with the host). */\nexport interface AppDownloadView {\n /** What it will be saved as (sanitized). */\n name: string\n /** The declared type, if any (the server's, for a linked file). */\n mimeType?: string\n /** Bytes. */\n size: number\n /** In the request (`embedded`), or read from the app's server (`link`). */\n source: 'embedded' | 'link'\n}\n\n/** What an app asks for besides a tool call, waiting for the user (`<AppRequestPrompt>`). */\nexport interface AppRequestView {\n id: string\n /** The app (`AppView.id`) that asks. */\n appId: string\n server: string\n kind: 'link' | 'message' | 'download' | 'sampling'\n /** `kind: 'link'`: the link, taken apart (the host is what the user checks). */\n link?: AppLink\n /** `kind: 'message'`: the app's text, cleaned. */\n text?: string\n /** `kind: 'download'`: the file. */\n download?: AppDownloadView\n /** `kind: 'sampling'`: exactly what the model would get (the core checked and cleaned it). */\n sampling?: AppSamplingView\n}\n\n/** How the user answered (`answer(id, accept, options)`). */\nexport interface AppRequestAnswerOptions {\n /** A sampling request: allow this app's requests until the page is reloaded. */\n always?: boolean\n}\n\n/** What `<McpAppFrame>` asks of the host, and what the host shows the user. */\nexport interface McpAppHost {\n /** No connection (apps are off, or the server is gone): frames say so. */\n connected: boolean\n read: (app: AppView, signal?: AbortSignal) => Promise<McpAppResource>\n /** The tool an app's tool-info names (for its host context); undefined when unknown. */\n tool: (app: AppView) => { description?: string; inputSchema?: unknown } | undefined\n /** An app's `tools/call`: the agent's consent gate first, then the call. Throws when refused. */\n callTool: (\n app: AppView,\n name: string,\n args: Record<string, unknown>,\n signal?: AbortSignal,\n ) => Promise<McpAppToolResult>\n /** An app's `ui/open-link`: true once the user opened it, false when they did not. */\n openLink: (app: AppView, link: AppLink, signal?: AbortSignal) => Promise<boolean>\n /** An app's `ui/message`: true once the user put it in the message box. */\n message: (app: AppView, text: string, signal?: AbortSignal) => Promise<boolean>\n /**\n * An app's `ui/download-file` (checked by the bridge): true once the user saved it, false when\n * they did not. Present only with `downloads` on: absent, the method is not offered.\n */\n downloadFile?: (app: AppView, file: AppDownload, signal?: AbortSignal) => Promise<boolean>\n /**\n * An app's `sampling/createMessage`: the agent's model answers it (the core's\n * `Agent.sampleForApp`), after the user said yes. Present only with `sampling` on and a\n * `sample` given: absent, the method is not offered.\n */\n sample?: (app: AppView, params: Record<string, unknown>, signal?: AbortSignal) => Promise<unknown>\n /** Links, messages, files and sampling requests waiting for the user. */\n requests: AppRequestView[]\n /**\n * The user's answer to a request. Call it from the click: an accepted link is opened right\n * there (`window.open`, `noopener,noreferrer`) and an accepted file saved right there\n * (`saveAppFile`), nowhere else. `always` (a sampling request): this app's next requests are\n * not asked about until the page is reloaded.\n */\n answer: (id: string, accept: boolean, options?: AppRequestAnswerOptions) => void\n /** The last message the user accepted: the composer appends it as a draft (never sends it). */\n draft?: { id: string; text: string }\n /** Whether the app has something waiting for the user (a link, a message, a tool call). */\n isWaiting: (app: AppView) => boolean\n /**\n * Where apps run: on an origin of their own, through the sandbox page at this URL - or, when\n * absent (the default), in an opaque frame. See `McpAppSandboxOptions`.\n */\n sandbox?: McpAppSandboxOptions\n}\n\nexport interface UseMcpAppHostOptions {\n /** The connection(s) the apps came from; without one, frames say their server is not connected. */\n connection?: McpAppsConnectionLike\n /** The agent's consent gate for an app's calls: `useAgent().approveAppToolCall`. */\n approve?: (call: AppToolCallRequest, signal?: AbortSignal) => Promise<void>\n /** The pending consent requests (`useAgent().pendingApprovals`): an app's are its \"waiting\". */\n approvals?: ApprovalView[]\n /**\n * Run apps on an origin of their own: the URL of a sandbox page you serve on ANOTHER origin\n * (`./mcp-app-sandbox`). Without it, apps run in an opaque frame (no storage of their own).\n */\n sandbox?: McpAppSandboxOptions\n /**\n * Let apps hand the user a file to save (`ui/download-file`, `hostCapabilities.downloadFile`).\n * Each file is put to the user (name, type, size) and saved only on their click. Default false.\n */\n downloads?: boolean\n /**\n * Let apps ask the agent's model for a completion (`sampling/createMessage`,\n * `hostCapabilities.sampling` - never `sampling.tools`). Needs `sample`. Default false.\n */\n sampling?: boolean\n /** The agent's seam for it: `useAgent().sampleForApp`. */\n sample?: (\n request: AppSamplingRequest,\n approve: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ) => Promise<AppSamplingResult>\n}\n\nlet seq = 0\n\nconst refused = (message: string): McpAppRpcError => new McpAppRpcError(MCP_APP_REFUSED, message)\n\n/**\n * The host's side of MCP Apps for a chat: reads an app from its own server, puts each tool call\n * an app asks for through the agent's consent gate, and holds the link and message requests until\n * the user answers. `<AgentChat mcpApps={…}>` uses it; use it yourself with `<McpAppFrame>` and\n * `<AppRequestPrompt>` in your own UI.\n */\nexport const useMcpAppHost = ({\n connection,\n approve,\n approvals = [],\n sandbox,\n downloads = false,\n sampling = false,\n sample: sampleFn,\n}: UseMcpAppHostOptions): McpAppHost => {\n const [requests, setRequests] = useState<AppRequestView[]>([])\n const [draft, setDraft] = useState<{ id: string; text: string } | undefined>()\n const waiting = useRef(\n new Map<\n string,\n {\n request: AppRequestView\n resolve: (ok: boolean) => void\n /** A file to save on the user's Allow (never in state). */\n file?: { name: string; bytes: Uint8Array }\n /** A sampling request: the app's key, for \"always for this app\". */\n app?: string\n }\n >(),\n )\n // Apps whose sampling the user allowed until the page is reloaded (server + resource).\n const samplingAllowed = useRef(new Set<string>())\n const sampleRef = useRef(sampleFn)\n sampleRef.current = sampleFn\n // Calls of an app that wait in the agent's gate, by app id (for \"waiting for you\").\n const [gated, setGated] = useState<Record<string, number>>({})\n const connectionRef = useRef(connection)\n connectionRef.current = connection\n const approveRef = useRef(approve)\n approveRef.current = approve\n\n // Nothing is left waiting behind an unmounted chat.\n useEffect(\n () => () => {\n for (const { resolve } of waiting.current.values()) resolve(false)\n waiting.current.clear()\n },\n [],\n )\n\n const ask = useCallback(\n (\n request: Omit<AppRequestView, 'id'>,\n signal?: AbortSignal,\n extra: { file?: { name: string; bytes: Uint8Array }; app?: string } = {},\n ): Promise<boolean> => {\n // One question per app at a time: an app cannot pile up prompts.\n for (const w of waiting.current.values()) {\n if (w.request.appId === request.appId) {\n return Promise.reject(refused('Another request of this app is waiting for the user'))\n }\n }\n if (signal?.aborted) return Promise.resolve(false)\n seq += 1\n const full: AppRequestView = { ...request, id: `app-request-${seq}` }\n return new Promise<boolean>((resolve) => {\n const done = (ok: boolean) => {\n if (!waiting.current.delete(full.id)) return\n signal?.removeEventListener('abort', onAbort)\n setRequests((list) => list.filter((r) => r.id !== full.id))\n resolve(ok)\n }\n const onAbort = () => done(false)\n signal?.addEventListener('abort', onAbort, { once: true })\n waiting.current.set(full.id, { request: full, resolve: done, ...extra })\n setRequests((list) => [...list, full])\n })\n },\n [],\n )\n\n const answer = useCallback((id: string, accept: boolean, options?: AppRequestAnswerOptions) => {\n const w = waiting.current.get(id)\n if (!w) return\n if (accept && w.request.kind === 'link' && w.request.link) {\n // Only here, on the user's click, and without an opener or a referrer.\n globalThis.open?.(w.request.link.href, '_blank', 'noopener,noreferrer')\n }\n if (accept && w.request.kind === 'message' && w.request.text) {\n setDraft({ id, text: w.request.text })\n }\n if (accept && w.request.kind === 'download' && w.file) {\n // Only here, on the user's click: a blob of this page, an <a download> of ours.\n try {\n saveAppFile(w.file, {\n document,\n URL,\n setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),\n })\n } catch {\n w.resolve(false)\n return\n }\n }\n if (accept && options?.always && w.request.kind === 'sampling' && w.app) {\n samplingAllowed.current.add(w.app)\n }\n w.resolve(accept)\n }, [])\n\n const read = useCallback((app: AppView, signal?: AbortSignal) => {\n const c = connectionRef.current\n if (!c) return Promise.reject(new Error(`no connection to the server “${app.server}”`))\n return c.readUiResource(app.server, app.resourceUri, signal ? { signal } : undefined)\n }, [])\n\n const tool = useCallback(\n (app: AppView) => connectionRef.current?.appTool(app.server, app.toolName),\n [],\n )\n\n const callTool = useCallback(\n async (\n app: AppView,\n name: string,\n args: Record<string, unknown>,\n signal?: AbortSignal,\n ): Promise<McpAppToolResult> => {\n const c = connectionRef.current\n if (!c) throw refused(`The server “${app.server}” is not connected`)\n // Only a tool of the app's OWN server that lets apps call it (visibility 'app').\n const t = c.appTool(app.server, name)\n if (!t) throw new McpAppRpcError(-32602, `This app may not call “${name.slice(0, 80)}”`)\n const gate = approveRef.current\n if (!gate) throw refused('This host cannot ask the user about an app’s tool calls')\n setGated((g) => ({ ...g, [app.id]: (g[app.id] ?? 0) + 1 }))\n try {\n await gate(\n {\n tool: t.key,\n toolName: name,\n server: app.server,\n resourceUri: app.resourceUri,\n input: args,\n readOnly: t.readOnly,\n },\n signal,\n )\n } catch (err) {\n const denied = err instanceof Error && err.name === 'ToolDeniedError'\n throw refused(\n denied\n ? 'Tool call denied by the user'\n : err instanceof Error\n ? err.message\n : String(err),\n )\n } finally {\n setGated((g) => {\n const next = { ...g, [app.id]: (g[app.id] ?? 1) - 1 }\n if (next[app.id] <= 0) delete next[app.id]\n return next\n })\n }\n return c.callAppTool(app.server, name, args, signal ? { signal } : undefined)\n },\n [],\n )\n\n const openLink = useCallback(\n (app: AppView, link: AppLink, signal?: AbortSignal) =>\n ask({ appId: app.id, server: app.server, kind: 'link', link }, signal),\n [ask],\n )\n const message = useCallback(\n (app: AppView, text: string, signal?: AbortSignal) =>\n ask({ appId: app.id, server: app.server, kind: 'message', text }, signal),\n [ask],\n )\n\n const downloadFile = useCallback(\n async (app: AppView, file: AppDownload, signal?: AbortSignal): Promise<boolean> => {\n const c = connectionRef.current\n if (file.kind === 'link' && !c) throw refused(`The server “${app.server}” is not connected`)\n // A linked file is read from the app's OWN server through the connection - never fetched.\n const ready = await resolveAppDownload(file, app.server, c?.readResource, signal)\n return ask(\n {\n appId: app.id,\n server: app.server,\n kind: 'download',\n download: {\n name: ready.name,\n ...(ready.mimeType ? { mimeType: ready.mimeType } : {}),\n size: ready.bytes.length,\n source: ready.source,\n },\n },\n signal,\n { file: { name: ready.name, bytes: ready.bytes } },\n )\n },\n [ask],\n )\n\n const sample = useCallback(\n async (app: AppView, params: Record<string, unknown>, signal?: AbortSignal) => {\n const fn = sampleRef.current\n if (!fn) throw refused('This host cannot answer sampling requests')\n const key = `${app.server}\\u0000${app.resourceUri}`\n try {\n return await fn(\n { server: app.server, resourceUri: app.resourceUri, params },\n (view) =>\n samplingAllowed.current.has(key)\n ? Promise.resolve(true)\n : ask(\n { appId: app.id, server: app.server, kind: 'sampling', sampling: view },\n signal,\n { app: key },\n ),\n signal,\n )\n } catch (err) {\n // The core's refusals carry the code the app is told (-1: the user said no).\n throw appSamplingErrorOf(err)\n }\n },\n [ask],\n )\n\n const pendingAppServers = useMemo(\n () =>\n new Set(\n approvals\n .filter((a) => a.app && a.status === 'pending')\n .map((a) => `${a.app!.server}\\u0000${a.app!.resourceUri}`),\n ),\n [approvals],\n )\n\n const isWaiting = useCallback(\n (app: AppView) =>\n requests.some((r) => r.appId === app.id) ||\n (Boolean(gated[app.id]) && pendingAppServers.has(`${app.server}\\u0000${app.resourceUri}`)),\n [requests, gated, pendingAppServers],\n )\n\n // A new object each render (an inline prop) is the same setting.\n const sandboxUrl = sandbox?.url\n const sandboxTimeout = sandbox?.timeoutMs\n const sandboxSetting = useMemo<McpAppSandboxOptions | undefined>(\n () =>\n sandboxUrl === undefined\n ? undefined\n : {\n url: sandboxUrl,\n ...(sandboxTimeout !== undefined ? { timeoutMs: sandboxTimeout } : {}),\n },\n [sandboxUrl, sandboxTimeout],\n )\n\n const samplingOn = sampling && Boolean(sampleFn)\n return useMemo(\n () => ({\n connected: Boolean(connection),\n read,\n tool,\n callTool,\n openLink,\n message,\n ...(downloads ? { downloadFile } : {}),\n ...(samplingOn ? { sample } : {}),\n requests,\n answer,\n draft,\n isWaiting,\n ...(sandboxSetting ? { sandbox: sandboxSetting } : {}),\n }),\n [\n connection,\n read,\n tool,\n callTool,\n openLink,\n message,\n downloads,\n downloadFile,\n samplingOn,\n sample,\n requests,\n answer,\n draft,\n isWaiting,\n sandboxSetting,\n ],\n )\n}\n","import { mcpAppOrigin, type McpAppCsp } from '@dudko.dev/agent-web'\nimport { cspMetaTag, escapeAttribute, withPolicyFirst } from './html-preview.js'\nimport {\n isMcpAppSandboxMessage,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n mcpAppPolicy,\n mcpAppPolicyToken,\n} from './mcp-app-policy.js'\n\n/**\n * MCP Apps, the host's side: the security core of `<McpAppFrame>`, as pure code - no React, no\n * DOM - so every guard is unit-tested (`tests/apps.test.ts`) and proved in a real browser\n * (`e2e/apps.spec.ts`).\n *\n * The frame: an app is third-party HTML WITH scripts that must talk to the page, so it gets the\n * HTML preview's boundary (`html-preview.ts`) and one addition, a relay:\n *\n * 1. The outer `<iframe sandbox=\"allow-scripts\">` (never `allow-same-origin`): an opaque origin,\n * no access to the page's DOM, storage, IndexedDB (the key vault) or cookies; no top\n * navigation, popups, forms, modals, downloads. No `allow` attribute: no camera, microphone,\n * geolocation or clipboard, whatever the app asked for.\n * 2. It holds a SHELL of ours (`buildMcpAppDocument`): the policy built from the resource's\n * declared origins and nothing else (`mcpAppCsp`), one inner frame - the app, also\n * `sandbox=\"allow-scripts\"`, with the same policy first in its own document - and a relay\n * script. The shell's `frame-src 'none'` is what stops the app navigating itself (a frame\n * may always navigate itself; only the EMBEDDING document's policy decides where to).\n * 3. The relay forwards messages between the page and the app, and nothing else: from the\n * app's window to the page, from the page to the app's window, never the\n * `ui/notifications/sandbox-*` messages the specification reserves. The app talks to\n * `window.parent` as the extension's SDK does; the page accepts messages only from the outer\n * frame (`event.source`), so the app writing to `window.top` directly is ignored.\n * 4. The bridge (`McpAppBridge`) answers the app: a method allow-list, checked parameters, a\n * cap on requests in flight, and every request that DOES something (a tool call, a link, a\n * message) handed to the host, which asks the user.\n *\n * That is the default. Opt-in, the app runs on an origin of its own instead, behind a sandbox\n * page the host serves on another origin (the specification's \"sandbox proxy\"): 1 - 3 change\n * (see \"An app on an origin of its own\" below and `mcp-app-policy.ts`), 4 does not.\n */\n\n/** The revision of the extension this host speaks. */\nexport const MCP_APP_PROTOCOL_VERSION = '2026-01-26'\n\n/** An app's frame height, before it says how tall it is. */\nexport const APP_DEFAULT_HEIGHT = 360\n/** The frame's height is the host's: the app's wish, clamped to these. */\nexport const APP_MIN_HEIGHT = 120\nexport const APP_MAX_HEIGHT = 800\n\n/** At most this many requests of one app wait at once (tool calls, links, messages). */\nexport const MCP_APP_MAX_IN_FLIGHT = 3\n/** A message an app puts in the chat: at most this many characters. */\nexport const MCP_APP_MAX_MESSAGE_CHARS = 4000\n/** A link an app asks to open: at most this many characters. */\nexport const MCP_APP_MAX_URL_CHARS = 2048\n/** The arguments of a tool call an app makes: at most this many characters as JSON. */\nexport const MCP_APP_MAX_ARGS_CHARS = 64_000\n\nexport const clampAppHeight = (height: number): number =>\n Math.min(\n APP_MAX_HEIGHT,\n Math.max(APP_MIN_HEIGHT, Math.round(Number.isFinite(height) ? height : APP_DEFAULT_HEIGHT)),\n )\n\n/** The declared origins of a list that are origins (re-checked here: whoever built the object). */\nconst origins = (list: readonly string[] | undefined): string[] => {\n const out: string[] = []\n for (const entry of list ?? []) {\n const origin = mcpAppOrigin(entry)\n if (origin && !out.includes(origin)) out.push(origin)\n }\n return out\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it - `connectDomains` for `fetch` / XHR / WebSocket,\n * `resourceDomains` for scripts, styles, images, fonts and media. Nothing declared, nothing\n * reached. Nested frames, workers, plugins, forms and `<base>` are refused whatever was declared\n * (`frameDomains` / `baseUriDomains` are not granted: a frame the app may embed would also be a\n * place it may navigate itself to). Each entry is checked again with the core's `mcpAppOrigin`.\n */\nexport const mcpAppCsp = (csp?: Partial<McpAppCsp>): string =>\n mcpAppPolicy({ connect: origins(csp?.connectDomains), resources: origins(csp?.resourceDomains) })\n\n/** The origins the policy actually grants: what the app is told in `hostCapabilities.sandbox`. */\nexport const grantedAppCsp = (\n csp?: Partial<McpAppCsp>,\n): { connectDomains: string[]; resourceDomains: string[] } => ({\n connectDomains: origins(csp?.connectDomains),\n resourceDomains: origins(csp?.resourceDomains),\n})\n\n/**\n * The relay of the shell: the app's messages to the page, the page's to the app - matched by\n * `event.source`, never by anything the message says - and not the reserved\n * `ui/notifications/sandbox-*` ones. It reads nothing else and runs nothing it is sent.\n */\nexport const MCP_APP_RELAY =\n \"(function(){var f=document.getElementById('app');\" +\n \"function reserved(d){return !!d&&typeof d.method==='string'&&d.method.indexOf('ui/notifications/sandbox-')===0}\" +\n \"addEventListener('message',function(e){var w=f&&f.contentWindow;if(!w||reserved(e.data))return;\" +\n \"if(e.source===w){parent.postMessage(e.data,'*')}else if(e.source===parent){w.postMessage(e.data,'*')}})})()\"\n\n/**\n * What goes into the OUTER frame's `srcdoc`: the shell (the app's policy first, one inner frame\n * that fills it, the relay) carrying the app, escaped, as the inner frame's `srcdoc` - with the\n * same policy first in it. Give the outer `<iframe>` `sandbox=\"allow-scripts\"` and nothing else.\n */\nexport const buildMcpAppDocument = (html: string, csp?: Partial<McpAppCsp>): string => {\n const policy = mcpAppCsp(csp)\n return (\n '<!doctype html><html><head>' +\n `<meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\">` +\n '<style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n 'iframe{display:block;border:0;width:100%;height:100%}</style></head><body>' +\n `<iframe id=\"app\" sandbox=\"allow-scripts\" referrerpolicy=\"no-referrer\" ` +\n `srcdoc=\"${escapeAttribute(withPolicyFirst(html, policy))}\"></iframe>` +\n `<script>${MCP_APP_RELAY}</script></body></html>`\n )\n}\n\n/** A link an app asks to open, taken apart for the prompt: the host is what the user checks. */\nexport interface AppLink {\n /** The normalised URL (what is opened). */\n href: string\n /** `https://` */\n scheme: string\n /** The host (and port), as the browser will go there - an internationalised name in punycode. */\n host: string\n /** Everything after the host. */\n rest: string\n}\n\n/** An `http(s)` URL with a host and no credentials, at most `MCP_APP_MAX_URL_CHARS`; else none. */\nexport const appLinkOf = (value: unknown): AppLink | undefined => {\n if (typeof value !== 'string' || value.length > MCP_APP_MAX_URL_CHARS) return undefined\n let url: URL\n try {\n url = new URL(value)\n } catch {\n return undefined\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return undefined\n if (url.username || url.password || !url.hostname) return undefined\n const scheme = `${url.protocol}//`\n return {\n href: url.href,\n scheme,\n host: url.host,\n rest: url.href.slice(scheme.length + url.host.length),\n }\n}\n\n// Characters that change how text reads without being seen (bidirectional overrides,\n// zero-width) and control characters other than line breaks and tabs.\n// eslint-disable-next-line no-control-regex\nconst HIDDEN = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f​-‏‪-‮⁦-⁩]/g\n\n/**\n * The text of a `ui/message` an app sends: text blocks only (one, or a list of at most 20),\n * joined, without invisible characters, at most `MCP_APP_MAX_MESSAGE_CHARS`. Anything else -\n * an image, a resource, an empty or a longer text - is refused (`undefined`).\n */\nexport const appMessageTextOf = (content: unknown): string | undefined => {\n const blocks = Array.isArray(content) ? content : content === undefined ? [] : [content]\n if (blocks.length === 0 || blocks.length > 20) return undefined\n const texts: string[] = []\n for (const block of blocks) {\n if (!isObject(block) || block.type !== 'text' || typeof block.text !== 'string') {\n return undefined\n }\n texts.push(block.text)\n }\n const text = texts.join('\\n\\n').replace(HIDDEN, '').trim()\n return text && text.length <= MCP_APP_MAX_MESSAGE_CHARS ? text : undefined\n}\n\ntype Obj = Record<string, unknown>\nconst isObject = (value: unknown): value is Obj =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** A JSON-RPC message as the bridge sends it. */\nexport type McpAppRpcMessage =\n | { jsonrpc: '2.0'; id: string | number; method: string; params?: unknown }\n | { jsonrpc: '2.0'; method: string; params?: unknown }\n | { jsonrpc: '2.0'; id: string | number; result: unknown }\n | { jsonrpc: '2.0'; id: string | number; error: { code: number; message: string } }\n\n/** The requests an app may make of this host. Any other is answered \"method not found\". */\nexport const MCP_APP_REQUESTS = [\n 'ui/initialize',\n 'ping',\n 'tools/call',\n 'ui/open-link',\n 'ui/message',\n 'ui/request-display-mode',\n] as const\n/**\n * Requests answered only when the host turned the feature on (`downloadFile` / `sampling` in\n * `hostCapabilities`, a handler given to the bridge); otherwise \"method not found\", as before.\n */\nexport const MCP_APP_OPTIONAL_REQUESTS = ['ui/download-file', 'sampling/createMessage'] as const\n/** The notifications this host reads. Any other is dropped. */\nexport const MCP_APP_NOTIFICATIONS = [\n 'ui/notifications/initialized',\n 'ui/notifications/size-changed',\n] as const\n\n/** An error the bridge answers with: a JSON-RPC code and a message for the app. */\nexport class McpAppRpcError extends Error {\n constructor(\n readonly code: number,\n message: string,\n ) {\n super(message)\n this.name = 'McpAppRpcError'\n }\n}\n\nconst METHOD_NOT_FOUND = -32601\nconst INVALID_PARAMS = -32602\nconst INVALID_REQUEST = -32600\n/** The host refused: the user said no, too many requests, not initialized. */\nexport const MCP_APP_REFUSED = -32000\n\n/** How an app is shown (`hostContext.displayMode`). This host offers `inline` and `fullscreen`. */\nexport type McpAppDisplayMode = 'inline' | 'fullscreen' | 'pip'\n/** The modes the extension names (a request for any other is invalid). */\nexport const MCP_APP_DISPLAY_MODES: readonly McpAppDisplayMode[] = ['inline', 'fullscreen', 'pip']\n\n/** A file an app asks the host to save (`ui/download-file`), as checked by `appDownloadOf`. */\nexport type AppDownload =\n | {\n kind: 'embedded'\n /** The file name, sanitized (`appFileNameOf`): what it is saved as. */\n name: string\n /** The type the app declared, if it is a MIME type at all. */\n mimeType?: string\n bytes: Uint8Array\n }\n | {\n /** A `resource_link`: read with `resources/read` on the app's own server, never fetched. */\n kind: 'link'\n uri: string\n name: string\n mimeType?: string\n }\n\n/** What the host does for an app (the user is asked inside these, never by the bridge). */\nexport interface McpAppBridgeHandlers {\n /** A `tools/call`: resolves with the result the app is given; throws when refused. */\n callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>\n /** A link (already checked): resolves true when it was opened, false when the user said no. */\n openLink: (link: AppLink) => Promise<boolean>\n /** A message (already cleaned): resolves true when it was accepted, false when not. */\n message: (text: string) => Promise<boolean>\n /** The app's wish for a height (the caller clamps it). */\n resize: (height: number) => void\n /**\n * `ui/request-display-mode` for a mode the host offers and the app declared (or `inline`):\n * the mode the app is in afterwards - the host may say no and answer the current one.\n * Without it, an app stays where it is.\n */\n displayMode?: (mode: McpAppDisplayMode) => McpAppDisplayMode | Promise<McpAppDisplayMode>\n /**\n * `ui/download-file` (already checked): true once the file was saved, false when the user said\n * no. Without it the method is not offered (`hostCapabilities.downloadFile` absent).\n */\n downloadFile?: (file: AppDownload) => Promise<boolean>\n /**\n * `sampling/createMessage`: the result for the app; throws (an `McpAppRpcError`) when refused.\n * Without it the method is not offered (`hostCapabilities.sampling` absent).\n */\n sample?: (params: Record<string, unknown>) => Promise<unknown>\n}\n\nexport interface McpAppBridgeOptions {\n /** Send a message to the app (the page posts it to the outer frame). */\n post: (message: McpAppRpcMessage) => void\n handlers: McpAppBridgeHandlers\n hostInfo: { name: string; version: string }\n hostCapabilities: Record<string, unknown>\n hostContext: Record<string, unknown>\n /** The tool call's arguments: sent once the app says it is initialized. */\n toolInput: Record<string, unknown>\n /** Its result; `undefined` = the app is told the call was cancelled (`reason`). */\n toolResult?: unknown\n cancelledReason?: string\n maxInFlight?: number\n}\n\nconst validId = (id: unknown): id is string | number =>\n (typeof id === 'string' && id.length > 0 && id.length <= 100) ||\n (typeof id === 'number' && Number.isFinite(id))\n\n/**\n * One app's conversation with the host (the extension's JSON-RPC over `postMessage`). It never\n * touches the DOM: `receive` is given what arrived - from the right frame, the caller checked\n * `event.source` - and `post` sends. Requests outside the allow-list get \"method not found\";\n * before `ui/initialize`, only `ping` is answered; parameters are checked before a handler sees\n * them; at most `maxInFlight` requests run at once. The tool's input and result are sent once,\n * after the app's `ui/notifications/initialized`, as the specification requires.\n */\nexport class McpAppBridge {\n private readonly o: McpAppBridgeOptions\n private initializeSeen = false\n private delivered = false\n private inFlight = 0\n private closed = false\n private seq = 0\n // The display modes the app declared at `ui/initialize` (undefined: none declared).\n private appModes: McpAppDisplayMode[] | undefined\n\n constructor(options: McpAppBridgeOptions) {\n this.o = options\n }\n\n /** The app said it is ready, and was given the tool's input and result. */\n get initialized(): boolean {\n return this.delivered\n }\n\n /** Stop answering: the frame is gone or was reloaded. */\n close(): void {\n this.closed = true\n }\n\n /** Tell the app it is being torn down (not waited for: the frame goes anyway). */\n teardown(reason: string): void {\n if (!this.delivered || this.closed) return\n this.seq += 1\n this.send({\n jsonrpc: '2.0',\n id: `host-teardown-${this.seq}`,\n method: 'ui/resource-teardown',\n params: { reason },\n })\n }\n\n /** How the app is shown now (`hostContext.displayMode`). */\n get displayMode(): McpAppDisplayMode {\n const mode = this.o.hostContext.displayMode\n return MCP_APP_DISPLAY_MODES.includes(mode as McpAppDisplayMode)\n ? (mode as McpAppDisplayMode)\n : 'inline'\n }\n\n /** Tell an initialized app that part of the host context changed (the theme). */\n updateContext(patch: Record<string, unknown>): void {\n Object.assign(this.o.hostContext, patch)\n if (this.delivered && !this.closed) {\n this.send({ jsonrpc: '2.0', method: 'ui/notifications/host-context-changed', params: patch })\n }\n }\n\n /** One message from the app's frame. */\n receive(data: unknown): void {\n if (this.closed || !isObject(data) || data.jsonrpc !== '2.0') return\n const method = data.method\n const id = data.id\n if (method === undefined) return // a response to a request of ours: nothing waits for it\n if (typeof method !== 'string' || method.length === 0 || method.length > 100) {\n if (validId(id)) this.error(id, INVALID_REQUEST, 'Invalid request')\n return\n }\n if (id === undefined) {\n this.notification(method, data.params)\n return\n }\n if (!validId(id)) return\n if (data.params !== undefined && !isObject(data.params)) {\n this.error(id, INVALID_PARAMS, 'params must be an object')\n return\n }\n void this.request(id, method, (data.params ?? {}) as Obj)\n }\n\n private send(message: McpAppRpcMessage): void {\n if (!this.closed) this.o.post(message)\n }\n\n private error(id: string | number, code: number, message: string): void {\n this.send({ jsonrpc: '2.0', id, error: { code, message } })\n }\n\n private notification(method: string, params: unknown): void {\n const p = isObject(params) ? params : {}\n if (method === 'ui/notifications/initialized') {\n if (!this.initializeSeen || this.delivered) return\n this.delivered = true\n this.send({\n jsonrpc: '2.0',\n method: 'ui/notifications/tool-input',\n params: { arguments: this.o.toolInput },\n })\n this.send(\n this.o.toolResult === undefined\n ? {\n jsonrpc: '2.0',\n method: 'ui/notifications/tool-cancelled',\n params: { reason: this.o.cancelledReason ?? 'no result' },\n }\n : { jsonrpc: '2.0', method: 'ui/notifications/tool-result', params: this.o.toolResult },\n )\n return\n }\n if (method === 'ui/notifications/size-changed') {\n if (typeof p.height === 'number' && Number.isFinite(p.height) && p.height > 0) {\n this.o.handlers.resize(p.height)\n }\n }\n // Anything else (a log line, a teardown wish, an unknown one) is dropped.\n }\n\n private async request(id: string | number, method: string, params: Obj): Promise<void> {\n const h = this.o.handlers\n const offered =\n (MCP_APP_REQUESTS as readonly string[]).includes(method) ||\n (method === 'ui/download-file' && typeof h.downloadFile === 'function') ||\n (method === 'sampling/createMessage' && typeof h.sample === 'function')\n if (!offered) {\n this.error(id, METHOD_NOT_FOUND, `Method not found: ${method.slice(0, 60)}`)\n return\n }\n if (method === 'ping') {\n this.send({ jsonrpc: '2.0', id, result: {} })\n return\n }\n if (method === 'ui/initialize') {\n this.initializeSeen = true\n const caps = isObject(params.appCapabilities) ? params.appCapabilities : {}\n this.appModes = Array.isArray(caps.availableDisplayModes)\n ? caps.availableDisplayModes.filter((m): m is McpAppDisplayMode =>\n MCP_APP_DISPLAY_MODES.includes(m as McpAppDisplayMode),\n )\n : undefined\n this.send({\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion: MCP_APP_PROTOCOL_VERSION,\n hostInfo: this.o.hostInfo,\n hostCapabilities: this.o.hostCapabilities,\n hostContext: this.o.hostContext,\n },\n })\n return\n }\n if (!this.initializeSeen) {\n this.error(id, MCP_APP_REFUSED, 'The app is not initialized (send ui/initialize first)')\n return\n }\n if (method === 'ui/request-display-mode') {\n const requested = params.mode\n if (!MCP_APP_DISPLAY_MODES.includes(requested as McpAppDisplayMode)) {\n this.error(id, INVALID_PARAMS, 'mode must be \"inline\", \"fullscreen\" or \"pip\"')\n return\n }\n // The host decides where an app is shown, and answers the mode it is in afterwards.\n const current = this.displayMode\n const host = Array.isArray(this.o.hostContext.availableDisplayModes)\n ? (this.o.hostContext.availableDisplayModes as McpAppDisplayMode[])\n : ['inline' as const]\n let mode: McpAppDisplayMode = current\n if (\n h.displayMode &&\n appDisplayModeAllowed({\n requested: requested as McpAppDisplayMode,\n current,\n host,\n app: this.appModes,\n })\n ) {\n try {\n const next = await h.displayMode(requested as McpAppDisplayMode)\n mode = MCP_APP_DISPLAY_MODES.includes(next) ? next : current\n } catch {\n mode = this.displayMode\n }\n }\n this.send({ jsonrpc: '2.0', id, result: { mode } })\n return\n }\n // What remains does something the user is asked about: capped, then handed over.\n let run: (() => Promise<unknown>) | undefined\n if (method === 'tools/call') {\n const name = params.name\n const args = params.arguments === undefined ? {} : params.arguments\n if (typeof name !== 'string' || name.length === 0 || name.length > 128) {\n this.error(id, INVALID_PARAMS, 'tools/call needs the name of a tool')\n return\n }\n if (!isObject(args)) {\n this.error(id, INVALID_PARAMS, 'tools/call arguments must be an object')\n return\n }\n let size = Infinity\n try {\n size = JSON.stringify(args).length\n } catch {\n // not serialisable: refused below\n }\n if (size > MCP_APP_MAX_ARGS_CHARS) {\n this.error(id, INVALID_PARAMS, 'tools/call arguments are too large')\n return\n }\n run = () => this.o.handlers.callTool(name, args)\n } else if (method === 'ui/download-file') {\n const file = appDownloadOf(params)\n if (typeof file === 'string') {\n this.error(id, INVALID_PARAMS, file)\n return\n }\n const save = h.downloadFile!\n // Denied (or not saved): a result with `isError`, as the extension's SDK expects.\n run = async () => ((await save(file)) ? {} : { isError: true })\n } else if (method === 'sampling/createMessage') {\n const sample = h.sample!\n run = () => sample(params)\n } else if (method === 'ui/open-link') {\n const link = appLinkOf(params.url)\n if (!link) {\n this.error(id, INVALID_PARAMS, 'Invalid URL: only http(s) links without credentials')\n return\n }\n run = async () => {\n if (!(await this.o.handlers.openLink(link))) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Link opening denied by user')\n }\n return {}\n }\n } else {\n const text = params.role === 'user' ? appMessageTextOf(params.content) : undefined\n if (text === undefined) {\n this.error(\n id,\n INVALID_PARAMS,\n 'Invalid message format: one user text, not empty, not too long',\n )\n return\n }\n run = async () => {\n if (!(await this.o.handlers.message(text))) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Message sending denied')\n }\n return {}\n }\n }\n const cap = this.o.maxInFlight ?? MCP_APP_MAX_IN_FLIGHT\n if (this.inFlight >= cap) {\n this.error(id, MCP_APP_REFUSED, 'Too many requests of this app are waiting')\n return\n }\n this.inFlight += 1\n try {\n const result = await run()\n this.send({ jsonrpc: '2.0', id, result })\n } catch (err) {\n const code = err instanceof McpAppRpcError ? err.code : MCP_APP_REFUSED\n const message = (err instanceof Error ? err.message : String(err)).slice(0, 300)\n this.error(id, code, message)\n } finally {\n this.inFlight -= 1\n }\n }\n}\n\n/**\n * What this host tells an app it can do (`hostCapabilities` of `ui/initialize`): only what it\n * does. `downloadFile` and `sampling` (never `sampling.tools`) only when the host turned them on.\n */\nexport const mcpAppHostCapabilities = (\n csp?: Partial<McpAppCsp>,\n features: { downloadFile?: boolean; sampling?: boolean } = {},\n): Record<string, unknown> => ({\n openLinks: {},\n serverTools: {},\n message: { text: {} },\n ...(features.downloadFile ? { downloadFile: {} } : {}),\n ...(features.sampling ? { sampling: {} } : {}),\n // What the frame grants: the declared origins it kept; no permission at all.\n sandbox: { permissions: {}, csp: grantedAppCsp(csp) },\n})\n\n// ── Display modes ───────────────────────────────────────────────────────────────────────────\n\n/**\n * Whether a display mode an app asks for may be given: `inline` always (the way back needs no\n * permission); any other only when the host offers it AND the app declared it in\n * `appCapabilities.availableDisplayModes` - an app that declared nothing stays inline (the\n * specification lets a host decline it).\n */\nexport const appDisplayModeAllowed = (o: {\n requested: McpAppDisplayMode\n current: McpAppDisplayMode\n host: readonly McpAppDisplayMode[]\n app: readonly McpAppDisplayMode[] | undefined\n}): boolean =>\n o.requested === o.current ||\n o.requested === 'inline' ||\n (o.host.includes(o.requested) && (o.app?.includes(o.requested) ?? false))\n\n/**\n * Whether the user just acted INSIDE the app's frame: the page's frame element has the focus\n * (a click or a key in a frame focuses it) and the page has transient user activation (an\n * activation in a frame reaches every page above it, for a few seconds). Where the browser has\n * no `navigator.userActivation`, the focus alone.\n */\nexport const appGestureOf = (o: { focused: boolean; activation: boolean | undefined }): boolean =>\n o.focused && o.activation !== false\n\n// ── Downloads: a file the app hands the host to save ────────────────────────────────────────\n\n/** A file an app asks to save: at most this many bytes. */\nexport const MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024\n/** A saved file's name: at most this many characters (the extension kept). */\nexport const MCP_APP_MAX_FILE_NAME_CHARS = 100\n\n/**\n * Extensions this host never saves: programs, scripts, installers, shortcuts, disk images - and\n * documents a browser runs scripts in when they are opened (HTML, SVG, XML).\n */\nexport const MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS: readonly string[] = [\n 'exe',\n 'com',\n 'bat',\n 'cmd',\n 'scr',\n 'pif',\n 'msi',\n 'msp',\n 'mst',\n 'msc',\n 'cpl',\n 'dll',\n 'sys',\n 'ps1',\n 'psm1',\n 'psd1',\n 'vbs',\n 'vbe',\n 'js',\n 'jse',\n 'mjs',\n 'cjs',\n 'wsf',\n 'wsh',\n 'ws',\n 'hta',\n 'jar',\n 'jnlp',\n 'lnk',\n 'reg',\n 'inf',\n 'scf',\n 'url',\n 'website',\n 'application',\n 'gadget',\n 'sh',\n 'bash',\n 'zsh',\n 'csh',\n 'ksh',\n 'command',\n 'tool',\n 'app',\n 'pkg',\n 'mpkg',\n 'dmg',\n 'deb',\n 'rpm',\n 'apk',\n 'xapk',\n 'appimage',\n 'run',\n 'bin',\n 'elf',\n 'out',\n 'py',\n 'pyw',\n 'pyz',\n 'pl',\n 'rb',\n 'php',\n 'html',\n 'htm',\n 'xhtml',\n 'xht',\n 'shtml',\n 'mht',\n 'mhtml',\n 'svg',\n 'svgz',\n 'xml',\n 'xsl',\n 'xslt',\n 'webloc',\n 'desktop',\n 'iso',\n 'img',\n 'vhd',\n 'vhdx',\n 'library-ms',\n 'settingcontent-ms',\n]\n\n/** Types this host never saves (the same kinds), and any `…+xml`. */\nexport const MCP_APP_REFUSED_DOWNLOAD_TYPES: readonly string[] = [\n 'text/html',\n 'application/xhtml+xml',\n 'image/svg+xml',\n 'application/xml',\n 'text/xml',\n 'text/javascript',\n 'application/javascript',\n 'application/ecmascript',\n 'application/x-javascript',\n 'application/x-msdownload',\n 'application/x-msdos-program',\n 'application/x-msi',\n 'application/x-ms-installer',\n 'application/vnd.microsoft.portable-executable',\n 'application/x-executable',\n 'application/x-elf',\n 'application/x-sh',\n 'application/x-shellscript',\n 'application/x-csh',\n 'application/java-archive',\n 'application/x-java-jnlp-file',\n 'application/hta',\n 'application/x-apple-diskimage',\n 'application/vnd.android.package-archive',\n 'application/x-python-code',\n 'text/x-python',\n 'application/x-httpd-php',\n]\n\nconst MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/\n\n/** A declared type as a bare MIME type (`text/plain`), or undefined when it is not one. */\nexport const appMimeTypeOf = (value: unknown): string | undefined => {\n if (typeof value !== 'string') return undefined\n const type = value.split(';')[0]!.trim().toLowerCase()\n return MIME.test(type) ? type : undefined\n}\n\n// Device names Windows will not let a file be called (with any extension).\nconst RESERVED_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i\n\n/**\n * The name a file is saved under: the last segment of a path or URI (`file:///x/report.json` →\n * `report.json`; percent-encoding decoded, and split again), without what cannot be seen or\n * reserved characters (`<>:\"/\\|?*`, controls), no leading dots (a hidden file) or trailing dots\n * and spaces, not a Windows device name, at most `MCP_APP_MAX_FILE_NAME_CHARS` with the extension\n * kept; `download` when nothing is left.\n */\nexport const appFileNameOf = (value: unknown): string => {\n let name = typeof value === 'string' ? value.slice(0, 2048) : ''\n name = name.replace(/[?#].*$/s, '')\n name = name.split(/[\\\\/]/).pop() ?? ''\n try {\n name = decodeURIComponent(name)\n } catch {\n // not percent-encoded: as it is\n }\n name = (name.split(/[\\\\/]/).pop() ?? '')\n .replace(HIDDEN, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[<>:\"|?*\\u0000-\\u001f\\u007f]/g, '_')\n .replace(/\\s+/g, ' ')\n .replace(/^[.\\s]+/, '')\n .replace(/[.\\s]+$/, '')\n if (RESERVED_NAME.test(name)) name = `_${name}`\n if (name.length > MCP_APP_MAX_FILE_NAME_CHARS) {\n const dot = name.lastIndexOf('.')\n const ext = dot > 0 && name.length - dot <= 16 ? name.slice(dot) : ''\n name = name.slice(0, MCP_APP_MAX_FILE_NAME_CHARS - ext.length).replace(/[.\\s]+$/, '') + ext\n }\n return name || 'download'\n}\n\n/** The extension of a (sanitized) file name, lowercased, without the dot; '' when none. */\nexport const appFileExtensionOf = (name: string): string => {\n const dot = name.lastIndexOf('.')\n return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''\n}\n\n/**\n * Why a file may not be saved, or undefined when it may: an extension or a type of the refused\n * lists (a program, a script, a page a browser would run), checked on the sanitized name and\n * the declared type both.\n */\nexport const appDownloadRefusal = (name: string, mimeType?: string): string | undefined => {\n const ext = appFileExtensionOf(name)\n if (MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS.includes(ext)) return `“.${ext}” files are not saved`\n const type = appMimeTypeOf(mimeType)\n if (type && (MCP_APP_REFUSED_DOWNLOAD_TYPES.includes(type) || type.endsWith('+xml'))) {\n return `${type} files are not saved`\n }\n return undefined\n}\n\nconst URI_LINE = /^[^\\u0000-\\u001f\\u007f\\s]{1,2048}$/\n\nconst bytesOfBase64 = (blob: string, maxBytes: number): Uint8Array | string => {\n if (blob.length > Math.ceil((maxBytes * 4) / 3) + 4)\n return `the file is larger than ${maxBytes} bytes`\n if (!/^[A-Za-z0-9+/\\s]*={0,2}\\s*$/.test(blob)) return 'blob must be base64'\n try {\n const binary = atob(blob.replace(/\\s+/g, ''))\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return 'blob must be base64'\n }\n}\n\n/**\n * What `ui/download-file` asks for, checked - or why not (a message for the app): ONE item of\n * `contents` (one file per request, one prompt); an `EmbeddedResource` (`resource.uri` names\n * it, `text` as UTF-8 or base64 `blob`, at most `maxBytes`) or a `ResourceLink` (a one-line URI,\n * read later from the app's own server: the name is its last segment, else its `name`); the\n * name sanitized and the name and type not refused (`appDownloadRefusal`).\n */\nexport const appDownloadOf = (\n params: unknown,\n maxBytes: number = MCP_APP_MAX_DOWNLOAD_BYTES,\n): AppDownload | string => {\n const contents = isObject(params) ? params.contents : undefined\n if (!Array.isArray(contents) || contents.length === 0) return 'contents must list the file'\n if (contents.length > 1) return 'One file per request'\n const item = contents[0]\n if (!isObject(item)) return 'Invalid content'\n if (item.type === 'resource') {\n const r = item.resource\n if (!isObject(r) || typeof r.uri !== 'string' || !URI_LINE.test(r.uri)) {\n return 'Invalid content: resource.uri names the file'\n }\n const name = appFileNameOf(r.uri)\n const mimeType = appMimeTypeOf(r.mimeType)\n const refused = appDownloadRefusal(name, mimeType)\n if (refused) return `Policy violation: ${refused}`\n let bytes: Uint8Array | string\n if (typeof r.text === 'string') {\n bytes =\n r.text.length > maxBytes\n ? `the file is larger than ${maxBytes} bytes`\n : new TextEncoder().encode(r.text)\n } else if (typeof r.blob === 'string') {\n bytes = bytesOfBase64(r.blob, maxBytes)\n } else {\n return 'Invalid content: text or blob'\n }\n if (typeof bytes === 'string') return `Invalid content: ${bytes}`\n if (bytes.length > maxBytes) return `Invalid content: the file is larger than ${maxBytes} bytes`\n return { kind: 'embedded', name, ...(mimeType ? { mimeType } : {}), bytes }\n }\n if (item.type === 'resource_link') {\n if (typeof item.uri !== 'string' || !URI_LINE.test(item.uri)) {\n return 'Invalid content: a resource_link needs a URI'\n }\n const fromUri = appFileNameOf(item.uri)\n const name =\n fromUri !== 'download' || typeof item.name !== 'string' ? fromUri : appFileNameOf(item.name)\n const mimeType = appMimeTypeOf(item.mimeType)\n const refused = appDownloadRefusal(name, mimeType)\n if (refused) return `Policy violation: ${refused}`\n return { kind: 'link', uri: item.uri, name, ...(mimeType ? { mimeType } : {}) }\n }\n return 'Invalid content: a resource or a resource_link'\n}\n\n/** A file ready to be put to the user: its name, type, bytes, and where the bytes came from. */\nexport interface AppReadyDownload {\n name: string\n mimeType?: string\n bytes: Uint8Array\n source: 'embedded' | 'link'\n}\n\n/** How a linked file is read: `resources/read` on the app's OWN server (the connection's). */\nexport type AppResourceReader = (\n server: string,\n uri: string,\n options: { signal?: AbortSignal; maxBytes: number },\n) => Promise<{ mimeType?: string; bytes: Uint8Array }>\n\n/**\n * The bytes of a checked file: an embedded one as it came; a linked one read from `server` -\n * the app's own - through `read` (never a fetch of its URI), at most `maxBytes`, and the type the\n * SERVER gives it judged again (an app cannot pass a page off as a text file through a link).\n * Throws an `McpAppRpcError` for the app: no reader, a failed read, a refused type, too large.\n */\nexport const resolveAppDownload = async (\n file: AppDownload,\n server: string,\n read: AppResourceReader | undefined,\n signal?: AbortSignal,\n maxBytes: number = MCP_APP_MAX_DOWNLOAD_BYTES,\n): Promise<AppReadyDownload> => {\n if (file.kind === 'embedded') {\n return {\n name: file.name,\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n bytes: file.bytes,\n source: 'embedded',\n }\n }\n if (!read) throw new McpAppRpcError(MCP_APP_REFUSED, 'This host cannot read a linked file')\n let got: { mimeType?: string; bytes: Uint8Array }\n try {\n got = await read(server, file.uri, { ...(signal ? { signal } : {}), maxBytes })\n } catch (err) {\n const why = err instanceof Error ? err.message : String(err)\n throw new McpAppRpcError(MCP_APP_REFUSED, `Invalid content: ${why.slice(0, 200)}`)\n }\n if (!(got?.bytes instanceof Uint8Array)) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Invalid content: no bytes')\n }\n if (got.bytes.length > maxBytes) {\n throw new McpAppRpcError(INVALID_PARAMS, `Invalid content: larger than ${maxBytes} bytes`)\n }\n const mimeType = appMimeTypeOf(got.mimeType) ?? file.mimeType\n const refused = appDownloadRefusal(file.name, mimeType)\n if (refused) throw new McpAppRpcError(INVALID_PARAMS, `Policy violation: ${refused}`)\n return { name: file.name, ...(mimeType ? { mimeType } : {}), bytes: got.bytes, source: 'link' }\n}\n\n/**\n * The error an app is told when the agent did not answer its sampling request: the core's\n * `AppSamplingError` carries its JSON-RPC code (`-1`: the user said no, `-32602`: not a request\n * this host takes, `-32000`: too many); anything else is a refusal.\n */\nexport const appSamplingErrorOf = (err: unknown): McpAppRpcError => {\n if (err instanceof McpAppRpcError) return err\n const rpc = (err as { rpcCode?: unknown } | null)?.rpcCode\n const message = (err instanceof Error ? err.message : String(err)).slice(0, 300)\n return err instanceof Error && err.name === 'AppSamplingError' && typeof rpc === 'number'\n ? new McpAppRpcError(rpc, message)\n : new McpAppRpcError(MCP_APP_REFUSED, message)\n}\n\n/** What `saveAppFile` uses of the page (passed in: this module touches no DOM by itself). */\nexport interface AppFileSaverEnv {\n document: { createElement: (tag: 'a') => HTMLAnchorElement; body: { append: (n: Node) => void } }\n URL: { createObjectURL: (blob: Blob) => string; revokeObjectURL: (url: string) => void }\n setTimeout: (fn: () => void, ms: number) => unknown\n}\n\n/**\n * Save a checked file the user agreed to: a `Blob` of type `application/octet-stream` (the\n * browser never renders or sniffs it as a page), a `blob:` URL of THIS page, an `<a download>`\n * made here and clicked once. No navigation, no `data:` or `javascript:` URL, nothing of the app\n * in the page; the URL is revoked a minute later.\n */\nexport const saveAppFile = (\n file: { name: string; bytes: Uint8Array },\n env: AppFileSaverEnv,\n): void => {\n const blob = new Blob([file.bytes as BlobPart], { type: 'application/octet-stream' })\n const url = env.URL.createObjectURL(blob)\n const a = env.document.createElement('a')\n a.href = url\n a.download = appFileNameOf(file.name)\n a.rel = 'noopener'\n a.style.display = 'none'\n env.document.body.append(a)\n a.click()\n a.remove()\n env.setTimeout(() => env.URL.revokeObjectURL(url), 60_000)\n}\n\n// ── An app on an origin of its own: the sandbox proxy (opt-in) ──────────────────────────────\n//\n// The specification's web-host model: the app is not framed by a `srcdoc` of ours but by a page\n// the host serves on ANOTHER origin (`./mcp-app-sandbox`), so the app gets that origin - storage,\n// cookies, a real `Origin` on its requests - and never the page's. From the page down:\n//\n// your page ── <iframe sandbox=\"allow-scripts allow-same-origin\" srcdoc=SHELL> (your origin)\n// SHELL: no script (`script-src 'none'`); `frame-src` = the proxy's exact URL\n// └─ <iframe sandbox=\"allow-scripts allow-same-origin\" src=PROXY> (the sandbox origin)\n// PROXY: the app's policy as a header; relays messages\n// └─ the app, written into a frame of the proxy (the sandbox origin)\n//\n// The app is same-origin with the proxy and can reach into it - make it navigate, run code in it.\n// So the guards are what the app cannot reach: the frames' sandbox flags (drawn on YOUR side,\n// cross-origin to the app), the shell's `frame-src`, which pins the proxy's frame to its one URL\n// (any other navigation of it is refused, so nothing leaves for an origin the app did not\n// declare), the policy in that URL's PATH (which the pin covers; a query would not be), and the\n// page's checks below: messages only from the proxy's window AND the sandbox origin, posted to\n// that origin only, one handshake. A second `sandbox-proxy-ready` means the proxy was loaded again\n// - by the app - and the app is stopped. Without a sandbox URL, or when its page does not answer,\n// the app runs in the opaque frame above: the stricter of the two.\n\n/** `<AgentChat appSandbox>` / `useMcpAppHost({ sandbox })`. */\nexport interface McpAppSandboxOptions {\n /**\n * The sandbox page's base URL on another origin you serve (`mcpAppSandboxResponse` of the\n * `./mcp-app-sandbox` entry), e.g. `https://apps.example.com/sandbox/v1`; an app's frame loads\n * `<url>/<policy>`. `{server}` in the host name gives each server an origin of its own\n * (`https://{server}.apps.example.com/sandbox/v1`; the server's name must be a DNS label - it\n * needs a wildcard certificate). `https://` only; `http://` on `localhost` / `127.0.0.1`.\n */\n url: string\n /** How long a frame waits for the page's handshake before it falls back (default 5000 ms). */\n timeoutMs?: number\n}\n\n/** Why an app runs in the opaque frame although a sandbox URL is set. */\nexport type McpAppSandboxReason =\n | 'invalid'\n | 'insecure'\n | 'same-origin'\n | 'no-page-origin'\n | 'server-name'\n | 'too-many-origins'\n | 'no-answer'\n\nexport type McpAppSandboxTarget =\n { ok: true; origin: string; base: string } | { ok: false; reason: McpAppSandboxReason }\n\n/** The placeholder for the server's name in `McpAppSandboxOptions.url`. */\nexport const MCP_APP_SANDBOX_SERVER = '{server}'\nexport const MCP_APP_SANDBOX_TIMEOUT_MS = 5000\n/** After the shell has loaded (the proxy loaded or failed), the handshake gets this much longer. */\nexport const MCP_APP_SANDBOX_GRACE_MS = 1000\n/**\n * The sandbox flags of the shell's frame and of the proxy's: scripts and an origin - the shell\n * must keep YOUR origin (else the proxy below it would get an opaque one) and runs no script; the\n * proxy is on the sandbox origin. Nothing else: no navigation, popup, form, modal, download.\n */\nexport const MCP_APP_SANDBOX_FRAME_TOKENS = 'allow-scripts allow-same-origin'\n\nconst DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/\n// CSP cannot name an IPv6 literal (`[::1]`): the proxy's frame could not be pinned.\nconst LOOPBACK_HOSTS = ['localhost', '127.0.0.1']\n// What a `frame-src` source expression's path may hold, and a URL keeps as it is.\nconst SAFE_PATH = /^\\/[A-Za-z0-9\\-._~/%]*$/\n\nconst no = (reason: McpAppSandboxReason): McpAppSandboxTarget => ({ ok: false, reason })\n\n/**\n * Where an app of `server` runs, for a page on `pageOrigin`: the sandbox's origin and base URL,\n * or why not. Refused: not a URL; credentials, a query or a fragment; not `https://` (`http://`\n * only on `localhost` / `127.0.0.1`); a path a policy cannot name; `{server}` anywhere but the\n * host name, more than once, or a server name that is not a lowercase DNS label; a page without\n * an origin; and the sandbox on the PAGE'S OWN origin - `allow-same-origin` there would hand the\n * app your storage and the key vault.\n */\nexport const mcpAppSandboxTarget = (\n options: McpAppSandboxOptions | undefined,\n server: string,\n pageOrigin: string | undefined,\n): McpAppSandboxTarget => {\n const template = options?.url\n if (typeof template !== 'string' || template.length === 0 || template.length > 2048) {\n return no('invalid')\n }\n const parts = template.split(MCP_APP_SANDBOX_SERVER)\n if (parts.length > 2) return no('invalid')\n let raw = template\n if (parts.length === 2) {\n const authority = /^[a-z][a-z0-9+.-]*:\\/\\/([^/?#]*)/i.exec(template)?.[1] ?? ''\n if (!authority.replace(/:\\d*$/, '').includes(MCP_APP_SANDBOX_SERVER)) return no('invalid')\n if (typeof server !== 'string' || !DNS_LABEL.test(server)) return no('server-name')\n raw = template.replace(MCP_APP_SANDBOX_SERVER, server)\n }\n if (/[?#\\s]/.test(raw)) return no('invalid')\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n return no('invalid')\n }\n const loopback = LOOPBACK_HOSTS.includes(url.hostname)\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return no('insecure')\n if (url.username || url.password || !url.hostname) return no('invalid')\n if (!url.hostname.split('.').every((label) => DNS_LABEL.test(label))) {\n return no(parts.length === 2 ? 'server-name' : 'invalid')\n }\n if (!SAFE_PATH.test(url.pathname)) return no('invalid')\n if (!pageOrigin || pageOrigin === 'null') return no('no-page-origin')\n if (url.origin === pageOrigin) return no('same-origin')\n return { ok: true, origin: url.origin, base: `${url.origin}${url.pathname.replace(/\\/+$/, '')}` }\n}\n\n/** The proxy page's URL for an app's declared origins (`<base>/<policy>`), or none if too long. */\nexport const mcpAppSandboxProxyUrl = (\n base: string,\n csp?: Partial<McpAppCsp>,\n): string | undefined => {\n const granted = grantedAppCsp(csp)\n const token = mcpAppPolicyToken({\n connect: granted.connectDomains,\n resources: granted.resourceDomains,\n })\n return token ? `${base}/${token}` : undefined\n}\n\nconst PROXY_URL = /^https?:\\/\\/[A-Za-z0-9.-]+(?::\\d{1,5})?\\/[A-Za-z0-9\\-._~/%]*$/\n\n/**\n * The policy of the shell: no script at all, and frames from the proxy's exact URL only - a\n * `frame-src` with a path matches that path and nothing else (the query is not part of the\n * match), so the proxy's frame can never be navigated anywhere else.\n */\nexport const mcpAppSandboxShellCsp = (proxyUrl: string): string =>\n [\n \"default-src 'none'\",\n \"script-src 'none'\",\n \"style-src 'unsafe-inline'\",\n `frame-src ${proxyUrl}`,\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n ].join('; ')\n\n/**\n * What goes into the OUTER frame's `srcdoc` in sandbox mode: the shell - its policy first, one\n * frame of the proxy page, no script, nothing of the app. Give the outer `<iframe>`\n * `sandbox={MCP_APP_SANDBOX_FRAME_TOKENS}` and nothing else. Throws on a URL that is not a proxy\n * URL this package builds (`mcpAppSandboxProxyUrl`).\n */\nexport const buildMcpAppSandboxShell = (proxyUrl: string): string => {\n if (!PROXY_URL.test(proxyUrl)) throw new Error('not a sandbox proxy URL')\n return (\n '<!doctype html><html><head>' +\n cspMetaTag(mcpAppSandboxShellCsp(proxyUrl)) +\n '<style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n 'iframe{display:block;border:0;width:100%;height:100%}</style></head><body>' +\n `<iframe id=\"proxy\" sandbox=\"${MCP_APP_SANDBOX_FRAME_TOKENS}\" referrerpolicy=\"no-referrer\" ` +\n `src=\"${escapeAttribute(proxyUrl)}\"></iframe></body></html>`\n )\n}\n\n/** What one message from the proxy's frame is, for the page (`McpAppSandboxLink.receive`). */\nexport type McpAppSandboxInput = 'drop' | 'ready' | 'broken' | 'app'\n\nexport interface McpAppSandboxLinkOptions {\n /** The sandbox origin (`mcpAppSandboxTarget(…).origin`). */\n origin: string\n /** The app, as read from its server: sent once, on the proxy's first ready. */\n html: string\n csp?: Partial<McpAppCsp>\n /** Post to the proxy's window. Always called with the sandbox origin as the target - never `*`. */\n post: (message: unknown, targetOrigin: string) => void\n}\n\n/**\n * The page's side of the sandbox proxy, without the DOM: which messages are the proxy's, the\n * handshake, and every post to the sandbox origin. A message is the proxy's only when it comes\n * from the proxy's window (`event.source`) AND from the sandbox origin (`event.origin`). The\n * first `sandbox-proxy-ready` is answered with the app (`sandbox-resource-ready`); another one\n * means the proxy page was loaded again - by the app - and the link breaks (`'broken'`: stop the\n * app). Every other `ui/notifications/sandbox-*` message is dropped; nothing reaches the bridge\n * (`'app'`) before the app was handed over.\n */\nexport class McpAppSandboxLink {\n private readonly o: McpAppSandboxLinkOptions\n private state: 'waiting' | 'loaded' | 'broken' | 'closed' = 'waiting'\n\n constructor(options: McpAppSandboxLinkOptions) {\n this.o = options\n }\n\n /** The proxy answered and was given the app. */\n get ready(): boolean {\n return this.state === 'loaded'\n }\n\n /** The proxy page was loaded a second time: the app must be stopped. */\n get broken(): boolean {\n return this.state === 'broken'\n }\n\n /** Whether a message event is the proxy's: its window, and the sandbox origin. */\n accepts(event: { source: unknown; origin: string }, proxy: unknown): boolean {\n return (\n proxy !== null &&\n proxy !== undefined &&\n event.source === proxy &&\n event.origin === this.o.origin\n )\n }\n\n receive(\n event: { source: unknown; origin: string; data: unknown },\n proxy: unknown,\n ): McpAppSandboxInput {\n if (this.state === 'broken' || this.state === 'closed' || !this.accepts(event, proxy)) {\n return 'drop'\n }\n const data = event.data\n if (isMcpAppSandboxMessage(data)) {\n const d = data as { jsonrpc?: unknown; method: string }\n if (d.jsonrpc !== '2.0' || d.method !== MCP_APP_SANDBOX_PROXY_READY) return 'drop'\n if (this.state === 'loaded') {\n this.state = 'broken'\n return 'broken'\n }\n this.state = 'loaded'\n const granted = grantedAppCsp(this.o.csp)\n this.o.post(\n {\n jsonrpc: '2.0',\n method: MCP_APP_SANDBOX_RESOURCE_READY,\n params: { html: this.o.html, csp: granted },\n },\n this.o.origin,\n )\n return 'ready'\n }\n return this.state === 'loaded' ? 'app' : 'drop'\n }\n\n /** Send a message to the app, through the proxy, to the sandbox origin. Nothing once broken. */\n post(message: unknown): void {\n if (this.state === 'loaded') this.o.post(message, this.o.origin)\n }\n\n close(): void {\n if (this.state !== 'broken') this.state = 'closed'\n }\n}\n","/**\n * The sandboxed frame's security core: what untrusted HTML (a file the agent wrote, later an\n * MCP App) is wrapped in before it reaches an `<iframe>`. Pure strings - no React, no DOM - so\n * every guard is unit-tested here and proved in a real browser by `e2e/files.spec.ts`.\n *\n * The boundary, in three layers:\n * 1. `sandbox` WITHOUT `allow-same-origin`: the document gets an opaque origin - no access to\n * the page's DOM, storage, IndexedDB (the key vault), cookies. No `allow-top-navigation`,\n * `allow-popups`, `allow-forms`, `allow-modals`, `allow-downloads` either.\n * 2. A Content-Security-Policy with no network source at all, given twice: as the first element\n * of the document itself, and by inheritance from the shell (3) - a `srcdoc` document takes\n * its parent's policy, which nothing inside the document can pre-empt.\n * 3. A shell document of ours between the page and the untrusted one. A frame may always\n * navigate ITSELF (`location = …`, a link, `<meta http-equiv=refresh>`): neither the sandbox\n * nor a document's own CSP stops that, and a navigation is a network request. The only thing\n * that does is the `frame-src` of the document that EMBEDS the frame - so we embed it in one\n * we wrote, whose policy says `frame-src 'none'`.\n */\n\nexport interface SandboxedDocumentOptions {\n /** Let the document's own inline scripts run (default false). */\n scripts?: boolean\n}\n\n/**\n * The policy of the framed document: nothing is fetched from anywhere. Inline styles, and\n * images / fonts / media the document carries inside itself (`data:`, `blob:`), are all it gets;\n * inline scripts only when asked for. `frame-src 'none'` is what stops the frame from navigating.\n */\nexport const sandboxedCsp = (scripts = false): string =>\n [\n \"default-src 'none'\",\n scripts ? \"script-src 'unsafe-inline'\" : \"script-src 'none'\",\n \"style-src 'unsafe-inline'\",\n 'img-src data: blob:',\n 'font-src data:',\n 'media-src data: blob:',\n \"connect-src 'none'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n \"webrtc 'block'\",\n ].join('; ')\n\n/**\n * The `sandbox` attribute: empty (everything off) or `allow-scripts`. Never\n * `allow-same-origin`, never a navigation, popup, form, modal or download token.\n */\nexport const sandboxTokens = (scripts = false): string => (scripts ? 'allow-scripts' : '')\n\n/** A string as the value of a double-quoted HTML attribute. */\nexport const escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\n/** A `<meta>` that carries a Content-Security-Policy. */\nexport const cspMetaTag = (policy: string): string =>\n `<meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\">`\n\nconst cspMeta = (scripts: boolean): string => cspMetaTag(sandboxedCsp(scripts))\n\n// A DOCTYPE token ends at the first \">\" whatever is inside it (the tokenizer's rule), so this is\n// exactly where the parser leaves it.\nconst DOCTYPE = /^[\\t\\n\\f\\r ]*<!doctype[^>]*>/i\n\n/**\n * The document with our policy as its FIRST element: right after a leading DOCTYPE (so the\n * page stays in standards mode), otherwise before everything. Nothing the document says can\n * come earlier - not its own `<meta>`, not a `<base>`, not a script before `<html>` - and a\n * later policy of its own can only narrow ours.\n */\nexport const withCspFirst = (html: string, scripts = false): string =>\n withPolicyFirst(html, sandboxedCsp(scripts))\n\n/** `withCspFirst` with a policy of the caller's (an MCP App's, built by `mcpAppCsp`). */\nexport const withPolicyFirst = (html: string, policy: string): string => {\n const doctype = DOCTYPE.exec(html)?.[0] ?? ''\n return `${doctype}${cspMetaTag(policy)}${html.slice(doctype.length)}`\n}\n\n/**\n * What goes into the outer frame's `srcdoc`: the shell (ours: the policy, and one inner frame\n * that fills it) carrying the untrusted document, escaped, as the inner frame's `srcdoc`.\n * Give the OUTER `<iframe>` the same `sandboxTokens(scripts)`.\n */\nexport const buildSandboxedDocument = (\n html: string,\n { scripts = false }: SandboxedDocumentOptions = {},\n): string =>\n '<!doctype html><html><head>' +\n cspMeta(scripts) +\n '<style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n 'iframe{display:block;border:0;width:100%;height:100%}</style></head><body>' +\n `<iframe sandbox=\"${sandboxTokens(scripts)}\" referrerpolicy=\"no-referrer\" ` +\n `srcdoc=\"${escapeAttribute(withCspFirst(html, scripts))}\"></iframe></body></html>`\n\n/** HTML above this many characters is not framed at all - it is shown as source. */\nexport const HTML_PREVIEW_MAX_CHARS = 1_000_000\n\nconst ASSET_ATTR = /\\b(?:src|href)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'>]+))/gi\n\n/**\n * The files a document links to by a relative path (`style.css`, `./app.js`, `img/a.png`): the\n * preview does not load them, and says so. A hint for the user, not a guard - the policy is\n * what keeps them from loading.\n */\nexport const linkedFilesOf = (html: string, max = 4): string[] => {\n const found: string[] = []\n for (const m of html.matchAll(ASSET_ATTR)) {\n const ref = (m[1] ?? m[2] ?? m[3] ?? '').trim()\n if (!ref || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i.test(ref)) continue\n if (!found.includes(ref)) found.push(ref)\n if (found.length >= max) break\n }\n return found\n}\n\n/** A piece of HTML source, by what it is (for colouring the Source view). */\nexport interface SourceToken {\n kind: 'text' | 'tag' | 'attr' | 'string' | 'comment'\n text: string\n}\n\nconst RAW_TEXT = /^<(script|style|textarea|title)\\b/i\n\n/**\n * Split HTML source into coloured pieces. Lossless: the pieces joined are the input. It only\n * decides colours - the result is rendered as text nodes, never as markup.\n */\nexport const tokenizeHtml = (source: string): SourceToken[] => {\n const out: SourceToken[] = []\n const push = (kind: SourceToken['kind'], text: string) => {\n if (!text) return\n const last = out[out.length - 1]\n if (last && last.kind === kind) last.text += text\n else out.push({ kind, text })\n }\n let i = 0\n const n = source.length\n while (i < n) {\n const lt = source.indexOf('<', i)\n if (lt < 0) {\n push('text', source.slice(i))\n break\n }\n push('text', source.slice(i, lt))\n i = lt\n if (source.startsWith('<!--', i)) {\n const end = source.indexOf('-->', i + 4)\n const stop = end < 0 ? n : end + 3\n push('comment', source.slice(i, stop))\n i = stop\n continue\n }\n const open = /^<[!/?]?[a-zA-Z][^\\s/>]*/.exec(source.slice(i, i + 80))\n if (!open) {\n push('text', '<')\n i += 1\n continue\n }\n push('tag', open[0])\n const raw = RAW_TEXT.exec(open[0])?.[1].toLowerCase()\n i += open[0].length\n // Inside the tag, up to its \">\".\n while (i < n && source[i] !== '>') {\n const c = source[i]\n if (c === '\"' || c === \"'\") {\n const end = source.indexOf(c, i + 1)\n const stop = end < 0 ? n : end + 1\n push('string', source.slice(i, stop))\n i = stop\n } else if (/[^\\s=/>\"']/.test(c)) {\n const name = /^[^\\s=/>\"']+/.exec(source.slice(i, i + 200))?.[0] ?? c\n // After \"=\" it is an unquoted value; otherwise a name.\n const before = out[out.length - 1]\n push(before?.kind === 'text' && before.text.endsWith('=') ? 'string' : 'attr', name)\n i += name.length\n } else {\n push(c === '/' ? 'tag' : 'text', c)\n i += 1\n }\n }\n if (i < n) {\n push('tag', '>')\n i += 1\n }\n if (raw) {\n // The content of <script> / <style> is not markup: plain, up to its closing tag.\n const close = source.toLowerCase().indexOf(`</${raw}`, i)\n const stop = close < 0 ? n : close\n push('text', source.slice(i, stop))\n i = stop\n }\n }\n return out\n}\n","/**\n * MCP Apps: what the host (the page, `mcp-app.ts`) and the sandbox proxy (a page on ANOTHER\n * origin, `mcp-app-sandbox.ts`) must agree on - the app's Content-Security-Policy, the policy as a\n * path segment of the proxy's URL, and the names of the sandbox messages. Pure code with NO\n * imports at all: the proxy's server bundles it without React or the core (a Worker), so the\n * origin rule below is a copy of the core's `mcpAppOrigin`, and `tests/apps-sandbox.test.ts`\n * holds the two to the same answers.\n */\n\n/** The proxy tells the host it can take the app (Sandbox → Host; content-free). */\nexport const MCP_APP_SANDBOX_PROXY_READY = 'ui/notifications/sandbox-proxy-ready'\n/** The host hands the proxy the app's HTML (Host → Sandbox), once. */\nexport const MCP_APP_SANDBOX_RESOURCE_READY = 'ui/notifications/sandbox-resource-ready'\n\n/** The specification reserves these between a host and its proxy: never relayed to or from an app. */\nexport const isMcpAppSandboxMessage = (data: unknown): boolean =>\n typeof data === 'object' &&\n data !== null &&\n typeof (data as { method?: unknown }).method === 'string' &&\n (data as { method: string }).method.startsWith('ui/notifications/sandbox-')\n\n/** The origins an app's policy grants, each already an origin (`mcpAppPolicyOrigin`). */\nexport interface McpAppPolicyOrigins {\n /** `fetch` / XHR / WebSocket (`connect-src`). */\n connect: string[]\n /** Scripts, styles, images, fonts, media. */\n resources: string[]\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it. Nested frames, workers, plugins, forms and `<base>`\n * are refused whatever was declared (a frame the app may embed would also be a place it may\n * navigate itself to). The lists must already be checked origins: nothing here re-checks them.\n */\nexport const mcpAppPolicy = ({ connect, resources }: McpAppPolicyOrigins): string => {\n const from = resources.length > 0 ? ` ${resources.join(' ')}` : ''\n return [\n \"default-src 'none'\",\n `script-src 'unsafe-inline'${from}`,\n `style-src 'unsafe-inline'${from}`,\n `img-src data: blob:${from}`,\n `font-src data:${from}`,\n `media-src data: blob:${from}`,\n connect.length > 0 ? `connect-src ${connect.join(' ')}` : \"connect-src 'none'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n \"webrtc 'block'\",\n ].join('; ')\n}\n\n// ── The origin rule: a COPY of the core's `mcpAppOrigin` (src/mcp/apps.ts) ──────────────────\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst HOST = `(?:\\\\*\\\\.)?${LABEL}(?:\\\\.${LABEL})*`\nconst PORT = '(?::\\\\d{1,5})?'\nconst SECURE_ORIGIN = new RegExp(`^(?:https|wss)://${HOST}${PORT}$`)\nconst LOOPBACK_ORIGIN = new RegExp(`^(?:http|ws)://(?:localhost|127\\\\.0\\\\.0\\\\.1|\\\\[::1\\\\])${PORT}$`)\n\n/**\n * One declared CSP entry as a source expression a policy may carry, or `undefined`: only an\n * origin (`https://` / `wss://`, a `*.` wildcard over at least two labels, or `http://` /\n * `ws://` on loopback). The same answers as the core's `mcpAppOrigin`, for the proxy's server.\n */\nexport const mcpAppPolicyOrigin = (entry: unknown): string | undefined => {\n if (typeof entry !== 'string' || entry.length > 300) return undefined\n const value = entry.trim().toLowerCase().replace(/\\/$/, '')\n if (SECURE_ORIGIN.test(value)) {\n const host = value.replace(/^[a-z]+:\\/\\//, '').replace(/:\\d+$/, '')\n if (host.startsWith('*.') && !host.slice(2).includes('.')) return undefined\n return value\n }\n return LOOPBACK_ORIGIN.test(value) ? value : undefined\n}\n\n// ── The policy in the proxy's URL ────────────────────────────────────────────────────────────\n\n/** At most this many origins per list (the core's `MCP_APP_MAX_DOMAINS`). */\nexport const MCP_APP_POLICY_MAX_ORIGINS = 32\n/** A policy token longer than this is not put in a URL: the app runs without its own origin. */\nexport const MCP_APP_POLICY_TOKEN_MAX_CHARS = 4096\n\nconst B64URL = /^[A-Za-z0-9_-]+$/\n\n/**\n * The policy as one path segment (base64url of `{\"c\":[…],\"r\":[…]}`), or `undefined` when it does\n * not fit. It is in the PATH, not the query, because a `frame-src` source expression matches a\n * path exactly and ignores the query: the host pins the proxy's frame to this one URL, so nothing\n * inside the frame can load the proxy page with a policy of its choosing.\n */\nexport const mcpAppPolicyToken = ({\n connect,\n resources,\n}: McpAppPolicyOrigins): string | undefined => {\n const json = JSON.stringify({ c: connect, r: resources })\n // Origins are ASCII; anything else is not a list of checked origins.\n if (/[^\\x20-\\x7e]/.test(json)) return undefined\n const token = btoa(json).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n return token.length <= MCP_APP_POLICY_TOKEN_MAX_CHARS ? token : undefined\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst originList = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value) || value.length > MCP_APP_POLICY_MAX_ORIGINS) return undefined\n const out: string[] = []\n for (const entry of value) {\n // Exactly an origin as the host writes it: checked, canonical, once.\n if (typeof entry !== 'string' || mcpAppPolicyOrigin(entry) !== entry || out.includes(entry)) {\n return undefined\n }\n out.push(entry)\n }\n return out\n}\n\n/**\n * The policy a token stands for, or `undefined` for anything that is not exactly what\n * `mcpAppPolicyToken` writes: base64url of an object with the two lists and nothing else, every\n * entry an origin by the rule above, no more than `MCP_APP_POLICY_MAX_ORIGINS` each, the\n * canonical encoding (one URL per policy).\n */\nexport const mcpAppPolicyOfToken = (token: unknown): McpAppPolicyOrigins | undefined => {\n if (\n typeof token !== 'string' ||\n token.length === 0 ||\n token.length > MCP_APP_POLICY_TOKEN_MAX_CHARS ||\n !B64URL.test(token)\n ) {\n return undefined\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(atob(token.replace(/-/g, '+').replace(/_/g, '/')))\n } catch {\n return undefined\n }\n if (!isObject(parsed)) return undefined\n const keys = Object.keys(parsed)\n if (keys.length !== 2 || !keys.includes('c') || !keys.includes('r')) return undefined\n const connect = originList(parsed.c)\n const resources = originList(parsed.r)\n if (!connect || !resources) return undefined\n const policy = { connect, resources }\n return mcpAppPolicyToken(policy) === token ? policy : undefined\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 ArrowUpIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M12 19V5\" />\n <path d=\"m5 12 7-7 7 7\" />\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\nexport const QuestionIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z\" />\n <path d=\"M9.6 8a2.5 2.5 0 0 1 4.8.8c0 1.7-2.4 2-2.4 3.4\" />\n <path d=\"M12 14.6h.01\" />\n </svg>\n)\n\nexport const ExternalIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M15 3h6v6\" />\n <path d=\"M10 14 21 3\" />\n <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\" />\n </svg>\n)\n\nexport const CodeIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"m8 7-5 5 5 5M16 7l5 5-5 5\" />\n </svg>\n)\n\nexport const FileTextIcon = ({ 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 3v6h6M8 13h8M8 17h6\" />\n </svg>\n)\n\nexport const TableIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M3 10h18M3 15h18M9 4v16M15 4v16\" />\n </svg>\n)\n\nexport const ImageIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <circle cx=\"9\" cy=\"10\" r=\"1.6\" />\n <path d=\"m4 18 5.5-5 4 3.5 2.5-2 4 3.5\" />\n </svg>\n)\n\nexport const ChevronUpIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"m6 15 6-6 6 6\" />\n </svg>\n)\n\nexport const LockIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"5\" y=\"11\" width=\"14\" height=\"9\" rx=\"2\" />\n <path d=\"M8 11V8a4 4 0 0 1 8 0v3\" />\n </svg>\n)\n\nexport const NoNetworkIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18M4 4l16 16\" />\n </svg>\n)\n\nexport const ExpandIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M8 3H4v4M16 3h4v4M8 21H4v-4M16 21h4v-4\" />\n </svg>\n)\n\n/** Four corners inward: leave full screen. */\nexport const ShrinkIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M4 8h4V4M20 8h-4V4M4 16h4v4M20 16h-4v4\" />\n </svg>\n)\n\n// ── MCP Apps ─────────────────────────────────────────────────────────────────\n\n/** A window: an app a server shipped. */\nexport const AppIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"3\" />\n <path d=\"M3 9h18M8 6h.01\" />\n </svg>\n)\n\nexport const MoreIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <circle cx=\"5\" cy=\"12\" r=\"1\" />\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"19\" cy=\"12\" r=\"1\" />\n </svg>\n)\n\nexport const ReloadIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M3 12a9 9 0 0 1 15.5-6.2L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.5 6.2L3 16M3 21v-5h5\" />\n </svg>\n)\n\n/** A side panel. */\nexport const PanelIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M14 4v16\" />\n </svg>\n)\n\nexport const EyeOffIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M10.6 5.1A9.8 9.8 0 0 1 12 5c6.4 0 10 7 10 7a17 17 0 0 1-3 3.8M6.5 6.6A16.6 16.6 0 0 0 2 12s3.6 7 10 7a9.7 9.7 0 0 0 5.3-1.6M3 3l18 18\" />\n </svg>\n)\n\nexport const MessageIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\" />\n </svg>\n)\n","import type { ReactNode } from 'react'\nimport type { AppRequestAnswerOptions, AppRequestView } from '../hooks/use-mcp-app-host.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { BotIcon, DownloadIcon, ExternalIcon, MessageIcon } from './icons.js'\n\nexport interface AppRequestPromptProps {\n /** Waiting requests (`useMcpAppHost().requests`; `<AgentChat mcpApps>` passes its own). */\n requests: AppRequestView[]\n /**\n * The user's answer (`useMcpAppHost().answer`): an accepted link is opened and an accepted file\n * saved on this click; `always` allows an app's sampling until the page is reloaded.\n */\n onAnswer: (id: string, accept: boolean, options?: AppRequestAnswerOptions) => void\n /** Render a request yourself (gets the built-in card as `fallback`). */\n renderRequest?: (request: AppRequestView, fallback: ReactNode) => ReactNode\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * Consent cards for what an MCP App asks the host to do besides calling a tool: open a link\n * (the address with its host highlighted - what the user should check - and opened only on\n * \"Open\", in a new tab without an opener or a referrer), put a message in the message box\n * (shown as the app's text; accepted, it is a draft the user still sends - never sent for them),\n * save a file (its sanitized name, type and size; saved by this page only on \"Save file\"), or\n * ask the agent's model for an answer (the app's messages and instructions as plain text,\n * exactly what the model would get, and how much it may write). They sit with the agent's own\n * consent cards and say they come from the APP.\n */\nexport const AppRequestPrompt = ({\n requests,\n onAnswer,\n renderRequest,\n labels,\n className,\n}: AppRequestPromptProps) => {\n const L = useLabels(labels)\n if (requests.length === 0) return null\n const actions = (accept: string, decline: string, id: string, always?: string) => (\n <div className=\"awr-approval__actions\">\n <button type=\"button\" className=\"awr-btn awr-btn--primary\" onClick={() => onAnswer(id, true)}>\n {accept}\n </button>\n {always && (\n <button\n type=\"button\"\n className=\"awr-btn\"\n onClick={() => onAnswer(id, true, { always: true })}\n >\n {always}\n </button>\n )}\n <button type=\"button\" className=\"awr-btn\" onClick={() => onAnswer(id, false)}>\n {decline}\n </button>\n </div>\n )\n return (\n <div className={['awr-approvals', className].filter(Boolean).join(' ')} role=\"alert\">\n {requests.map((r) => {\n let card: ReactNode\n if (r.kind === 'link' && r.link) {\n card = (\n <div key={r.id} className=\"awr-approval awr-approval--app\" data-app={r.appId}>\n <div className=\"awr-approval__head\">\n <ExternalIcon size={14} className=\"awr-approval__icon\" />\n <span>{L.appLinkLead(r.server)}</span>\n </div>\n <p className=\"awr-approval__url\">\n {r.link.scheme}\n <b>{r.link.host}</b>\n {r.link.rest}\n </p>\n <p className=\"awr-approval__from\">{L.appLinkNote}</p>\n {actions(L.appLinkOpen, L.appCancel, r.id)}\n </div>\n )\n } else if (r.kind === 'download' && r.download) {\n const d = r.download\n card = (\n <div\n key={r.id}\n className=\"awr-approval awr-approval--app awr-approval--download\"\n data-app={r.appId}\n >\n <div className=\"awr-approval__head\">\n <DownloadIcon size={14} className=\"awr-approval__icon\" />\n <span>{L.appDownloadLead(r.server)}</span>\n </div>\n <p className=\"awr-approval__file\">\n <b className=\"awr-approval__filename\">{d.name}</b>\n <span className=\"awr-approval__filemeta\">\n {L.appDownloadType(d.mimeType)} · {L.appDownloadSize(d.size)}\n </span>\n </p>\n <p className=\"awr-approval__from\">\n {L.appDownloadSource(d.source, r.server)} {L.appDownloadNote}\n </p>\n {actions(L.appDownloadSave, L.appCancel, r.id)}\n </div>\n )\n } else if (r.kind === 'sampling' && r.sampling) {\n const s = r.sampling\n card = (\n <div\n key={r.id}\n className=\"awr-approval awr-approval--app awr-approval--sampling\"\n data-app={r.appId}\n >\n <div className=\"awr-approval__head\">\n <BotIcon size={14} className=\"awr-approval__icon\" />\n <span>{L.appSamplingLead(r.server)}</span>\n </div>\n <div className=\"awr-approval__sampling\">\n {s.systemPrompt && (\n <div className=\"awr-approval__turn awr-approval__turn--system\">\n <span className=\"awr-approval__role\">{L.appSamplingSystem}</span>\n <p className=\"awr-approval__quote\">{s.systemPrompt}</p>\n </div>\n )}\n {s.messages.map((m, i) => (\n <div key={i} className={`awr-approval__turn awr-approval__turn--${m.role}`}>\n <span className=\"awr-approval__role\">{L.appSamplingRole(m.role)}</span>\n {m.text && <p className=\"awr-approval__quote\">{m.text}</p>}\n {m.images.length > 0 && (\n <p className=\"awr-approval__from\">{L.appSamplingImages(m.images.length)}</p>\n )}\n </div>\n ))}\n </div>\n <p className=\"awr-approval__from\">\n {L.appSamplingTokens(s.maxTokens, s.requestedMaxTokens)} {L.appSamplingNote}\n </p>\n {actions(L.appSamplingAllow, L.appSamplingDeny, r.id, L.appSamplingAlways)}\n </div>\n )\n } else {\n card = (\n <div key={r.id} className=\"awr-approval awr-approval--app\" data-app={r.appId}>\n <div className=\"awr-approval__head\">\n <MessageIcon size={14} className=\"awr-approval__icon\" />\n <span>{L.appMessageLead(r.server)}</span>\n </div>\n <blockquote className=\"awr-approval__quote\">{r.text}</blockquote>\n <p className=\"awr-approval__from\">{L.appMessageNote}</p>\n {actions(L.appMessageAccept, L.appMessageDiscard, r.id)}\n </div>\n )\n }\n return renderRequest ? <div key={r.id}>{renderRequest(r, card)}</div> : card\n })}\n </div>\n )\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { McpAppResource } from '@dudko.dev/agent-web'\nimport type { McpAppHost } from '../hooks/use-mcp-app-host.js'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport {\n APP_DEFAULT_HEIGHT,\n APP_MAX_HEIGHT,\n appGestureOf,\n buildMcpAppDocument,\n buildMcpAppSandboxShell,\n clampAppHeight,\n MCP_APP_SANDBOX_FRAME_TOKENS,\n MCP_APP_SANDBOX_GRACE_MS,\n MCP_APP_SANDBOX_TIMEOUT_MS,\n McpAppBridge,\n mcpAppHostCapabilities,\n McpAppSandboxLink,\n mcpAppSandboxProxyUrl,\n mcpAppSandboxTarget,\n type McpAppDisplayMode,\n type McpAppSandboxReason,\n} from '../mcp-app.js'\nimport type { AppView } from '../types.js'\nimport { errMessage } from '../util.js'\nimport {\n AlertIcon,\n AppIcon,\n EyeOffIcon,\n LockIcon,\n MoreIcon,\n PanelIcon,\n ReloadIcon,\n ShrinkIcon,\n SpinnerIcon,\n ToolIcon,\n XIcon,\n} from './icons.js'\n\n/** Who the app is told it talks to (`hostInfo` of `ui/initialize`). */\nconst HOST_INFO = { name: '@dudko.dev/agent-web-react', version: '1' }\n\n/** At most this many of the app's calls are listed under its frame. */\nconst MAX_LISTED_CALLS = 12\n\nexport interface McpAppFrameProps {\n /** The app (an entry of `message.apps`). */\n app: AppView\n /** The host: reads the app, asks the user about its requests (`useMcpAppHost`). */\n host: McpAppHost\n /** `'inline'` under the answer (default), or `'panel'`: it fills the box it is given. */\n variant?: 'inline' | 'panel'\n /** The colour scheme the app is told (`hostContext.theme`). */\n theme?: 'light' | 'dark'\n /** Start folded to one line (default false). */\n defaultCollapsed?: boolean\n /** Adds \"Open in panel\" (a header button and a menu item). */\n onOpenPanel?: () => void\n /** In the panel: the close button (the app goes back into the chat). */\n onClosePanel?: () => void\n /** The tools the app ran, listed under the frame (default true). */\n showCalls?: boolean\n /**\n * Offer the app `fullscreen` besides `inline` (`hostContext.availableDisplayModes`), read when\n * the frame starts. Granted only to an app that declared it, right after the user acted inside\n * its frame, and not while it waits for the user: it then fills the chat panel (the viewport\n * on a narrow one) in the host's chrome - \"App from server …\", Exit full screen, Esc - with the\n * focus kept inside. Default false: an app stays inline.\n */\n allowFullscreen?: boolean\n labels?: AgentLabelsOverride\n className?: string\n}\n\ntype Loaded = { resource: McpAppResource } | { error: string } | { unavailable: true }\n\n// useLayoutEffect warns during server rendering; full screen only exists in the browser.\nconst useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect\n\n/** Where a full-screen app is drawn: over the chat panel, or (undefined) the whole viewport. */\ntype FullRect = { top: number; left: number; width: number; height: number } | undefined\n\nconst userActivation = (): boolean | undefined =>\n typeof navigator === 'undefined'\n ? undefined\n : (navigator as { userActivation?: { isActive?: boolean } }).userActivation?.isActive\n\n/** Where an app runs: an opaque frame of ours, or the sandbox page on its own origin. */\ntype Placement =\n { mode: 'opaque'; reason?: McpAppSandboxReason } | { mode: 'origin'; origin: string; url: string }\n\n// Sandbox origins whose page did not answer, for the life of this page: the next frame does not\n// wait for them again (its Reload tries again).\nconst silentSandboxes = new Set<string>()\nconst warned = new Set<string>()\nconst warnOnce = (key: string, text: string) => {\n if (warned.has(key)) return\n warned.add(key)\n console.warn(`[@dudko.dev/agent-web-react] ${text}`)\n}\nconst SANDBOX_WARNINGS: Record<McpAppSandboxReason, string> = {\n invalid: 'is not a URL a sandbox can be served at (no credentials, query or fragment)',\n insecure: 'is not https:// (http:// only on localhost / 127.0.0.1)',\n 'same-origin':\n \"is on this page's own origin - an app there would have your storage and the key vault\",\n 'no-page-origin': 'cannot be checked: this page has no origin of its own',\n 'server-name': 'has {server}, and this server name is not a lowercase DNS label',\n 'too-many-origins': 'cannot carry this app: it declares too many origins',\n 'no-answer': 'did not answer the handshake in time',\n}\n\nconst pageOrigin = (): string | undefined =>\n typeof location === 'undefined' ? undefined : location.origin\n\n/**\n * An MCP App inside chrome the host draws: \"App from server “travel” · sandboxed\", the host's\n * controls (panel, menu: reload / open in panel / hide) and the list of what the app ran - all\n * OUTSIDE the frame, where the app cannot paint over them. The app runs in the boundary\n * `mcp-app.ts` builds: an opaque origin - or, with `host.sandbox`, an origin of its own behind the\n * sandbox page (falling back to the opaque frame when that page does not answer) - network only\n * where its resource declared it, no navigation, and every request that does something (a tool\n * call, a link, a message) put to the user through the host. Its height is its wish, clamped to\n * 120 - 800 px.\n */\nexport const McpAppFrame = ({\n app,\n host,\n variant = 'inline',\n theme,\n defaultCollapsed = false,\n onOpenPanel,\n onClosePanel,\n showCalls = true,\n allowFullscreen = false,\n labels,\n className,\n}: McpAppFrameProps) => {\n const L = useLabels(labels)\n const [collapsed, setCollapsed] = useState(defaultCollapsed)\n const [menu, setMenu] = useState(false)\n const [reload, setReload] = useState(0)\n const [loaded, setLoaded] = useState<Loaded | undefined>()\n const [height, setHeight] = useState(APP_DEFAULT_HEIGHT)\n const [calls, setCalls] = useState<{ name: string; ok: boolean }[]>([])\n // The sandbox origin: gave up on it (`fallback`), the app reloaded its proxy (`broken`), the\n // handshake is done (`onOrigin`).\n const [fallback, setFallback] = useState<McpAppSandboxReason | undefined>()\n const [broken, setBroken] = useState(false)\n const [onOrigin, setOnOrigin] = useState(false)\n const shellLoaded = useRef<(() => void) | undefined>(undefined)\n // Full screen: the mode (state for the render, a ref for the bridge), the space it leaves in the\n // transcript, where it is drawn, and how the host takes it back (Esc, the button, a prompt).\n const [mode, setMode] = useState<McpAppDisplayMode>('inline')\n const modeRef = useRef<McpAppDisplayMode>('inline')\n const [holder, setHolder] = useState(0)\n const [fullRect, setFullRect] = useState<FullRect>()\n const leaveRef = useRef<(() => void) | undefined>(undefined)\n const rootRef = useRef<HTMLDivElement>(null)\n const exitRef = useRef<HTMLButtonElement>(null)\n const allowFullscreenRef = useRef(allowFullscreen)\n allowFullscreenRef.current = allowFullscreen\n const iframeRef = useRef<HTMLIFrameElement>(null)\n const bridgeRef = useRef<McpAppBridge | undefined>(undefined)\n const menuRef = useRef<HTMLDivElement>(null)\n const themeRef = useRef(theme)\n themeRef.current = theme\n const hostRef = useRef(host)\n hostRef.current = host\n // The app is known by its id: a host that hands a new object each render does not reload it.\n const appRef = useRef(app)\n appRef.current = app\n const live = !collapsed\n\n // Read the app from the server that declared it (cached by the connection).\n useEffect(() => {\n if (!live) return\n if (!hostRef.current.connected) {\n setLoaded({ unavailable: true })\n return\n }\n let gone = false\n setLoaded(undefined)\n hostRef.current.read(appRef.current).then(\n (resource) => {\n if (!gone) setLoaded({ resource })\n },\n (err) => {\n if (!gone) setLoaded({ error: errMessage(err) })\n },\n )\n return () => {\n gone = true\n }\n }, [live, host.connected, app.id, reload])\n\n const resource = loaded && 'resource' in loaded ? loaded.resource : undefined\n const sandboxUrl = host.sandbox?.url\n const timeoutMs = host.sandbox?.timeoutMs ?? MCP_APP_SANDBOX_TIMEOUT_MS\n const placement = useMemo<Placement | undefined>(() => {\n if (!resource) return undefined\n if (sandboxUrl === undefined) return { mode: 'opaque' }\n if (fallback) return { mode: 'opaque', reason: fallback }\n const target = mcpAppSandboxTarget({ url: sandboxUrl }, app.server, pageOrigin())\n if (!target.ok) return { mode: 'opaque', reason: target.reason }\n if (silentSandboxes.has(target.origin)) return { mode: 'opaque', reason: 'no-answer' }\n const url = mcpAppSandboxProxyUrl(target.base, resource.csp)\n if (!url) return { mode: 'opaque', reason: 'too-many-origins' }\n return { mode: 'origin', origin: target.origin, url }\n // `reload`: a reload asks again (an origin given up on may answer now).\n }, [resource, sandboxUrl, fallback, app.server, reload])\n const doc = useMemo(\n () =>\n !resource || !placement\n ? undefined\n : placement.mode === 'origin'\n ? buildMcpAppSandboxShell(placement.url)\n : buildMcpAppDocument(resource.html, resource.csp),\n [resource, placement],\n )\n\n // A sandbox URL this frame cannot use is said once, in the console, and the app runs opaque.\n useEffect(() => {\n const reason = placement?.mode === 'opaque' ? placement.reason : undefined\n if (reason && reason !== 'no-answer' && sandboxUrl !== undefined) {\n warnOnce(\n `${sandboxUrl}\\u0000${reason}`,\n `MCP Apps: the sandbox URL ${sandboxUrl} ${SANDBOX_WARNINGS[reason]}; apps run in the opaque sandbox.`,\n )\n }\n }, [placement, sandboxUrl])\n\n // The bridge: one per drawn frame, answering only that frame's window.\n useEffect(() => {\n const frame = iframeRef.current\n if (!live || !resource || !frame || !placement || broken) return\n const abort = new AbortController()\n const app = appRef.current\n const record = (name: string, ok: boolean) =>\n setCalls((list) => [...list, { name, ok }].slice(-MAX_LISTED_CALLS))\n const tool = hostRef.current.tool(app)\n // On its own origin: the proxy's window is the one frame in the shell (same origin as this\n // page), and every message to it goes to the sandbox origin.\n const proxyOf = (): Window | undefined => frame.contentWindow?.frames[0] ?? undefined\n const link =\n placement.mode === 'origin'\n ? new McpAppSandboxLink({\n origin: placement.origin,\n html: resource.html,\n csp: resource.csp,\n post: (message, targetOrigin) => proxyOf()?.postMessage(message, targetOrigin),\n })\n : undefined\n const fullscreenOffered = allowFullscreenRef.current\n // The host changes the mode and tells the app (`host-context-changed`); `inline` back is\n // always allowed, `fullscreen` only right after the user acted inside this frame and not\n // while the app waits for them (its prompt must never be under it).\n const show = (next: McpAppDisplayMode) => {\n if (next === modeRef.current) return\n if (next === 'fullscreen') {\n setHolder(Math.round(rootRef.current?.getBoundingClientRect().height ?? 0))\n }\n modeRef.current = next\n setMode(next)\n bridge.updateContext(\n next === 'inline'\n ? { displayMode: 'inline', containerDimensions: { maxHeight: APP_MAX_HEIGHT } }\n : { displayMode: next },\n )\n }\n leaveRef.current = () => show('inline')\n // A new bridge (a reload, another placement) is a new start: inline.\n setMode('inline')\n const host = hostRef.current\n const bridge = new McpAppBridge({\n post: link\n ? (message) => link.post(message)\n : (message) => frame.contentWindow?.postMessage(message, '*'),\n handlers: {\n callTool: async (name, args) => {\n try {\n const result = await hostRef.current.callTool(app, name, args, abort.signal)\n record(name, true)\n return result\n } catch (err) {\n record(name, false)\n throw err\n }\n },\n openLink: (link) => hostRef.current.openLink(app, link, abort.signal),\n message: (text) => hostRef.current.message(app, text, abort.signal),\n resize: (wish) => {\n if (variant === 'inline' && modeRef.current === 'inline') setHeight(clampAppHeight(wish))\n },\n displayMode: (requested) => {\n if (requested === 'inline') {\n show('inline')\n return 'inline'\n }\n const gesture = appGestureOf({\n focused: typeof document !== 'undefined' && document.activeElement === frame,\n activation: userActivation(),\n })\n if (\n requested !== 'fullscreen' ||\n !fullscreenOffered ||\n !gesture ||\n hostRef.current.isWaiting(app)\n ) {\n return modeRef.current\n }\n show('fullscreen')\n return 'fullscreen'\n },\n ...(host.downloadFile\n ? {\n downloadFile: (file) => {\n // The app waits for the user: their prompt is in the chat, not under the app.\n leaveRef.current?.()\n return hostRef.current.downloadFile!(app, file, abort.signal)\n },\n }\n : {}),\n ...(host.sample\n ? {\n sample: (params) => {\n leaveRef.current?.()\n return hostRef.current.sample!(app, params, abort.signal)\n },\n }\n : {}),\n },\n hostInfo: HOST_INFO,\n hostCapabilities: mcpAppHostCapabilities(resource.csp, {\n downloadFile: Boolean(host.downloadFile),\n sampling: Boolean(host.sample),\n }),\n hostContext: {\n toolInfo: {\n tool: {\n name: app.toolName,\n ...(tool?.description ? { description: tool.description } : {}),\n inputSchema: tool?.inputSchema ?? { type: 'object' },\n },\n },\n ...(themeRef.current ? { theme: themeRef.current } : {}),\n displayMode: 'inline',\n availableDisplayModes: fullscreenOffered ? ['inline', 'fullscreen'] : ['inline'],\n containerDimensions: { maxHeight: APP_MAX_HEIGHT },\n platform: 'web',\n ...(typeof navigator !== 'undefined' && navigator.language\n ? { locale: navigator.language }\n : {}),\n timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n },\n toolInput: app.input,\n ...(app.result\n ? { toolResult: app.result }\n : { cancelledReason: 'the result was too large to hand to the app' }),\n })\n bridgeRef.current = bridge\n // The sandbox page did not answer: the app runs in the opaque frame instead (stricter), and\n // the next frame does not wait for that origin again.\n const timers: ReturnType<typeof setTimeout>[] = []\n const giveUp = () => {\n if (!link || link.ready || link.broken || placement.mode !== 'origin') return\n silentSandboxes.add(placement.origin)\n warnOnce(\n `${placement.origin}\\u0000no-answer`,\n `MCP Apps: the sandbox page at ${placement.origin} ${SANDBOX_WARNINGS['no-answer']}; apps run in the opaque sandbox.`,\n )\n setFallback('no-answer')\n }\n if (link) {\n timers.push(setTimeout(giveUp, timeoutMs))\n // The shell's load waits for the proxy's: loaded (or failed) and still silent, it is not\n // coming.\n shellLoaded.current = () => timers.push(setTimeout(giveUp, MCP_APP_SANDBOX_GRACE_MS))\n }\n const onMessage = (event: MessageEvent) => {\n if (link) {\n // The proxy's window AND the sandbox origin, or nothing (`McpAppSandboxLink`).\n const input = link.receive(event, proxyOf())\n if (input === 'ready') setOnOrigin(true)\n else if (input === 'app') bridge.receive(event.data)\n else if (input === 'broken') {\n // The proxy page was loaded again (the app navigated it): stop the app.\n bridge.close()\n abort.abort()\n setBroken(true)\n }\n return\n }\n // Only the frame drawn here. The app's own window writing to the top directly, another\n // frame, or the page itself: none of them is this app.\n if (event.source !== frame.contentWindow) return\n bridge.receive(event.data)\n }\n window.addEventListener('message', onMessage)\n return () => {\n for (const t of timers) clearTimeout(t)\n shellLoaded.current = undefined\n window.removeEventListener('message', onMessage)\n bridge.teardown('the app was closed')\n bridge.close()\n link?.close()\n // Whatever the app still waits for (a prompt, a consent) is given up.\n abort.abort()\n bridgeRef.current = undefined\n leaveRef.current = undefined\n modeRef.current = 'inline'\n }\n }, [live, resource, reload, variant, app.id, placement, broken, timeoutMs])\n\n const fullscreen = mode === 'fullscreen' && live && !broken\n const waitingNow = host.isWaiting(app)\n\n // While the app waits for the user, it is not shown full screen: the prompt is in the chat.\n useEffect(() => {\n if (fullscreen && waitingNow) leaveRef.current?.()\n }, [fullscreen, waitingNow])\n\n // Full screen: over the chat panel (or the viewport on a phone), kept in place as the page\n // moves; Esc takes it back; the focus starts on the way back; the app is told its size.\n useIsoLayoutEffect(() => {\n if (!fullscreen) return\n const place = () => {\n // The chat panel, whatever its width; the whole viewport on a phone (or outside a chat).\n const chat = rootRef.current?.closest('.awr-chat')\n if (chat instanceof HTMLElement && window.innerWidth > 640) {\n const r = chat.getBoundingClientRect()\n setFullRect({ top: r.top, left: r.left, width: r.width, height: r.height })\n } else {\n setFullRect(undefined)\n }\n }\n place()\n window.addEventListener('resize', place)\n window.addEventListener('scroll', place, true)\n const chat = rootRef.current?.closest('.awr-chat')\n const ro =\n typeof ResizeObserver === 'undefined'\n ? undefined\n : new ResizeObserver(() => {\n place()\n const f = iframeRef.current?.getBoundingClientRect()\n if (f && f.width > 0 && f.height > 0) {\n bridgeRef.current?.updateContext({\n containerDimensions: { width: Math.round(f.width), height: Math.round(f.height) },\n })\n }\n })\n if (chat) ro?.observe(chat)\n if (iframeRef.current) ro?.observe(iframeRef.current)\n return () => {\n window.removeEventListener('resize', place)\n window.removeEventListener('scroll', place, true)\n ro?.disconnect()\n }\n }, [fullscreen])\n\n useEffect(() => {\n if (!fullscreen) return\n const before = document.activeElement\n exitRef.current?.focus()\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n e.preventDefault()\n leaveRef.current?.()\n }\n }\n document.addEventListener('keydown', onKey)\n return () => {\n document.removeEventListener('keydown', onKey)\n // Back where the user was: the app's frame, if they were in it.\n const frame = iframeRef.current\n if (frame && (before === frame || document.activeElement === document.body)) frame.focus()\n }\n }, [fullscreen])\n\n // A theme switch reaches an app that is running.\n useEffect(() => {\n if (theme) bridgeRef.current?.updateContext({ theme })\n }, [theme])\n\n // The menu closes on a click elsewhere, and on Escape.\n useEffect(() => {\n if (!menu) return\n const close = (e: Event) => {\n if (\n e instanceof KeyboardEvent\n ? e.key === 'Escape'\n : !menuRef.current?.contains(e.target as Node)\n ) {\n setMenu(false)\n }\n }\n document.addEventListener('pointerdown', close)\n document.addEventListener('keydown', close)\n return () => {\n document.removeEventListener('pointerdown', close)\n document.removeEventListener('keydown', close)\n }\n }, [menu])\n\n const doReload = () => {\n setMenu(false)\n leaveRef.current?.()\n setHeight(APP_DEFAULT_HEIGHT)\n if (sandboxUrl !== undefined) {\n const target = mcpAppSandboxTarget({ url: sandboxUrl }, app.server, pageOrigin())\n if (target.ok) silentSandboxes.delete(target.origin)\n }\n setFallback(undefined)\n setBroken(false)\n setOnOrigin(false)\n setReload((n) => n + 1)\n }\n\n if (collapsed) {\n return (\n <McpAppLine\n app={app}\n note={L.appHidden}\n action={L.appShow}\n onAction={() => setCollapsed(false)}\n labels={labels}\n className={className}\n />\n )\n }\n\n const waiting = waitingNow\n const panel = variant === 'panel'\n const sandboxed = placement?.mode === 'origin' && onOrigin\n const sandboxNote =\n placement?.mode === 'origin'\n ? onOrigin\n ? L.appSandboxOrigin(placement.origin)\n : undefined\n : placement?.reason\n ? L.appSandboxFallback(L.appSandboxReasons[placement.reason])\n : undefined\n const badge = (\n <span title={sandboxNote}>\n <LockIcon size={11} /> {sandboxed ? L.appSandboxedOrigin : L.appSandboxed}\n </span>\n )\n const body = !loaded ? (\n <div className=\"awr-frame__status\">\n <SpinnerIcon size={13} /> {L.appLoading}\n </div>\n ) : 'unavailable' in loaded ? (\n <div className=\"awr-frame__status awr-frame__status--error\" role=\"alert\">\n <AlertIcon size={13} /> {L.appUnavailable(app.server)}\n </div>\n ) : 'error' in loaded ? (\n <div className=\"awr-frame__status awr-frame__status--error\" role=\"alert\">\n <AlertIcon size={13} /> {L.appFailed(loaded.error)}\n </div>\n ) : broken ? (\n <div className=\"awr-frame__status awr-frame__status--error\" role=\"alert\">\n <AlertIcon size={13} /> {L.appSandboxBroken}\n </div>\n ) : (\n <div className=\"awr-frame__well\">\n {placement?.mode === 'origin' ? (\n <iframe\n // The shell (ours, this page's origin, no script) around the sandbox page.\n key={`${reload}:origin`}\n ref={iframeRef}\n className=\"awr-frame__iframe\"\n title={L.appFrameName(app.server)}\n sandbox={MCP_APP_SANDBOX_FRAME_TOKENS}\n referrerPolicy=\"no-referrer\"\n srcDoc={doc}\n onLoad={() => shellLoaded.current?.()}\n style={panel || fullscreen ? undefined : { height }}\n />\n ) : (\n <iframe\n // A reload is a new frame: a new window, a new bridge, the app from the start.\n key={`${reload}:opaque`}\n ref={iframeRef}\n className=\"awr-frame__iframe\"\n title={L.appFrameName(app.server)}\n sandbox=\"allow-scripts\"\n referrerPolicy=\"no-referrer\"\n srcDoc={doc}\n style={panel || fullscreen ? undefined : { height }}\n />\n )}\n </div>\n )\n const exit = (\n <button\n ref={exitRef}\n type=\"button\"\n className=\"awr-btn awr-frame__exit\"\n title={`${L.appFullscreenExit} (${L.appFullscreenKey})`}\n onClick={() => leaveRef.current?.()}\n >\n <ShrinkIcon size={14} /> {L.appFullscreenExit}{' '}\n <kbd className=\"awr-frame__key\">{L.appFullscreenKey}</kbd>\n </button>\n )\n // The focus stays inside while it is full screen: past either end, it comes round.\n const guard = (to: 'exit' | 'app') => (\n <span\n className=\"awr-frame__guard\"\n tabIndex={0}\n aria-hidden=\"true\"\n onFocus={() => (to === 'exit' ? exitRef.current : iframeRef.current)?.focus()}\n />\n )\n\n return (\n <>\n {fullscreen && (\n // The place the app had in the transcript, kept while it is shown full screen.\n <div className=\"awr-frame__holder\" style={{ height: holder }} aria-hidden=\"true\" />\n )}\n <div\n ref={rootRef}\n className={[\n 'awr-frame awr-frame--app',\n panel && 'awr-frame--panel',\n fullscreen && 'awr-frame--fullscreen',\n waiting && 'is-waiting',\n className,\n ]\n .filter(Boolean)\n .join(' ')}\n style={fullscreen && fullRect ? fullRect : undefined}\n data-app={app.id}\n data-display={fullscreen ? 'fullscreen' : 'inline'}\n data-sandbox={\n placement?.mode === 'origin' ? (onOrigin ? 'origin' : 'connecting') : placement?.mode\n }\n {...(fullscreen\n ? { role: 'dialog', 'aria-modal': true, 'aria-label': L.appFrom(app.server) }\n : {})}\n >\n {fullscreen ? guard('app') : null}\n <div className=\"awr-frame__head\">\n <AppIcon size={14} className=\"awr-frame__icon\" />\n {fullscreen ? (\n <div className=\"awr-frame__label\">\n <span className=\"awr-frame__titles\">\n <span className=\"awr-frame__title\">{L.appFrom(app.server)}</span>\n <span className=\"awr-frame__badges\">\n {badge} · {L.appFullscreenBadge}\n </span>\n </span>\n {waiting && <span className=\"awr-frame__state\">{L.appWaiting}</span>}\n </div>\n ) : panel ? (\n <div className=\"awr-frame__label\">\n <span className=\"awr-frame__titles\">\n <span className=\"awr-frame__title\">{L.appFrom(app.server)}</span>\n <span className=\"awr-frame__badges\">\n {badge} · {app.resourceUri}\n </span>\n </span>\n {waiting && <span className=\"awr-frame__state\">{L.appWaiting}</span>}\n </div>\n ) : (\n <div className=\"awr-frame__label\">\n <span className=\"awr-frame__title\">{L.appFrom(app.server)}</span>\n <span className=\"awr-frame__badges\">{badge}</span>\n {waiting && <span className=\"awr-frame__state\">{L.appWaiting}</span>}\n </div>\n )}\n {fullscreen ? (\n exit\n ) : panel ? (\n <>\n <button\n type=\"button\"\n className=\"awr-frame__btn\"\n aria-label={L.appReload}\n title={L.appReload}\n onClick={doReload}\n >\n <ReloadIcon size={15} />\n </button>\n {onClosePanel && (\n <button\n type=\"button\"\n className=\"awr-frame__btn\"\n aria-label={L.appClosePanel}\n title={L.appClosePanel}\n onClick={onClosePanel}\n >\n <XIcon size={15} />\n </button>\n )}\n </>\n ) : (\n <>\n {onOpenPanel && (\n <button\n type=\"button\"\n className=\"awr-frame__btn\"\n aria-label={L.appOpenPanel}\n title={L.appOpenPanel}\n onClick={onOpenPanel}\n >\n <PanelIcon size={15} />\n </button>\n )}\n <button\n type=\"button\"\n className={`awr-frame__btn${menu ? ' is-on' : ''}`}\n aria-label={L.appMenu}\n title={L.appMenu}\n aria-haspopup=\"menu\"\n aria-expanded={menu}\n onClick={() => setMenu((m) => !m)}\n >\n <MoreIcon size={15} />\n </button>\n </>\n )}\n </div>\n {menu && !panel && !fullscreen && (\n <div className=\"awr-frame__menu\" role=\"menu\" ref={menuRef}>\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"awr-frame__menuitem\"\n onClick={doReload}\n >\n <ReloadIcon size={14} /> {L.appReload}\n </button>\n {onOpenPanel && (\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"awr-frame__menuitem\"\n onClick={() => {\n setMenu(false)\n onOpenPanel()\n }}\n >\n <PanelIcon size={14} /> {L.appOpenPanel}\n </button>\n )}\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"awr-frame__menuitem\"\n onClick={() => {\n setMenu(false)\n setCollapsed(true)\n }}\n >\n <EyeOffIcon size={14} /> {L.appHide}\n </button>\n <div className=\"awr-frame__menusep\" />\n <p className=\"awr-frame__menunote\">{L.appServedBy(app.server, app.resourceUri)}</p>\n {sandboxNote && <p className=\"awr-frame__menunote\">{sandboxNote}</p>}\n </div>\n )}\n {body}\n {panel ? (\n <div className=\"awr-frame__foot\">\n <LockIcon size={11} />{' '}\n <span className=\"awr-frame__footmeta\">{L.appPanelNote(app.server)}</span>\n </div>\n ) : showCalls && calls.length > 0 ? (\n <div className=\"awr-frame__foot\">\n <ToolIcon size={11} />\n <span className=\"awr-frame__footmeta\">\n {L.appRan(\n calls.map((c) => (c.ok ? c.name : `${c.name} (${L.appRefused})`)).join(' · '),\n )}\n </span>\n </div>\n ) : null}\n {fullscreen ? guard('exit') : null}\n </div>\n </>\n )\n}\n\nexport interface McpAppLineProps {\n app: AppView\n /** What the line says after the title (\"hidden\", \"open in the panel\"). */\n note: ReactNode\n /** The button (\"Show\", \"Bring back\"). */\n action: ReactNode\n onAction: () => void\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/** An app folded to one line: where it was, and the button that brings it back. */\nexport const McpAppLine = ({ app, note, action, onAction, labels, className }: McpAppLineProps) => {\n const L = useLabels(labels)\n return (\n <div\n className={['awr-frame awr-frame--app awr-frame--line', className].filter(Boolean).join(' ')}\n data-app={app.id}\n >\n <div className=\"awr-frame__head\">\n <AppIcon size={14} className=\"awr-frame__icon\" />\n <div className=\"awr-frame__label\">\n <span className=\"awr-frame__title\">{L.appFrom(app.server)}</span>\n <span className=\"awr-frame__badges\">{note}</span>\n </div>\n <button type=\"button\" className=\"awr-btn awr-frame__show\" onClick={onAction}>\n {action}\n </button>\n </div>\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). Paste works in the message field and anywhere in the drop zone. 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 /**\n * Text to put in the message field as a draft - e.g. a message an MCP App asked to send that\n * the user accepted. Each new `id` appends its `text` (on a new line after what is there) and\n * focuses the field; it is never sent: the user sends it, or not.\n */\n draft?: { id: string; text: string }\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 draft,\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 // A draft handed in from outside (an app's accepted message): appended once per id.\n const draftId = draft?.id\n const draftText = draft?.text\n useEffect(() => {\n if (draftId === undefined || !draftText) return\n setText((t) => (t.trim() ? `${t.trimEnd()}\\n${draftText}` : draftText))\n inputRef.current?.focus()\n }, [draftId, draftText])\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 const doc = globalThis.document\n let pointerInside = false\n const onPointer = (e: Event) => {\n pointerInside =\n target !== globalThis.window &&\n e.target instanceof Node &&\n (target as HTMLElement).contains(e.target)\n }\n // Ctrl+V of files outside the textarea (which has its own handler and has\n // already taken the event by the time it gets here): anywhere inside the\n // drop zone (with nothing focused: when the zone is the window, or the last\n // click was inside it). A\n // paste into another field is that field's, and text is never touched.\n const onPasteFiles = (e: Event) => {\n if (e.defaultPrevented) return\n const pasted = (e as globalThis.ClipboardEvent).clipboardData?.files\n if (!pasted?.length) return\n const at = e.target instanceof Element ? e.target : null\n if (at?.closest('input, textarea, select, [contenteditable]:not([contenteditable=\"false\"])'))\n return\n if (target !== globalThis.window) {\n const zone = target as HTMLElement\n // Nothing focusable was clicked (the transcript, say): the event lands on\n // the body, and the last click says whether the user is in this zone.\n const unfocused = !at || at === doc?.body || at === doc?.documentElement\n if (unfocused ? !pointerInside : !zone.contains(at)) return\n }\n e.preventDefault()\n void addFilesRef.current(Array.from(pasted))\n }\n target.addEventListener('dragenter', onEnter)\n target.addEventListener('dragover', onOver)\n target.addEventListener('dragleave', onLeave)\n target.addEventListener('drop', onDropFiles)\n doc?.addEventListener('paste', onPasteFiles)\n doc?.addEventListener('pointerdown', onPointer, true)\n return () => {\n target.removeEventListener('dragenter', onEnter)\n target.removeEventListener('dragover', onOver)\n target.removeEventListener('dragleave', onLeave)\n target.removeEventListener('drop', onDropFiles)\n doc?.removeEventListener('paste', onPasteFiles)\n doc?.removeEventListener('pointerdown', onPointer, true)\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","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\n/** One result of the core's `web_search` tool, as far as a UI shows it. */\nexport interface WebSearchResultView {\n title: string\n /** An http(s) address - anything else is left out. */\n url: string\n /** The host of `url`, for the line under the title. */\n host: string\n snippet: string\n date?: string\n}\n\nexport interface WebSearchView {\n query: string\n results: WebSearchResultView[]\n /** Results the egress policy left out. */\n filtered: number\n truncated: boolean\n}\n\nconst text = (v: unknown, max: number): string =>\n typeof v === 'string' ? v.replace(/\\s+/g, ' ').trim().slice(0, max) : ''\n\n/**\n * The result of the core's `web_search` tool (`{ query, results: [{ title, url, snippet, date? }],\n * filtered?, truncated?, untrusted: true }`), or undefined when `output` is not one. Titles and\n * snippets are third-party text: they come back as plain strings, to be rendered as text. A\n * result whose `url` is not http(s) is dropped, so a link can never be a `javascript:` one.\n */\nexport const webSearchOf = (output: unknown): WebSearchView | undefined => {\n let value = output\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const o = value as Record<string, unknown>\n if (typeof o.query !== 'string' || !Array.isArray(o.results)) return undefined\n const results: WebSearchResultView[] = []\n for (const r of o.results.slice(0, 10)) {\n if (!r || typeof r !== 'object') continue\n const item = r as Record<string, unknown>\n if (typeof item.url !== 'string') continue\n let url: URL\n try {\n url = new URL(item.url)\n } catch {\n continue\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') continue\n const date = text(item.date, 40)\n results.push({\n title: text(item.title, 200) || url.host,\n url: url.href,\n host: url.host,\n snippet: text(item.snippet, 400),\n ...(date ? { date } : {}),\n })\n }\n return {\n query: text(o.query, 300),\n results,\n filtered: typeof o.filtered === 'number' && o.filtered > 0 ? o.filtered : 0,\n truncated: o.truncated === true,\n }\n}\n\n/** 0.934 → \"0.93\", 0.8 → \"0.8\", 1 → \"1\". */\nexport const formatProbability = (p: number): string => String(Math.round(p * 100) / 100)\n","import type { 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 { useEffect, useId, useState } from 'react'\nimport type { FormEvent, ReactNode } from 'react'\nimport {\n elicitationFields,\n elicitationFormAnswer,\n elicitationInitialDraft,\n elicitationLink,\n formatCountdown,\n type ElicitationDraft,\n type ElicitationDraftValue,\n type ElicitationField,\n type ElicitationIssue,\n type ElicitationOutcomeReason,\n type PendingElicitation,\n} from '../elicitation.js'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { McpElicitationResult } from '../mcp-types.js'\nimport type { ElicitationView } from '../types.js'\nimport { previewValue } from './format.js'\nimport { AlertIcon, ExternalIcon, QuestionIcon, XIcon } from './icons.js'\n\nexport interface ElicitationPromptProps {\n /**\n * The questions waiting for the user (`useMcp().pendingElicitations` /\n * `useMcpServers().pendingElicitations`, or the requests your own `onElicitation` was given).\n * One is shown at a time, with a count.\n */\n elicitations: PendingElicitation[]\n /**\n * The user's decision: `accept` (with the form's values, or a link the user opened and\n * finished), `decline` or `cancel`. Wire it to the hook's `answerElicitation`. The values go\n * to this callback and nowhere else.\n */\n onAnswer: (id: string, result: McpElicitationResult) => void\n /**\n * The run's questions as the reducer keeps them (`useAgent().elicitations`): the ones that\n * were answered without anybody deciding - a timeout, a stopped run, a cap - are said so.\n */\n outcomes?: ElicitationView[]\n /** Say which questions were answered automatically (default true; needs `outcomes`). */\n showOutcomes?: boolean\n /** The note that a question expires, with the time left when it is known (default true). */\n showExpiry?: boolean\n /** Say that a helper's call is the one that asks (default true). */\n showHelper?: boolean\n /**\n * Render a question yourself: `fallback` is the built-in card, `answer` decides it. The\n * request's strings are the SERVER's text - render them as text.\n */\n renderElicitation?: (\n elicitation: PendingElicitation,\n fallback: ReactNode,\n answer: (result: McpElicitationResult) => void,\n ) => ReactNode\n labels?: AgentLabelsOverride\n className?: string\n}\n\n// Why a question was answered automatically, in the labels' words (the core's code otherwise).\nconst reasonText = (outcome: ElicitationView, L: AgentLabels): string => {\n const reason = outcome.reason\n if (reason && Object.hasOwn(L.elicitationReasons, reason)) {\n return L.elicitationReasons[reason as ElicitationOutcomeReason]\n }\n return reason || outcome.status\n}\n\n/** Ticks once a second while `active`, so a countdown redraws. */\nconst useNow = (active: boolean): number => {\n const [now, setNow] = useState(() => Date.now())\n useEffect(() => {\n if (!active) return\n setNow(Date.now())\n const timer = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(timer)\n }, [active])\n return now\n}\n\nconst Expiry = ({ expiresAt, L }: { expiresAt?: number; L: AgentLabels }) => {\n const now = useNow(expiresAt !== undefined)\n return (\n <p className=\"awr-elicit__expiry\">\n {expiresAt === undefined\n ? L.elicitationExpires\n : L.elicitationExpiresIn(formatCountdown(expiresAt - now))}\n </p>\n )\n}\n\n/** The server's own words: plain text, under a caption that says whose they are. */\nconst ServerText = ({\n server,\n message,\n children,\n L,\n}: {\n server: string\n message: string\n children?: ReactNode\n L: AgentLabels\n}) => (\n <div className=\"awr-elicit__server\">\n <span className=\"awr-elicit__from\">{L.elicitationFrom(server)}</span>\n {message && <p className=\"awr-elicit__message\">{message}</p>}\n {children}\n </div>\n)\n\ninterface FieldProps {\n field: ElicitationField\n id: string\n value: ElicitationDraftValue | undefined\n issue?: ElicitationIssue\n onChange: (value: ElicitationDraftValue) => void\n L: AgentLabels\n}\n\nconst FieldControl = ({ field, id, value, issue, onChange, L }: FieldProps) => {\n const hintId = field.description ? `${id}-hint` : undefined\n const errorId = issue ? `${id}-error` : undefined\n const describedBy = [hintId, errorId].filter(Boolean).join(' ') || undefined\n const common = {\n 'aria-describedby': describedBy,\n 'aria-invalid': issue ? (true as const) : undefined,\n }\n const mark = field.required && (\n <span className=\"awr-elicit__req\" title={L.elicitationRequired}>\n <span aria-hidden=\"true\">*</span>\n <span className=\"awr-elicit__sr\"> ({L.elicitationRequired})</span>\n </span>\n )\n const hint = field.description && (\n <p className=\"awr-elicit__hint\" id={hintId}>\n {field.description}\n </p>\n )\n const error = issue && (\n <p className=\"awr-elicit__error\" id={errorId} role=\"alert\">\n {L.elicitationErrors[issue.kind](field.label, issue.limit)}\n </p>\n )\n const wrap = `awr-elicit__field awr-elicit__field--${field.control}${issue ? ' is-invalid' : ''}`\n\n if (field.control === 'checkbox') {\n return (\n <div className={wrap} data-field={field.name}>\n <label className=\"awr-elicit__check\">\n <input\n id={id}\n type=\"checkbox\"\n checked={value === true}\n onChange={(e) => onChange(e.target.checked)}\n {...common}\n />\n <span>\n {field.label}\n {mark}\n </span>\n </label>\n {hint}\n {error}\n </div>\n )\n }\n\n if (field.control === 'multiselect') {\n const picked = Array.isArray(value) ? value : []\n return (\n <fieldset className={wrap} data-field={field.name} {...common}>\n <legend className=\"awr-elicit__label\">\n {field.label}\n {mark}\n </legend>\n {hint}\n {(field.options ?? []).map((option, i) => (\n <label key={option.value} className=\"awr-elicit__check\">\n <input\n id={i === 0 ? id : undefined}\n type=\"checkbox\"\n checked={picked.includes(option.value)}\n onChange={(e) =>\n onChange(\n e.target.checked\n ? [...picked, option.value]\n : picked.filter((v) => v !== option.value),\n )\n }\n />\n <span>{option.label}</span>\n </label>\n ))}\n {error}\n </fieldset>\n )\n }\n\n const text = typeof value === 'string' ? value : ''\n return (\n <div className={wrap} data-field={field.name}>\n <label className=\"awr-elicit__label\" htmlFor={id}>\n {field.label}\n {mark}\n </label>\n {hint}\n {field.control === 'select' ? (\n <select\n id={id}\n className=\"awr-elicit__input\"\n value={text}\n required={field.required}\n onChange={(e) => onChange(e.target.value)}\n {...common}\n >\n <option value=\"\">{L.elicitationChoose}</option>\n {(field.options ?? []).map((option) => (\n <option key={option.value} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n ) : (\n <input\n id={id}\n className=\"awr-elicit__input\"\n // A number is typed as text: the browser's own number field hides what does not\n // parse, and the form could then only say \"required\".\n type={\n field.control === 'datetime'\n ? 'datetime-local'\n : field.control === 'number'\n ? 'text'\n : field.control\n }\n inputMode={\n field.control === 'number'\n ? field.schema.type === 'integer'\n ? 'numeric'\n : 'decimal'\n : undefined\n }\n value={text}\n required={field.required}\n autoComplete=\"off\"\n spellCheck={false}\n onChange={(e) => onChange(e.target.value)}\n {...common}\n />\n )}\n {error}\n </div>\n )\n}\n\ninterface CardProps {\n elicitation: PendingElicitation\n answer: (result: McpElicitationResult) => void\n L: AgentLabels\n}\n\n/** Form mode. What is typed lives in this component only, and goes with it. */\nconst FormBody = ({ elicitation, answer, L }: CardProps) => {\n const baseId = useId()\n const schema = elicitation.requestedSchema\n const fields = elicitationFields(schema)\n const [draft, setDraft] = useState<ElicitationDraft>(() => elicitationInitialDraft(schema))\n const [issues, setIssues] = useState<Record<string, ElicitationIssue> | undefined>(undefined)\n const fieldId = (i: number) => `${baseId}-f${i}`\n\n const submit = (e: FormEvent) => {\n e.preventDefault()\n const outcome = elicitationFormAnswer(schema, draft)\n if (outcome.ok) {\n answer({ action: 'accept', content: outcome.content })\n return\n }\n setIssues(outcome.issues)\n const first = fields.findIndex((f) => outcome.issues[f.name])\n if (first >= 0 && typeof document !== 'undefined') {\n document.getElementById(fieldId(first))?.focus()\n }\n }\n\n const change = (name: string, value: ElicitationDraftValue) => {\n const next = { ...draft, [name]: value }\n setDraft(next)\n // Once a submit was refused, the messages follow what is typed.\n if (issues) {\n const outcome = elicitationFormAnswer(schema, next)\n setIssues(outcome.ok ? {} : outcome.issues)\n }\n }\n\n const wrong = issues ? Object.keys(issues).length : 0\n return (\n <form className=\"awr-elicit__form\" noValidate onSubmit={submit}>\n <ServerText server={elicitation.server} message={elicitation.message} L={L}>\n {fields.map((field, i) => (\n <FieldControl\n key={field.name}\n field={field}\n id={fieldId(i)}\n value={draft[field.name]}\n issue={issues?.[field.name]}\n onChange={(value) => change(field.name, value)}\n L={L}\n />\n ))}\n </ServerText>\n {wrong > 0 && <p className=\"awr-elicit__fix\">{L.elicitationFix(wrong)}</p>}\n <div className=\"awr-elicit__actions\">\n <button type=\"submit\" className=\"awr-btn awr-btn--primary\">\n {L.elicitationSubmit}\n </button>\n <button type=\"button\" className=\"awr-btn\" onClick={() => answer({ action: 'decline' })}>\n {L.elicitationDecline}\n </button>\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--ghost\"\n onClick={() => answer({ action: 'cancel' })}\n >\n {L.elicitationCancel}\n </button>\n </div>\n </form>\n )\n}\n\n/** URL mode. The link is text; it is opened by the user's click on \"Open\" and by nothing else. */\nconst UrlBody = ({ elicitation, answer, L }: CardProps) => {\n const link = elicitationLink(elicitation.url)\n const [opened, setOpened] = useState(false)\n const open = () => {\n if (!link.openable || typeof window === 'undefined') return\n window.open(link.href, '_blank', 'noopener,noreferrer')\n setOpened(true)\n }\n return (\n <div className=\"awr-elicit__form\">\n <ServerText server={elicitation.server} message={elicitation.message} L={L} />\n <div className=\"awr-elicit__link\">\n <span className=\"awr-elicit__linklead\">{L.elicitationUrlLead(elicitation.server)}</span>\n <strong className=\"awr-elicit__host\">{link.host || '—'}</strong>\n <span className=\"awr-elicit__urllabel\">{L.elicitationUrlFull}</span>\n <code className=\"awr-elicit__url\">{link.href}</code>\n </div>\n {!link.openable && (\n <p className=\"awr-elicit__error\" role=\"alert\">\n {L.elicitationUrlRefused}\n </p>\n )}\n {opened && (\n <p className=\"awr-elicit__opened\" role=\"status\">\n {L.elicitationOpened}\n </p>\n )}\n <div className=\"awr-elicit__actions\">\n {link.openable && (\n <button\n type=\"button\"\n className={`awr-btn${opened ? '' : ' awr-btn--primary'}`}\n onClick={open}\n >\n <ExternalIcon size={14} /> {L.elicitationOpen}\n </button>\n )}\n {link.openable && opened && (\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--primary\"\n onClick={() => answer({ action: 'accept' })}\n >\n {L.elicitationUrlDone}\n </button>\n )}\n <button type=\"button\" className=\"awr-btn\" onClick={() => answer({ action: 'decline' })}>\n {L.elicitationDecline}\n </button>\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--ghost\"\n onClick={() => answer({ action: 'cancel' })}\n >\n {L.elicitationCancel}\n </button>\n </div>\n </div>\n )\n}\n\n/**\n * A question an MCP server puts to the user in the middle of a tool call (MCP elicitation): a\n * form to fill in, or a link to open. The header is the host's own - which server asks, during\n * which tool - and everything the server wrote is shown under a caption that says so, as plain\n * text. Three outcomes: accept (Submit / \"I have finished there\"), decline, cancel.\n *\n * Wire it to `useMcp` / `useMcpServers` (`pendingElicitations`, `answerElicitation`);\n * `<AgentChat elicitations onElicitationAnswer>` renders it for you. What the user types is\n * kept in this component only and handed to `onAnswer` once: it is not in the agent's state,\n * its events or the transcript.\n */\nexport const ElicitationPrompt = ({\n elicitations,\n onAnswer,\n outcomes,\n showOutcomes = true,\n showExpiry = true,\n showHelper = true,\n renderElicitation,\n labels,\n className,\n}: ElicitationPromptProps) => {\n const L = useLabels(labels)\n const [dismissed, setDismissed] = useState<ReadonlySet<string>>(() => new Set())\n const automatic = showOutcomes\n ? (outcomes ?? []).filter(\n (o) => o.automatic === true && o.status !== 'pending' && !dismissed.has(o.id),\n )\n : []\n const current = elicitations[0]\n if (!current && automatic.length === 0) return null\n\n let card: ReactNode = null\n if (current) {\n const answer = (result: McpElicitationResult) => onAnswer(current.id, result)\n // A helper's role is text the model wrote: plain text, shortened.\n const helper = showHelper ? current.subagent : undefined\n const role = helper\n ? previewValue(outcomes?.find((o) => o.id === current.id)?.subagent?.role ?? '', 60) ||\n undefined\n : undefined\n const Body = current.mode === 'url' ? UrlBody : FormBody\n const builtIn = (\n <section\n className={`awr-elicit awr-elicit--${current.mode}`}\n aria-label={L.elicitationTitle}\n data-server={current.server}\n data-subagent={helper?.id}\n >\n <div className=\"awr-elicit__head\" role=\"alert\">\n <QuestionIcon size={16} className=\"awr-elicit__icon\" />\n <span className=\"awr-elicit__lead\">\n {helper\n ? L.elicitationLeadHelper(current.server, role)\n : L.elicitationLead(current.server)}{' '}\n <span className=\"awr-elicit__during\">\n {L.elicitationDuring} <code className=\"awr-tool__name\">{current.tool}</code>\n </span>\n </span>\n {elicitations.length > 1 && (\n <span className=\"awr-elicit__count\">{L.elicitationCount(1, elicitations.length)}</span>\n )}\n </div>\n {/* Before the form, not under it: a long form is read from the top. */}\n {showExpiry && <Expiry key={`x-${current.id}`} expiresAt={current.expiresAt} L={L} />}\n {/* Keyed by the question: the next one starts from an empty form. */}\n <Body key={current.id} elicitation={current} answer={answer} L={L} />\n </section>\n )\n card = renderElicitation ? renderElicitation(current, builtIn, answer) : builtIn\n }\n\n return (\n <div className={['awr-elicits', className].filter(Boolean).join(' ')}>\n {automatic.map((o) => (\n <div key={o.id} className=\"awr-elicit-outcome\" role=\"status\" data-reason={o.reason}>\n <AlertIcon size={14} className=\"awr-elicit-outcome__icon\" />\n <span className=\"awr-elicit-outcome__text\">\n {L.elicitationAutomatic(o.server, reasonText(o, L))}\n </span>\n <button\n type=\"button\"\n className=\"awr-iconbtn awr-elicit-outcome__dismiss\"\n aria-label={L.elicitationDismiss}\n title={L.elicitationDismiss}\n onClick={() => setDismissed((d) => new Set(d).add(o.id))}\n >\n <XIcon size={14} />\n </button>\n </div>\n ))}\n {card}\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, useEffect, useMemo, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { VirtualFile, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { fileKindOf, fileNameOf, type FileKind } from '../file-kinds.js'\nimport { useVirtualFiles } from '../hooks/use-virtual-files.js'\nimport {\n HTML_PREVIEW_MAX_CHARS,\n linkedFilesOf,\n tokenizeHtml,\n type SourceToken,\n} from '../html-preview.js'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { WrittenFileView } from '../types.js'\nimport {\n ChevronUpIcon,\n CodeIcon,\n DownloadIcon,\n ExpandIcon,\n EyeIcon,\n FileIcon,\n FileTextIcon,\n ImageIcon,\n LockIcon,\n NoNetworkIcon,\n TableIcon,\n XIcon,\n} from './icons.js'\nimport { bytesOf, useFileUrl } from './Media.js'\nimport { SandboxedFrame } from './SandboxedFrame.js'\n\n/** How an `.html` file is previewed. */\nexport interface HtmlPreviewOptions {\n /**\n * Let the page's inline scripts run inside the sandbox (default false: a static render). Even\n * with scripts the page has an opaque origin and no network.\n */\n scripts?: boolean\n /** Height of the frame in px (default 300; clamped to 120 - 800). */\n height?: number\n}\n\n/** Characters of a text file a preview shows (the rest is cut, and the preview says so). */\nexport const FILE_PREVIEW_CHARS = 20_000\n\nconst textOf = (file: VirtualFile): string =>\n file.encoding === 'base64'\n ? new TextDecoder().decode(bytesOf(file.content, 'base64'))\n : file.content\n\nconst KIND_ICON: Record<FileKind, typeof FileIcon> = {\n html: CodeIcon,\n markdown: FileTextIcon,\n csv: TableIcon,\n json: CodeIcon,\n image: ImageIcon,\n code: CodeIcon,\n text: FileTextIcon,\n file: FileIcon,\n}\n\n/** Save a workspace file through the browser's download. */\nconst downloadFile = async (vfs: VirtualFileSystem, path: string): Promise<void> => {\n const file = await vfs.read(path)\n if (!file) return\n // Never typed as what it claims to be: a download, not a document the page could open.\n const url = URL.createObjectURL(\n new Blob([bytesOf(file.content, file.encoding)], { type: 'application/octet-stream' }),\n )\n const a = document.createElement('a')\n a.href = url\n a.download = fileNameOf(path)\n a.click()\n setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n\ninterface SegProps<T extends string> {\n value: T\n options: { value: T; label: string; icon?: ReactNode }[]\n onChange: (value: T) => void\n label: string\n}\n\n/** A two-way switch (Preview | Source). */\nconst Seg = <T extends string>({ value, options, onChange, label }: SegProps<T>) => (\n <div className=\"awr-seg\" role=\"group\" aria-label={label}>\n {options.map((o) => (\n <button\n key={o.value}\n type=\"button\"\n className={`awr-seg__opt${o.value === value ? ' is-on' : ''}`}\n aria-pressed={o.value === value}\n onClick={() => onChange(o.value)}\n >\n {o.icon}\n {o.label}\n </button>\n ))}\n </div>\n)\n\nconst linesOf = (tokens: SourceToken[]): SourceToken[][] => {\n const lines: SourceToken[][] = [[]]\n for (const t of tokens) {\n const parts = t.text.split('\\n')\n parts.forEach((part, i) => {\n if (i > 0) lines.push([])\n if (part) lines[lines.length - 1].push({ kind: t.kind, text: part })\n })\n }\n return lines\n}\n\nexport interface SourceViewProps {\n text: string\n /** Colour it as HTML (default: plain). */\n html?: boolean\n /** Characters shown (default 20 000). */\n maxChars?: number\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * A file's text with line numbers. Always text nodes - the content of a file is never set as\n * markup, whatever it contains.\n */\nexport const SourceView = ({\n text,\n html = false,\n maxChars = FILE_PREVIEW_CHARS,\n labels,\n className,\n}: SourceViewProps) => {\n const L = useLabels(labels)\n const cut = text.length > maxChars\n const shown = cut ? text.slice(0, maxChars) : text\n const lines = useMemo(\n () => linesOf(html ? tokenizeHtml(shown) : [{ kind: 'text', text: shown }]),\n [shown, html],\n )\n return (\n <>\n <pre className={['awr-source', className].filter(Boolean).join(' ')} tabIndex={0}>\n {lines.map((line, i) => (\n <span key={i} className=\"awr-source__line\">\n {line.map((t, k) =>\n t.kind === 'text' ? (\n <Fragment key={k}>{t.text}</Fragment>\n ) : (\n <span key={k} className={`awr-source__${t.kind}`}>\n {t.text}\n </span>\n ),\n )}\n {'\\n'}\n </span>\n ))}\n </pre>\n {cut && <p className=\"awr-fileview__cut\">{L.fileCut(maxChars)}</p>}\n </>\n )\n}\n\ninterface PreviewProps {\n written: WrittenFileView\n file: VirtualFile\n kind: FileKind\n vfs: VirtualFileSystem\n htmlPreview: HtmlPreviewOptions | false\n renderFileContent?: FileChipsProps['renderFileContent']\n previewChars: number\n onClose: () => void\n L: AgentLabels\n}\n\n/** An `.html` file: the page in the sandboxed frame, or its source as text. */\nconst HtmlPreview = ({ written, file, htmlPreview, previewChars, L }: PreviewProps) => {\n const html = useMemo(() => textOf(file), [file])\n const options = htmlPreview === false ? undefined : htmlPreview\n const tooLarge = html.length > HTML_PREVIEW_MAX_CHARS\n const canFrame = Boolean(options) && !tooLarge\n const [view, setView] = useState<'preview' | 'source'>(canFrame ? 'preview' : 'source')\n const [tall, setTall] = useState(false)\n const showing = canFrame ? view : 'source'\n const scripts = options?.scripts === true\n const height = options?.height ?? 300\n const linked = useMemo(() => (showing === 'preview' ? linkedFilesOf(html) : []), [html, showing])\n return (\n <SandboxedFrame\n className=\"awr-frame--html\"\n title={L.htmlFrameName(written.path)}\n html={showing === 'preview' ? html : undefined}\n scripts={scripts}\n height={tall ? height * 2 : height}\n label={\n <>\n <CodeIcon size={14} className=\"awr-frame__icon\" />\n <span className=\"awr-frame__titles\">\n <span className=\"awr-frame__title\">{L.htmlFrameTitle}</span>\n <span className=\"awr-frame__badges\">\n {showing === 'preview' ? (\n <>\n <LockIcon size={11} /> {L.htmlSandboxed} · <NoNetworkIcon size={11} />{' '}\n {L.htmlNoNetwork}\n </>\n ) : (\n L.htmlSourceNote\n )}\n </span>\n </span>\n </>\n }\n actions={\n canFrame ? (\n <>\n <Seg\n label={L.htmlFrameTitle}\n value={showing}\n onChange={setView}\n options={[\n { value: 'preview', label: L.preview, icon: <EyeIcon size={13} /> },\n { value: 'source', label: L.fileSource, icon: <CodeIcon size={13} /> },\n ]}\n />\n <button\n type=\"button\"\n className={`awr-frame__btn${tall ? ' is-on' : ''}`}\n aria-label={tall ? L.htmlShorter : L.htmlTaller}\n title={tall ? L.htmlShorter : L.htmlTaller}\n aria-pressed={tall}\n disabled={showing !== 'preview'}\n onClick={() => setTall((t) => !t)}\n >\n <ExpandIcon size={15} />\n </button>\n </>\n ) : undefined\n }\n footer={\n <>\n <FileIcon size={11} />\n <code>{written.path}</code>\n <span className=\"awr-frame__footmeta\">\n · {L.bytes(file.size)} ·{' '}\n {showing === 'preview' ? L.htmlScripts(scripts) : L.fileLines(html.split('\\n').length)}\n {linked.length > 0 ? ` · ${L.htmlLinkedFiles(linked.join(', '))}` : ''}\n </span>\n </>\n }\n >\n {showing === 'source' ? (\n <>\n {tooLarge && options ? <p className=\"awr-fileview__cut\">{L.htmlTooLarge}</p> : null}\n <SourceView text={html} html maxChars={previewChars} className=\"awr-frame__source\" />\n </>\n ) : undefined}\n </SandboxedFrame>\n )\n}\n\n/** A picture, typed as one of the image types the core writes (never as what the file claims). */\nconst ImagePreview = ({ written, vfs, onClose, L }: PreviewProps) => {\n const url = useFileUrl(vfs, written.path, written.mediaType.toLowerCase().split(';')[0].trim())\n return (\n <div className=\"awr-fileview\">\n <FileViewHead written={written} kind=\"image\" onClose={onClose} L={L} />\n <div className=\"awr-fileview__image\">\n {url ? <img src={url} alt={fileNameOf(written.path)} /> : null}\n </div>\n </div>\n )\n}\n\nconst FileViewHead = ({\n written,\n kind,\n onClose,\n L,\n children,\n}: {\n written: WrittenFileView\n kind: FileKind\n onClose: () => void\n L: AgentLabels\n children?: ReactNode\n}) => (\n <div className=\"awr-fileview__head\">\n <span className=\"awr-fileview__name\" title={written.path}>\n {fileNameOf(written.path)}\n </span>\n <span className=\"awr-fileview__kind\">· {L.fileKinds[kind]}</span>\n <span className=\"awr-fileview__actions\">\n {children}\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.closePreview}\n title={L.closePreview}\n onClick={onClose}\n >\n <XIcon size={14} />\n </button>\n </span>\n </div>\n)\n\n/** Text, Markdown, CSV, JSON, code: the source - and the host's rendering of it, when it has one. */\nconst TextPreview = ({\n written,\n file,\n kind,\n renderFileContent,\n previewChars,\n onClose,\n L,\n}: PreviewProps) => {\n const text = useMemo(() => textOf(file), [file])\n const rendered = useMemo(\n () => renderFileContent?.(written, text.slice(0, previewChars)),\n [renderFileContent, written, text, previewChars],\n )\n const hasRendered = rendered !== undefined && rendered !== null && rendered !== false\n const [view, setView] = useState<'rendered' | 'source'>('rendered')\n const [all, setAll] = useState(false)\n const showing = hasRendered ? view : 'source'\n // Long enough to be worth folding (the fold itself is CSS: a capped height).\n const long = text.length > 1200 || text.split('\\n').length > 16\n return (\n <div className=\"awr-fileview\">\n <FileViewHead written={written} kind={kind} onClose={onClose} L={L}>\n {hasRendered && (\n <Seg\n label={fileNameOf(written.path)}\n value={showing}\n onChange={setView}\n options={[\n { value: 'rendered', label: L.fileRendered },\n { value: 'source', label: L.fileSource },\n ]}\n />\n )}\n </FileViewHead>\n <div className={`awr-fileview__body${long && !all ? ' is-folded' : ''}`}>\n {showing === 'rendered' ? (\n <>\n <div className=\"awr-fileview__rendered\">{rendered}</div>\n {text.length > previewChars && (\n <p className=\"awr-fileview__cut\">{L.fileCut(previewChars)}</p>\n )}\n </>\n ) : (\n <SourceView text={text} maxChars={previewChars} />\n )}\n </div>\n {long && (\n <div className=\"awr-fileview__more\">\n <button type=\"button\" className=\"awr-linkbtn\" onClick={() => setAll((a) => !a)}>\n {all ? L.fileShowLess : L.fileShowRest}\n </button>\n </div>\n )}\n </div>\n )\n}\n\nconst NoPreview = ({ written, kind, onClose, L }: PreviewProps) => (\n <div className=\"awr-fileview\">\n <FileViewHead written={written} kind={kind} onClose={onClose} L={L} />\n <p className=\"awr-fileview__none\">{L.fileNoPreview}</p>\n </div>\n)\n\nexport interface FileChipsProps {\n /** The files of a turn (`ChatMessage.writtenFiles`). */\n written: WrittenFileView[]\n /**\n * The workspace they are in (the core's `VirtualFileSystem`). Without it the chips still\n * name the files, with nothing to open or download.\n */\n files?: VirtualFileSystem\n /** The line above the chips - \"3 files written in this turn\" (default true). */\n showHeader?: boolean\n /** Shows a \"Show in Files\" link in that line. */\n onShowFiles?: () => void\n /**\n * How an `.html` file is previewed: in a sandboxed frame without network, scripts off\n * (default `{}`); `{ scripts: true }` lets its inline scripts run; `false` never renders\n * HTML - the file is shown as source only.\n */\n htmlPreview?: HtmlPreviewOptions | false\n /** A whole chip; `fallback` is the built-in one. */\n renderFile?: (file: WrittenFileView, fallback: ReactNode) => ReactNode\n /**\n * A text file rendered your way - e.g. Markdown through your renderer. Return `undefined`\n * for a file you do not render: it is then shown as source. `text` is already capped.\n */\n renderFileContent?: (file: WrittenFileView, text: string) => ReactNode\n /** Characters of a text file a preview shows (default 20 000). */\n previewChars?: number\n /** A file whose preview is open at first (its path). */\n defaultOpen?: string\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * The files an answer left in the workspace, as chips under it: name, kind, size, open and\n * download. Opening one shows it right there - text as text (rendered too, when the host gives\n * a renderer), a picture as a picture, and an `.html` page in a sandboxed frame with a\n * Preview / Source switch (see `SandboxedFrame`).\n */\nexport const FileChips = ({\n written,\n files: vfs,\n showHeader = true,\n onShowFiles,\n htmlPreview = {},\n renderFile,\n renderFileContent,\n previewChars = FILE_PREVIEW_CHARS,\n defaultOpen,\n labels,\n className,\n}: FileChipsProps) => {\n const L = useLabels(labels)\n const live = useVirtualFiles(vfs)\n const [openPath, setOpenPath] = useState<string | undefined>(defaultOpen)\n const [file, setFile] = useState<VirtualFile | undefined>()\n\n const open = written.find((f) => f.path === openPath)\n // The open file's content, re-read when it is written again.\n const stamp = live.files.find((f) => f.path === openPath)?.updatedAt\n useEffect(() => {\n if (!vfs || !openPath) return setFile(undefined)\n let gone = false\n vfs\n .read(openPath)\n .then((f) => {\n if (!gone) setFile(f)\n })\n .catch(() => {\n if (!gone) setFile(undefined)\n })\n return () => {\n gone = true\n }\n }, [vfs, openPath, stamp])\n\n if (written.length === 0) return null\n\n const preview = (): ReactNode => {\n if (!open || !vfs || !file || file.path !== open.path) return null\n const kind = fileKindOf(open.path, file.mimeType)\n const props: PreviewProps = {\n written: open,\n file,\n kind,\n vfs,\n htmlPreview,\n renderFileContent,\n previewChars,\n onClose: () => setOpenPath(undefined),\n L,\n }\n if (kind === 'html') return <HtmlPreview key={open.path} {...props} />\n if (kind === 'image') return <ImagePreview key={open.path} {...props} />\n if (kind === 'file') return <NoPreview key={open.path} {...props} />\n return <TextPreview key={open.path} {...props} />\n }\n\n return (\n <div className={['awr-msg__files', className].filter(Boolean).join(' ')}>\n {showHeader && (\n <div className=\"awr-msg__fileshead\">\n <FileIcon size={13} />\n <span>{L.filesWritten(written.length)}</span>\n {onShowFiles && (\n <button type=\"button\" className=\"awr-linkbtn\" onClick={onShowFiles}>\n {L.showInFiles}\n </button>\n )}\n </div>\n )}\n <ul className=\"awr-filechips\">\n {written.map((w) => {\n const info = live.files.find((f) => f.path === w.path)\n const gone = Boolean(vfs) && !live.loading && !info\n const usable = Boolean(vfs) && !gone\n const isOpen = openPath === w.path && usable\n const chip = (\n <FileChip\n written={w}\n mediaType={info?.mimeType ?? w.mediaType}\n bytes={info?.size ?? w.bytes}\n files={usable ? vfs : undefined}\n gone={gone}\n open={isOpen}\n onToggle={() => setOpenPath(isOpen ? undefined : w.path)}\n labels={labels}\n />\n )\n return (\n <li key={w.path} className=\"awr-filechips__item\">\n {renderFile ? renderFile(w, chip) : chip}\n </li>\n )\n })}\n </ul>\n {preview()}\n </div>\n )\n}\n\nexport interface FileChipProps {\n written: WrittenFileView\n /** The type and size now (default: what the turn recorded). */\n mediaType?: string\n bytes?: number\n /** The workspace: gives the chip its download, its thumbnail and its open button. */\n files?: VirtualFileSystem\n /** The file is not in the workspace any more. */\n gone?: boolean\n open?: boolean\n onToggle?: () => void\n labels?: AgentLabelsOverride\n}\n\n/** One file: icon (a thumbnail for a picture), name, kind · size, open, download. */\nexport const FileChip = ({\n written,\n mediaType = written.mediaType,\n bytes = written.bytes,\n files: vfs,\n gone = false,\n open = false,\n onToggle,\n labels,\n}: FileChipProps) => {\n const L = useLabels(labels)\n const kind = fileKindOf(written.path, mediaType)\n const name = fileNameOf(written.path)\n const Icon = KIND_ICON[kind]\n const thumb = useFileUrl(\n kind === 'image' ? vfs : undefined,\n written.path,\n kind === 'image' ? mediaType.toLowerCase().split(';')[0].trim() : undefined,\n )\n const meta = gone\n ? L.fileGone\n : [L.fileKinds[kind], L.bytes(bytes), written.by ? L.fileBy(written.by.name) : '']\n .filter(Boolean)\n .join(' · ')\n return (\n <div\n className={`awr-filechip${open ? ' is-open' : ''}${gone ? ' is-gone' : ''}`}\n title={written.path}\n >\n <span className=\"awr-filechip__thumb\">\n {thumb ? <img src={thumb} alt=\"\" /> : <Icon size={16} />}\n </span>\n <span className=\"awr-filechip__text\">\n <span className=\"awr-filechip__name\">{name}</span>\n <span className=\"awr-filechip__meta\">{meta}</span>\n </span>\n {vfs && (\n <span className=\"awr-filechip__actions\">\n {onToggle && (\n <button\n type=\"button\"\n className={`awr-iconbtn${open ? ' is-on' : ''}`}\n aria-label={open ? L.fileClose(name) : L.fileOpen(name)}\n title={open ? L.closePreview : L.preview}\n aria-expanded={open}\n onClick={onToggle}\n >\n {open ? <ChevronUpIcon size={15} /> : <EyeIcon size={15} />}\n </button>\n )}\n <button\n type=\"button\"\n className=\"awr-iconbtn\"\n aria-label={L.fileDownload(name)}\n title={L.download}\n onClick={() => void downloadFile(vfs, written.path)}\n >\n <DownloadIcon size={15} />\n </button>\n </span>\n )}\n </div>\n )\n}\n","import { MEDIA_IMAGE_TYPES, isTextMime } from '@dudko.dev/agent-web'\n\n/**\n * What a workspace file is to the UI. `image` is only what the core's media tools accept\n * (PNG / JPEG / GIF / WebP - never SVG, which is shown as its source); `file` is anything that\n * cannot be shown as text: a chip with a download and no preview.\n */\nexport type FileKind = 'html' | 'markdown' | 'csv' | 'json' | 'image' | 'code' | 'text' | 'file'\n\nconst CODE =\n /\\.(?:js|mjs|cjs|jsx|ts|tsx|css|scss|py|rb|go|rs|java|kt|c|h|cpp|cs|php|sh|sql|xml|svg|yaml|yml|toml)$/i\n\nconst mimeOf = (mediaType: string): string => mediaType.toLowerCase().split(';')[0].trim()\n\n/** The kind of a file, by its MIME type first and its extension second. */\nexport const fileKindOf = (path: string, mediaType: string): FileKind => {\n const mime = mimeOf(mediaType)\n if (Object.hasOwn(MEDIA_IMAGE_TYPES, mime)) return 'image'\n if (mime === 'text/html' || mime === 'application/xhtml+xml' || /\\.x?html?$/i.test(path))\n return 'html'\n if (mime === 'text/markdown' || /\\.(?:md|markdown)$/i.test(path)) return 'markdown'\n if (mime === 'text/csv' || /\\.(?:csv|tsv)$/i.test(path)) return 'csv'\n if (mime === 'application/json' || /\\.json$/i.test(path)) return 'json'\n if (CODE.test(path)) return 'code'\n if (mime === 'text/plain' || /\\.(?:txt|log)$/i.test(path) || isTextMime(mime)) return 'text'\n return 'file'\n}\n\n/** The last segment of a path: what a chip is called and what a download is saved as. */\nexport const fileNameOf = (path: string): string => path.split('/').filter(Boolean).pop() || 'file'\n","import { useEffect, useState } from 'react'\nimport { MEDIA_AUDIO_TYPES, MEDIA_IMAGE_TYPES, type VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { MediaView, TranscriptView } from '../types.js'\nimport { FileIcon } from './icons.js'\n\n/**\n * How a generated file may be shown: only the types the core's media tools accept\n * (PNG / JPEG / GIF / WebP, and its audio list). Anything else - SVG included - is a file chip.\n */\nexport const mediaFamilyOf = (mediaType: string): 'image' | 'audio' | undefined => {\n const type = mediaType.toLowerCase().split(';')[0].trim()\n if (Object.hasOwn(MEDIA_IMAGE_TYPES, type)) return 'image'\n if (Object.hasOwn(MEDIA_AUDIO_TYPES, type)) return 'audio'\n return undefined\n}\n\n/** The bytes of a workspace file (its content is text, or base64). */\nexport const bytesOf = (content: string, encoding: string): Uint8Array<ArrayBuffer> => {\n if (encoding !== 'base64') return new TextEncoder().encode(content)\n const binary = atob(content)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\n/**\n * An object URL of a workspace file, typed as `mediaType` (never as whatever the file says it\n * is), revoked when the file, the workspace or the component goes away.\n */\nexport const useFileUrl = (\n files: VirtualFileSystem | undefined,\n path: string,\n mediaType: string | undefined,\n): string | undefined => {\n const [url, setUrl] = useState<string | undefined>(undefined)\n useEffect(() => {\n if (!files || !mediaType) return\n let made: string | undefined\n let gone = false\n files\n .read(path)\n .then((file) => {\n if (gone || !file) return\n made = URL.createObjectURL(\n new Blob([bytesOf(file.content, file.encoding)], { type: mediaType }),\n )\n setUrl(made)\n })\n .catch(() => {\n /* the chip stays */\n })\n return () => {\n gone = true\n if (made) URL.revokeObjectURL(made)\n setUrl(undefined)\n }\n }, [files, path, mediaType])\n return url\n}\n\nexport interface GeneratedMediaProps {\n media: MediaView\n /** The workspace the file is in (the core's `VirtualFileSystem`). Without it: a file chip. */\n files?: VirtualFileSystem\n labels?: AgentLabelsOverride\n}\n\n/**\n * A file a media tool wrote, read from the workspace: an image inline, audio as a native\n * player. A type the core does not generate, a missing file or no workspace gives a chip with\n * the path.\n */\nexport const GeneratedMedia = ({ media, files, labels }: GeneratedMediaProps) => {\n const L = useLabels(labels)\n const family = mediaFamilyOf(media.mediaType)\n const type = family ? media.mediaType.toLowerCase().split(';')[0].trim() : undefined\n const url = useFileUrl(files, media.path, type)\n if (url && family === 'image') {\n return (\n <a\n className=\"awr-media awr-media--image\"\n href={url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n title={media.path}\n >\n <img className=\"awr-media__img\" src={url} alt={L.mediaImage(media.path)} />\n </a>\n )\n }\n if (url && family === 'audio') {\n return (\n <span className=\"awr-media awr-media--audio\" title={media.path}>\n <audio\n className=\"awr-media__audio\"\n controls\n preload=\"metadata\"\n src={url}\n aria-label={L.mediaAudio(media.path)}\n />\n </span>\n )\n }\n return (\n <span className=\"awr-chip awr-file awr-media awr-media--file\" title={L.mediaFile(media.path)}>\n <FileIcon size={13} /> {media.path}\n </span>\n )\n}\n\nexport interface TranscriptBlockProps {\n transcript: TranscriptView\n labels?: AgentLabelsOverride\n}\n\n/**\n * What an audio file said, folded: \"Transcript of memo.mp3\". The text is the content of the\n * user's file - shown as plain text and marked as such.\n */\nexport const TranscriptBlock = ({ transcript, labels }: TranscriptBlockProps) => {\n const L = useLabels(labels)\n return (\n <details className=\"awr-transcript\">\n <summary className=\"awr-transcript__summary\">\n <FileIcon size={13} /> {L.transcriptOf(transcript.name)}\n </summary>\n <p className=\"awr-transcript__note\">{L.transcriptNote}</p>\n <blockquote className=\"awr-transcript__text\">{transcript.text}</blockquote>\n </details>\n )\n}\n","import type { ReactNode } from 'react'\nimport { buildSandboxedDocument, sandboxTokens } from '../html-preview.js'\n\n/** The frame's height is the host's: a number of pixels between these, never the content's wish. */\nexport const FRAME_MIN_HEIGHT = 120\nexport const FRAME_MAX_HEIGHT = 800\n\nexport const clampFrameHeight = (height: number): number =>\n Math.min(\n FRAME_MAX_HEIGHT,\n Math.max(FRAME_MIN_HEIGHT, Math.round(Number.isFinite(height) ? height : 300)),\n )\n\nexport interface SandboxedFrameProps {\n /**\n * The untrusted document. It is shown inside `<iframe sandbox>` without `allow-same-origin`,\n * under a policy with no network, wrapped by `buildSandboxedDocument`. Omit it (and pass\n * `children`) to show host-rendered content - the source as text - in the same chrome.\n */\n html?: string\n /** Let the document's inline scripts run (default false). */\n scripts?: boolean\n /** The accessible name of the frame. */\n title: string\n /** The host's label, in the header: what this is and where it came from. */\n label: ReactNode\n /** Host controls in the header (a view switch, buttons). */\n actions?: ReactNode\n /** A host line under the frame. */\n footer?: ReactNode\n /** Height of the framed document in px (default 300; clamped to 120 - 800). */\n height?: number\n /** Host-rendered content in place of the framed document. */\n children?: ReactNode\n className?: string\n}\n\n/**\n * Third-party HTML inside chrome the host draws. The header, the footer and every control are\n * OUTSIDE the `<iframe>`: the content can paint whatever it likes inside its box and still cannot\n * imitate or cover a control of the chat. The box has a fixed height the host chose - the frame\n * is never resized by a message from the content, and the component listens to none.\n *\n * Reusable for anything untrusted that must be drawn (an HTML file, an MCP App): give it the\n * document and a label; see `html-preview.ts` for what the boundary is made of.\n */\nexport const SandboxedFrame = ({\n html,\n scripts = false,\n title,\n label,\n actions,\n footer,\n height = 300,\n children,\n className,\n}: SandboxedFrameProps) => (\n <div className={['awr-frame', className].filter(Boolean).join(' ')}>\n <div className=\"awr-frame__head\">\n <div className=\"awr-frame__label\">{label}</div>\n {actions}\n </div>\n {html !== undefined && children === undefined ? (\n <div className=\"awr-frame__well\">\n <iframe\n // A new mode is a new frame: `sandbox` is read when a document loads, so the element\n // is replaced rather than re-attributed.\n key={scripts ? 'scripts' : 'static'}\n className=\"awr-frame__iframe\"\n title={title}\n sandbox={sandboxTokens(scripts)}\n referrerPolicy=\"no-referrer\"\n srcDoc={buildSandboxedDocument(html, { scripts })}\n style={{ height: clampFrameHeight(height) }}\n />\n </div>\n ) : (\n children\n )}\n {footer ? <div className=\"awr-frame__foot\">{footer}</div> : null}\n </div>\n)\n","import { Fragment } from 'react'\nimport type { ReactNode } from 'react'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type {\n ApprovalView,\n DecisionView,\n StepView,\n SubagentView,\n ToolCallView,\n UserNoteView,\n} from '../types.js'\nimport {\n formatDuration,\n formatProbability,\n formatTokens,\n imagesInOutput,\n previewValue,\n webSearchOf,\n} from './format.js'\nimport {\n AlertIcon,\n AppIcon,\n ArrowUpIcon,\n BrainIcon,\n CheckIcon,\n GlobeIcon,\n SendIcon,\n ShieldIcon,\n SpinnerIcon,\n ToolIcon,\n} from './icons.js'\nimport { SubagentTree, type RenderSubagent } from './SubagentTree.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 /**\n * Mark a call of an escalated attempt (\"attempt 1\") and a write that was not run a second\n * time (default true). Nothing shows without model tiers.\n */\n showTiers?: boolean\n /**\n * A `web_search` call's results as a short list under the row: the query, then title + host\n * of each result as a link and its snippet as plain text (default true).\n */\n showSearchResults?: boolean\n labels?: AgentLabelsOverride\n}\n\n/** The name of the core's search tool (its `WEB_SEARCH_TOOL`). */\nconst WEB_SEARCH = 'web_search'\n\n/**\n * One tool call: name, arguments, status — and optionally its cost, any images it returned and,\n * for a web search, what it found.\n */\nexport const ToolCallRow = ({\n call,\n showUsage = true,\n showTiers = true,\n showSearchResults = true,\n labels,\n}: 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 search =\n showSearchResults && call.name === WEB_SEARCH && call.status === 'done' && call.ok !== false\n ? webSearchOf(call.output)\n : undefined\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\n className={`awr-tool awr-tool--${state}${showTiers && call.attempt !== undefined ? ' awr-tool--earlier' : ''}`}\n >\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 {showTiers && call.replayed && (\n <span className=\"awr-tool__tag\" title={L.replayedTitle}>\n {L.replayed}\n </span>\n )}\n {showTiers && call.attempt !== undefined && (\n <span className=\"awr-tool__tag\">{L.attemptTag(call.attempt)}</span>\n )}\n {call.app && (\n <span className=\"awr-tool__tag awr-tool__tag--app\" data-app={call.app}>\n <AppIcon size={10} /> {L.appTag}\n </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 {search && (\n <div className=\"awr-search\">\n <p className=\"awr-search__query\">\n <GlobeIcon size={12} /> {L.searchQuery} <q>{search.query}</q>\n </p>\n {search.results.length > 0 ? (\n <ol className=\"awr-search__results\">\n {search.results.map((r, i) => (\n <li key={i} className=\"awr-search__result\">\n {/* Third-party text: React text nodes only, never markup. */}\n <a\n className=\"awr-search__title\"\n href={r.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {r.title}\n </a>{' '}\n <span className=\"awr-search__host\">\n {r.host}\n {r.date ? ` · ${r.date}` : ''}\n </span>\n {r.snippet && <p className=\"awr-search__snippet\">{r.snippet}</p>}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"awr-search__note\">{L.searchNoResults}</p>\n )}\n {(search.filtered > 0 || search.truncated) && (\n <p className=\"awr-search__note\">\n {[\n search.filtered > 0 ? L.searchFiltered(search.filtered) : '',\n search.truncated ? L.searchTruncated : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </p>\n )}\n </div>\n )}\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\n/** \"decision model: continue (0.93)\" / \"decision model fell back: low confidence (0.41 < 0.8)\". */\nexport const decisionNote = (d: DecisionView, L: AgentLabels): string => {\n if (d.accepted) {\n return L.decisionAccepted(\n d.choice ?? '',\n d.confidence !== undefined ? formatProbability(d.confidence) : '',\n )\n }\n const detail =\n d.reason === 'low-confidence' && d.confidence !== undefined\n ? `${formatProbability(d.confidence)} < ${formatProbability(d.threshold)}`\n : ''\n return L.decisionFellBack(d.reason ? L.decisionReasons[d.reason] : '', detail)\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 showTiers: boolean\n showReplanFailed: boolean\n showDecisions: boolean\n showSearchResults: boolean\n showSubagents: boolean\n renderToolCall?: RenderToolCall\n renderSubagent?: RenderSubagent\n L: AgentLabels\n}\n\nconst StepItem = ({\n step,\n subagents,\n approvals,\n notes,\n onStopSubagent,\n showToolCalls,\n showUsage,\n showThoughts,\n showTiers,\n showReplanFailed,\n showDecisions,\n showSearchResults,\n showSubagents,\n renderToolCall,\n renderSubagent,\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 {showTiers && step.tier && (\n <div className=\"awr-step__meta\">\n <span\n className={`awr-step__tier awr-step__tier--${step.tier}`}\n title={step.tierReason ? L.tierReasons[step.tierReason] : undefined}\n >\n {L.tierNames[step.tier]}\n </span>\n {step.model && <span className=\"awr-step__model\">{step.model}</span>}\n </div>\n )}\n {showTiers &&\n step.escalations?.map((e, i) => (\n <div key={i} className=\"awr-step__escalated\">\n <p className=\"awr-step__escalated-line\">\n <ArrowUpIcon size={12} />\n <span>\n {L.escalated(L.tierNames[e.from], L.tierNames[e.to], L.escalationReasons[e.reason])}\n </span>\n </p>\n {e.text?.trim() && (\n <details className=\"awr-step__attempt\">\n <summary>{L.escalatedAttemptText}</summary>\n <p className=\"awr-step__text\">{e.text.trim()}</p>\n </details>\n )}\n </div>\n ))}\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 = (\n <ToolCallRow\n key={i}\n call={call}\n showUsage={showUsage}\n showTiers={showTiers}\n showSearchResults={showSearchResults}\n />\n )\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 {a.subagent && <span className=\"awr-tool__tag\">{L.subagentHelper}</span>}\n </li>\n ))}\n </ul>\n )}\n {showSubagents && (\n <SubagentTree\n subagents={subagents}\n onStop={onStopSubagent}\n showUsage={showUsage}\n renderSubagent={renderSubagent}\n />\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 {showReplanFailed && step.replanFailed && (\n <p className=\"awr-step__warn\" title={step.replanFailed}>\n <AlertIcon size={12} /> {L.replanFailed}\n </p>\n )}\n {showDecisions &&\n step.decisions?.map((d, i) => (\n <p\n key={i}\n className={`awr-step__decision${d.accepted ? '' : ' awr-step__decision--fallback'}`}\n title={d.model}\n >\n {decisionNote(d, L)}\n </p>\n ))}\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 /** The subagent tree under the step that started it (default true). */\n showSubagents?: boolean\n /** Render a node of the subagent tree yourself (gets the built-in `<li>` as `fallback`). */\n renderSubagent?: RenderSubagent\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 /**\n * Model tiers: the tier / model badge on a step, its \"escalated: light → strong\" line and the\n * marks on the earlier attempt's tool calls (default true; nothing shows when tiers are off).\n */\n showTiers?: boolean\n /** The \"replanning failed, continuing with the plan\" warning under a step (default true). */\n showReplanFailed?: boolean\n /**\n * The decision model's note under the step it was asked after - \"decision model: continue\n * (0.93)\" (default true; nothing shows without `decisionModel`).\n */\n showDecisions?: boolean\n /** A `web_search` call's results as a list under its row (default true). */\n showSearchResults?: 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 showTiers = true,\n showReplanFailed = true,\n showDecisions = true,\n showSearchResults = true,\n showSubagents = true,\n renderToolCall,\n renderSubagent,\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 // A subagent is drawn under the step that delegated it (its own subagents come with it: they\n // carry the same step). One whose step is not known is drawn at the end rather than lost.\n const loose = showSubagents ? subagents.filter((s) => !s.stepId || !known.has(s.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 showTiers={showTiers}\n showReplanFailed={showReplanFailed}\n showDecisions={showDecisions}\n showSearchResults={showSearchResults}\n showSubagents={showSubagents}\n renderToolCall={renderToolCall}\n renderSubagent={renderSubagent}\n L={L}\n />\n ))}\n {loose.length > 0 && (\n <li className=\"awr-step awr-step--subagents\">\n <SubagentTree\n subagents={loose}\n onStop={onStopSubagent}\n showUsage={showUsage}\n renderSubagent={renderSubagent}\n />\n </li>\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 { Fragment, useEffect, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport { useLabels, type AgentLabelsOverride } from '../labels.js'\nimport { subagentTree } from '../state.js'\nimport type { SubagentNode, SubagentView } from '../types.js'\nimport { formatDuration, formatTokens, previewValue } from './format.js'\nimport { AlertIcon, BotIcon, SpinnerIcon, StopIcon } from './icons.js'\n\n/** Render a node yourself; `fallback` is the built-in `<li>` (with its children) — return it, or your own `<li>`. */\nexport type RenderSubagent = (node: SubagentNode, fallback: ReactNode) => ReactNode\n\n/** Seconds a running node has been going, ticking; nothing without a start time. */\nconst useElapsed = (startedAt: number | undefined, running: boolean): number | undefined => {\n const [now, setNow] = useState<number | undefined>(undefined)\n useEffect(() => {\n if (!running || startedAt === undefined) return\n setNow(Date.now())\n const timer = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(timer)\n }, [running, startedAt])\n return running && startedAt !== undefined && now !== undefined\n ? Math.max(0, now - startedAt)\n : undefined\n}\n\nexport interface SubagentRowProps {\n sub: SubagentView\n /** Stop this subagent (`useAgent().stopSubagent`); the button shows while it runs. */\n onStop?: (id: string) => void\n /** Its status line: status, model, tokens, tool calls, time (default true). */\n showUsage?: boolean\n /** The tools a helper was given (default true). */\n showTools?: boolean\n labels?: AgentLabelsOverride\n /** The subagents this one started (the tree puts them here). */\n children?: ReactNode\n}\n\n/**\n * One subagent - a static one or a helper the model started: who it is, its task, its status\n * with the model, tokens and time, what it is doing, and its answer when done. With `onStop`,\n * a running one gets a stop button (the run and its siblings go on).\n */\nexport const SubagentRow = ({\n sub,\n onStop,\n showUsage = true,\n showTools = true,\n labels,\n children,\n}: SubagentRowProps) => {\n const L = useLabels(labels)\n const running = sub.status === 'running'\n const elapsed = useElapsed(sub.startedAt, running)\n const time = sub.durationMs ?? elapsed\n // A helper's role is what the model wrote for it: plain text, shown as its name.\n const role = sub.dynamic ? previewValue(sub.role ?? '', 48) : ''\n const meta = [\n sub.model ?? '',\n sub.tier ? L.tierNames[sub.tier] : '',\n sub.usage.totalTokens > 0 ? L.subagentTokens(formatTokens(sub.usage.totalTokens)) : '',\n sub.toolCalls > 0 ? L.toolCalls(sub.toolCalls) : '',\n time !== undefined ? formatDuration(time) : '',\n ].filter(Boolean)\n return (\n <li\n className={`awr-subagent awr-subagent--${sub.status}${sub.dynamic ? ' awr-subagent--dynamic' : ''}`}\n data-depth={sub.depth}\n >\n <div className=\"awr-subagent__head\">\n <span className=\"awr-subagent__icon\">\n {running ? (\n <SpinnerIcon size={13} />\n ) : sub.status === 'done' ? (\n <BotIcon size={13} />\n ) : sub.status === 'stopped' ? (\n <StopIcon size={13} />\n ) : (\n <AlertIcon size={13} />\n )}\n </span>\n <span className=\"awr-subagent__name\" title={sub.role}>\n {role || (sub.dynamic ? L.subagentHelper : sub.name)}\n </span>\n {sub.dynamic && role && <span className=\"awr-subagent__profile\">{L.subagentHelper}</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 {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 {showUsage && (\n <div className=\"awr-subagent__meta\">\n <span className=\"awr-subagent__status\">{L.subagentStatus[sub.status]}</span>\n {meta.map((part, i) => (\n <span key={i} className=\"awr-subagent__metaitem\">\n {part}\n </span>\n ))}\n </div>\n )}\n {showTools && sub.tools && (\n <div className=\"awr-subagent__tools\">\n {sub.tools.length > 0 ? L.subagentTools(sub.tools.join(', ')) : L.subagentNoTools}\n </div>\n )}\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}${!showUsage && sub.toolCalls ? ` · ${L.toolCalls(sub.toolCalls)}` : ''}`}\n </div>\n {children}\n </li>\n )\n}\n\nexport interface SubagentTreeProps {\n /**\n * The subagents to draw (`agent.subagents`, or a message's): static subagents and the helpers\n * the model started, at any depth. The flat list is nested by `parentId`.\n */\n subagents: SubagentView[]\n /** Give each running node a stop button (`useAgent().stopSubagent`). */\n onStop?: (id: string) => void\n /** Each node's status line: status, model, tokens, tool calls, time (default true). */\n showUsage?: boolean\n /** The tools each helper was given (default true). */\n showTools?: boolean\n /** Render a node yourself (gets the built-in `<li>` as `fallback`). */\n renderSubagent?: RenderSubagent\n labels?: AgentLabelsOverride\n className?: string\n}\n\n/**\n * The run's subagents as an indented tree: each node with its status, model, tokens and time,\n * what it is doing, and - while it runs - a stop button. A helper's own helpers sit under it.\n * Renders nothing when there are none.\n */\nexport const SubagentTree = ({\n subagents,\n onStop,\n showUsage = true,\n showTools = true,\n renderSubagent,\n labels,\n className,\n}: SubagentTreeProps) => {\n if (subagents.length === 0) return null\n const branch = (nodes: SubagentNode[], nested: boolean): ReactNode => (\n <ul\n className={['awr-subagents', nested ? 'awr-subagents--nested' : className]\n .filter(Boolean)\n .join(' ')}\n >\n {nodes.map((node) => {\n const row = (\n <SubagentRow\n key={node.id}\n sub={node}\n onStop={onStop}\n showUsage={showUsage}\n showTools={showTools}\n labels={labels}\n >\n {node.children.length > 0 ? branch(node.children, true) : null}\n </SubagentRow>\n )\n return renderSubagent ? <Fragment key={node.id}>{renderSubagent(node, row)}</Fragment> : row\n })}\n </ul>\n )\n return branch(subagentTree(subagents), false)\n}\n","import type { ReactNode } from 'react'\nimport type { IUsage, VirtualFileSystem } from '@dudko.dev/agent-web'\nimport { useLabels, type AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { AppView, ChatAttachment, ChatMessage, MediaView, WrittenFileView } from '../types.js'\nimport { formatDuration, formatTokens } from './format.js'\nimport { BookIcon, BrainIcon, FileIcon, GlobeIcon, SpinnerIcon } from './icons.js'\nimport { FileChips, type FileChipsProps } from './FileChips.js'\nimport { GeneratedMedia, TranscriptBlock } from './Media.js'\nimport { StepList, type RenderToolCall } from './StepList.js'\nimport type { RenderSubagent } from './SubagentTree.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 /** Model tiers: the tier badges, escalation lines and the escalation count (default true). */\n showTiers?: boolean\n /** The \"replanning failed, continuing with the plan\" warning under a step (default true). */\n showReplanFailed?: boolean\n /** The decision model's note under a step (default true; nothing shows without one). */\n showDecisions?: boolean\n /** A `web_search` call's results as a list under its row (default true). */\n showSearchResults?: boolean\n /** The subagent tree under the step that started it (default true). */\n showSubagents?: boolean\n /**\n * What the run generated, in the answer: images inline, audio as a player - and the\n * transcripts of audio files, folded (default true). Needs `files` to show the bytes.\n */\n showMedia?: boolean\n /**\n * The files an answer wrote to the workspace, as chips under it - open (an inline preview;\n * an `.html` file in a sandboxed frame) and download (default true). Needs `files`.\n */\n showFileChips?: boolean\n /** The workspace generated and written files are read from (the core's `VirtualFileSystem`). */\n files?: VirtualFileSystem\n /** How an `.html` file is previewed (see `FileChips`); `false` shows HTML as source only. */\n htmlPreview?: FileChipsProps['htmlPreview']\n /** Adds a \"Show in Files\" link above the chips. */\n onShowFiles?: () => void\n /** A file chip; `fallback` is the built-in one. */\n renderFile?: (file: WrittenFileView, message: ChatMessage, fallback: ReactNode) => ReactNode\n /** A text file rendered your way (Markdown through your renderer); `undefined` = as source. */\n renderFileContent?: FileChipsProps['renderFileContent']\n /** A generated file; `fallback` is the built-in image / player / chip. */\n renderMedia?: (media: MediaView, message: ChatMessage, fallback: ReactNode) => ReactNode\n /** A node of the subagent tree (gets the built-in `<li>` as `fallback`). */\n renderSubagent?: RenderSubagent\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 /**\n * The MCP Apps an answer's tool calls came with (`message.apps`), drawn between its activity\n * and its text. `<AgentChat mcpApps>` passes `<McpAppFrame>`; without this prop none is drawn.\n */\n renderApp?: (app: AppView, message: ChatMessage) => ReactNode\n /** Draw the apps of an answer (default true; needs `renderApp`). */\n showApps?: boolean\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 showTiers: boolean,\n showFileChips: boolean,\n L: AgentLabels,\n showApps = false,\n): string => {\n const steps = m.steps ?? []\n const parts = [L.steps(steps.length)]\n if (showToolCalls) parts.push(L.toolCalls(toolCallCount(m)))\n const escalations = steps.reduce((n, s) => n + (s.escalations?.length ?? 0), 0)\n if (showTiers && escalations > 0) parts.push(L.escalations(escalations))\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 if (showFileChips && m.writtenFiles?.length) parts.push(L.filesCount(m.writtenFiles.length))\n if (showApps && m.apps?.length) parts.push(L.appsCount(m.apps.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 showTiers = true,\n showReplanFailed = true,\n showDecisions = true,\n showSearchResults = true,\n showSubagents = true,\n showMedia = true,\n showFileChips = true,\n files,\n htmlPreview,\n onShowFiles,\n renderFile,\n renderFileContent,\n renderMedia,\n renderSubagent,\n onStopSubagent,\n activityOpen = false,\n liveExtra,\n renderContent,\n renderMessage,\n renderAttachment,\n renderToolCall,\n renderApp,\n showApps = true,\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(\n m,\n showToolCalls,\n showLearned,\n showTiers,\n showFileChips,\n L,\n showApps && Boolean(renderApp),\n )}\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 showTiers={showTiers}\n showReplanFailed={showReplanFailed}\n showDecisions={showDecisions}\n showSearchResults={showSearchResults}\n showSubagents={showSubagents}\n renderToolCall={renderToolCall}\n renderSubagent={renderSubagent}\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 {showApps && renderApp && m.role === 'assistant' && m.apps?.length ? (\n <div className=\"awr-msg__apps\">\n {m.apps.map((app) => (\n <div key={app.id} className=\"awr-msg__app\">\n {renderApp(app, m)}\n </div>\n ))}\n </div>\n ) : null}\n {showMedia && m.transcripts?.length ? (\n <div className=\"awr-msg__transcripts\">\n {m.transcripts.map((t, i) => (\n <TranscriptBlock key={i} transcript={t} labels={labels} />\n ))}\n </div>\n ) : null}\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 {showMedia && m.media?.length ? (\n <div className=\"awr-msg__media\">\n {m.media.map((item, i) => {\n const built = (\n <GeneratedMedia key={i} media={item} files={files} labels={labels} />\n )\n return renderMedia ? (\n <span key={i} className=\"awr-msg__mediaitem\">\n {renderMedia(item, m, built)}\n </span>\n ) : (\n built\n )\n })}\n </div>\n ) : null}\n {showFileChips && m.role === 'assistant' && m.writtenFiles?.length ? (\n <FileChips\n written={m.writtenFiles}\n files={files}\n htmlPreview={htmlPreview}\n onShowFiles={onShowFiles}\n renderFile={renderFile ? (f, fallback) => renderFile(f, m, fallback) : undefined}\n renderFileContent={renderFileContent}\n labels={labels}\n />\n ) : null}\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 AgentLabels, type AgentLabelsOverride } from '../labels.js'\nimport type { ApprovalView, SkillConsentView } 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 /**\n * Offer \"Always allow\" (remembers the tool for the agent's life) - and, on a request about an\n * MCP server's skill, \"Always for this server\" (that server's skills for the agent's life,\n * nested ones excepted). Default true.\n */\n allowRemember?: boolean\n /**\n * On a request about an MCP server's skill: the collapsible preview of the instructions the\n * model would read (plain text). Default true.\n */\n showSkillPreview?: boolean\n /** Say which helper is asking when the call is a helper's, not the run's own (default true). */\n showHelper?: 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 * The card for a request about an MCP server's skill (`approval.skill`): which server offers\n * which skill, its description, size and files, and - collapsed - the very text the model would\n * read. Every string of the server's is a text node in a box captioned as the server's.\n */\nconst SkillConsentCard = ({\n approval: a,\n skill,\n helper,\n L,\n allowRemember,\n showPreview,\n onApprove,\n onDeny,\n}: {\n approval: ApprovalView\n skill: SkillConsentView\n helper: ApprovalView['subagent']\n L: AgentLabels\n allowRemember: boolean\n showPreview: boolean\n onApprove: ToolApprovalPromptProps['onApprove']\n onDeny: ToolApprovalPromptProps['onDeny']\n}) => (\n <div\n className={`awr-approval awr-approval--skill${helper ? ' awr-approval--helper' : ''}`}\n data-skill={skill.name}\n data-skill-server={skill.server}\n data-subagent={helper?.id}\n >\n <div className=\"awr-approval__head\">\n <ShieldIcon size={14} className=\"awr-approval__icon\" />\n <span>{L.skillConsentLead(skill.server, skill.skill)}</span>\n </div>\n {skill.description && <p className=\"awr-approval__quote\">{skill.description}</p>}\n <p className=\"awr-approval__skillmeta\">\n <code className=\"awr-tool__name\">{skill.name}</code>\n <span>{L.skillConsentSize(skill.size, skill.fileCount)}</span>\n </p>\n {skill.byUri && <p className=\"awr-approval__from\">{L.skillConsentByUri}</p>}\n {skill.nestedIn && (\n <p className=\"awr-approval__from awr-approval__nested\">\n {L.skillConsentNested(skill.nestedIn)}\n </p>\n )}\n {skill.dynamic && (\n <p className=\"awr-approval__from awr-approval__dynamic\">{L.skillConsentDynamic}</p>\n )}\n {skill.dynamic && skill.noFileListing && (\n <p className=\"awr-approval__from\">{L.skillConsentNoFileListing}</p>\n )}\n {showPreview && skill.body !== undefined && (\n <details className=\"awr-approval__preview\">\n <summary>{L.skillConsentPreview}</summary>\n <pre className=\"awr-approval__quote awr-approval__body\">{skill.body}</pre>\n {skill.files.length > 0 && (\n <p className=\"awr-approval__from\">\n {L.skillConsentFiles(skill.files.join(', '), skill.fileCount - skill.files.length)}\n </p>\n )}\n </details>\n )}\n <p className=\"awr-approval__from\">{L.skillConsentNote(skill.server, skill.consent)}</p>\n <div className=\"awr-approval__actions\">\n <button type=\"button\" className=\"awr-btn awr-btn--primary\" onClick={() => onApprove(a.id)}>\n {L.skillConsentAllow}\n </button>\n {allowRemember && (\n <button\n type=\"button\"\n className=\"awr-btn\"\n onClick={() => onApprove(a.id, { remember: true })}\n >\n {L.skillConsentAlways}\n </button>\n )}\n <button\n type=\"button\"\n className=\"awr-btn awr-btn--danger\"\n onClick={() => onDeny(a.id, L.skillConsentDeclined)}\n >\n {L.skillConsentDeny}\n </button>\n </div>\n </div>\n)\n\n/**\n * Consent cards for tool calls the agent wants to make — \"Allow once\",\n * \"Always allow\" and \"Deny\" - and for an MCP server's skill about to enter the agent's context\n * (\"Allow once\", \"Always for this server\", \"Deny\"). Wire it to {@link useAgent}'s\n * `pendingApprovals`, `approve` and `deny`; `<AgentChat>` renders it for you.\n */\nexport const ToolApprovalPrompt = ({\n approvals,\n onApprove,\n onDeny,\n allowRemember = true,\n showSkillPreview = true,\n showHelper = 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 if (a.skill) {\n const card = (\n <SkillConsentCard\n key={a.id}\n approval={a}\n skill={a.skill}\n helper={showHelper ? a.subagent : undefined}\n L={L}\n allowRemember={allowRemember}\n showPreview={showSkillPreview}\n onApprove={onApprove}\n onDeny={onDeny}\n />\n )\n return renderApproval ? <div key={a.id}>{renderApproval(a, card)}</div> : card\n }\n // A helper's role is text the model wrote: shown as plain text, shortened.\n const helper = showHelper ? a.subagent : undefined\n // An MCP App asks, not the agent: said in the lead, with the server's own tool name.\n const app = a.app\n const card = (\n <div\n key={a.id}\n className={`awr-approval${helper ? ' awr-approval--helper' : ''}${app ? ' awr-approval--app' : ''}`}\n data-subagent={helper?.id}\n data-app-server={app?.server}\n >\n <div className=\"awr-approval__head\">\n <ShieldIcon size={14} className=\"awr-approval__icon\" />\n <span>\n {app\n ? L.approvalLeadApp(app.server)\n : helper\n ? L.approvalLeadHelper(\n previewValue(helper.role ?? '', 60) || undefined,\n helper.depth,\n )\n : L.approvalLead}{' '}\n <code className=\"awr-tool__name\">{app ? app.tool : a.name}</code>\n {a.readOnly && !app ? ` (${L.readOnlyTool})` : ''}\n </span>\n </div>\n {previewValue(a.input, 300) && (\n <pre className=\"awr-approval__input\">{previewValue(a.input, 300)}</pre>\n )}\n {app && (\n <p className=\"awr-approval__from\">{L.approvalFromApp(app.server, a.readOnly)}</p>\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 { useLabels, type AgentLabelsOverride } from '../labels.js'\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 /**\n * Calls that are not tokens - to the media models and to the decision model - when there were\n * any (default true).\n */\n showCalls?: boolean\n labels?: AgentLabelsOverride\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, and the media / decision calls when the run made\n * some. The full breakdown is on hover.\n */\nexport const UsageBadge = ({\n usage,\n compact = false,\n showCalls = true,\n labels,\n className,\n}: UsageBadgeProps) => {\n const L = useLabels(labels)\n const media = showCalls ? (usage.mediaCalls ?? 0) : 0\n const decisions = showCalls ? (usage.decisionCalls ?? 0) : 0\n if (usage.totalTokens === 0 && media === 0 && decisions === 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 media ? L.usageMedia(media) : '',\n decisions ? L.usageDecisions(decisions) : '',\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 {!compact && media > 0 && ` · ${L.usageMedia(media)}`}\n {!compact && decisions > 0 && ` · ${L.usageDecisions(decisions)}`}\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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ACF;AAAA,UACA,UAAU;AAAA;AAAA,MACZ;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,OAAO;AAAA,UAC3B,UAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OAEJ;AAAA,KACF;AAEJ;;;A7C4FA,IAAAC,oBA0BO;","names":["import_agent_web","req","text","base","m","req","text","approve","import_react","import_react","text","import_react","import_react","import_agent_web","import_agent_web","import_react","model","seq","import_react","text","base","import_react","import_jsx_runtime","text","import_react","import_react","import_agent_web","text","text","refused","LOOPBACK_HOSTS","pageOrigin","base","text","downloadFile","import_jsx_runtime","import_jsx_runtime","import_react","import_jsx_runtime","text","resource","app","host","link","chat","import_react","import_jsx_runtime","useIsoLayoutEffect","readDataUrl","text","import_react","import_jsx_runtime","text","import_jsx_runtime","import_react","import_jsx_runtime","text","import_react","import_jsx_runtime","text","import_react","import_agent_web","import_react","import_agent_web","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","text","import_react","import_react","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","card","import_jsx_runtime","import_jsx_runtime","Composer","import_jsx_runtime","import_react","import_jsx_runtime","text","import_jsx_runtime","import_jsx_runtime","import_react","import_jsx_runtime","import_agent_web"]}