@dudko.dev/agent-web-react 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-agent.ts","../src/state.ts","../src/util.ts","../src/hooks/use-credentials.ts","../src/hooks/use-webllm-model.ts","../src/context.tsx","../src/components/AgentChat.tsx","../src/components/icons.tsx","../src/components/Composer.tsx","../src/components/MessageList.tsx","../src/components/ModelLoadBar.tsx","../src/components/format.ts","../src/components/StepList.tsx","../src/components/UsageBadge.tsx","../src/components/PlanView.tsx","../src/components/ApiKeyForm.tsx","../src/index.ts"],"sourcesContent":["import { useCallback, useEffect, useReducer, useRef, useState } from 'react'\nimport type { DependencyList } from 'react'\nimport {\n createAgent,\n type Agent,\n type AgentEventHandler,\n type BrowserAgentConfig,\n type RunResult,\n} from '@dudko.dev/agent-web'\nimport { agentStateReducer, createInitialAgentState } from '../state.js'\nimport type { AgentUiState } 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\nexport interface UseAgentReturn extends AgentUiState {\n /** Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. */\n run: (goal: string) => Promise<RunResult | undefined>\n /** Abort the in-flight run (observed between phases and mid-stream). */\n stop: () => void\n /** Clear the whole conversation — transcript and current run. */\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}\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, streamed final answer, token\n * usage, model-load progress and a chat transcript), and exposes `run` / `stop`\n * / `reset` / `reload`.\n *\n * ```tsx\n * const agent = useAgent({\n * model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },\n * credentials,\n * tools,\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 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 const reload = useCallback(() => setGeneration((g) => g + 1), [])\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 dispatch({ type: 'status', status: 'idle' })\n return\n }\n let cancelled = false\n dispatch({ type: 'status', status: 'initializing' })\n createAgent(cfg)\n .then((agent) => {\n if (cancelled) return\n agentRef.current = agent\n dispatch({ type: 'status', status: 'ready' })\n })\n .catch((err) => {\n if (cancelled) return\n dispatch({ type: 'status', 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 when the component unmounts.\n useEffect(() => () => abortRef.current?.abort(), [])\n\n const run = useCallback(async (goal: string): 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 dispatch({ type: 'status', status: 'running' })\n try {\n return await agent.run(goal, {\n signal: controller.signal,\n onEvent: (event) => {\n dispatch({ type: 'event', event, maxEvents: optionsRef.current.maxEvents })\n try {\n optionsRef.current.onEvent?.(event)\n } catch {\n /* a bad host handler must not break the run */\n }\n },\n })\n } catch (err) {\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 dispatch({ type: 'status', status: 'ready' })\n }\n }, [])\n\n const stop = useCallback(() => abortRef.current?.abort(), [])\n const reset = useCallback(() => dispatch({ type: 'reset' }), [])\n\n return {\n ...state,\n run,\n stop,\n reset,\n reload,\n agent: agentRef.current,\n isRunning: state.status === 'running',\n isReady: state.status === 'ready',\n }\n}\n","import type { AgentEvent, IUsage } from '@dudko.dev/agent-web'\nimport type { AgentUiState, ChatMessage, StepView, ToolCallView } 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`), so it can be\n * unit-tested in isolation and reused to 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 /** Fold one streamed agent event into the view. */\n | { type: 'event'; event: AgentEvent; maxEvents?: number }\n\nconst emptyUsage = (): IUsage => ({ inputTokens: 0, outputTokens: 0, totalTokens: 0 })\n\nconst addUsage = (a: IUsage, b: IUsage): IUsage => ({\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n})\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 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, status and seq counter. */\nconst resetRun = (state: AgentUiState): AgentUiState => ({\n ...createInitialAgentState(),\n status: state.status,\n messages: state.messages,\n seq: state.seq,\n})\n\n/** Apply `fn` to the step whose id matches, leaving the rest untouched. */\nconst patchStep = (steps: StepView[], id: string, fn: (s: StepView) => StepView): StepView[] =>\n steps.map((s) => (s.id === id ? fn(s) : s))\n\n/** Finalize the trailing pending assistant message with the given content. */\nconst finalizeAssistant = (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: content || m.content, pending: false }\n return next\n }\n }\n return messages\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): 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 messages: [\n ...base.messages,\n { id: userId, role: 'user', content: event.goal, pending: false },\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 { ...state, plan: event.plan, replan: { mode: 'revise', reason: event.reason } }\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 toolCalls: [],\n status: 'running',\n blocked: false,\n }\n return { ...state, steps: [...state.steps, view] }\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 = { name: event.name, input: event.input, status: 'calling' }\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 { ...c, output: event.output, ok: event.ok, status: 'done' as const }\n }\n return c\n })\n .reverse()\n return { ...s, toolCalls }\n }),\n }\n\n case 'step.complete':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n status: 'done',\n summary: event.result.summary,\n blocked: event.result.blocked,\n // The result carries the authoritative, ordered tool-call list.\n toolCalls: event.result.toolCalls.map((c) => ({\n name: c.name,\n input: c.input,\n output: c.output,\n ok: c.ok,\n status: 'done' as const,\n })),\n })),\n }\n\n case 'replan.decision':\n return { ...state, replan: { mode: event.mode, reason: event.reason } }\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),\n }\n\n case 'usage':\n return { ...state, usage: addUsage(state.usage, event.usage) }\n\n case 'stopped':\n return {\n ...state,\n stopped: true,\n messages: finalizeAssistant(state.messages, state.finalText || 'Stopped.'),\n }\n\n case 'error':\n // A per-step ('execute'/'plan'/...) error does not end the run — only a\n // top-level 'run' error does, and it arrives with no trailing `final`.\n return event.phase === 'run'\n ? {\n ...state,\n error: event.error,\n messages: finalizeAssistant(state.messages, state.finalText || `Error: ${event.error}`),\n }\n : { ...state, error: event.error }\n\n case 'retry':\n return state\n\n default:\n return state\n }\n}\n\nexport const agentStateReducer = (state: AgentUiState, action: AgentAction): AgentUiState => {\n switch (action.type) {\n case 'reset':\n // A full \"new conversation\" clear — unlike run.start, this also drops the\n // transcript. Keep status (the agent is still built) and the seq counter\n // (so ids stay unique across resets).\n return { ...createInitialAgentState(), status: state.status, seq: state.seq }\n case 'status':\n return {\n ...state,\n status: action.status,\n error: action.status === 'error' ? action.error : undefined,\n }\n case 'event': {\n const next = applyEvent(state, action.event)\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 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, 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 { useCallback, useRef, useState } from 'react'\nimport {\n createWebLLMModel,\n isWebGPUAvailable,\n preloadWebLLMModel,\n type WebLLMModelOptions,\n} from '@dudko.dev/agent-web'\nimport { errMessage } from '../util.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\nexport interface UseWebLLMModelReturn {\n /** The built model once loaded — pass to `createAgent({ model })`. */\n model: WebLLMModel | undefined\n /** Start the download / engine init. Idempotent-ish: safe to call again to retry. */\n load: () => Promise<WebLLMModel | undefined>\n /** True while weights are downloading / the engine is initializing. */\n loading: boolean\n /** Load progress, 0..1. */\n progress: number\n /** Human-readable progress text from WebLLM. */\n text: string\n /** Error message if the load failed. */\n error: string | undefined\n /** Whether WebGPU is available (required for local models). */\n supported: boolean\n /** True once the model is ready. */\n ready: boolean\n}\n\n/**\n * Load a local WebGPU model with WebLLM and track its download progress.\n * Nothing downloads until you call `load()` (models are large), so you can\n * gate it behind a user action. `load()` eagerly initializes the engine (via\n * the core's `preloadWebLLMModel`), so `ready` means \"ready to chat\" and\n * progress fills during the load rather than silently on the first message.\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 const [model, setModel] = useState<WebLLMModel | undefined>(undefined)\n const [loading, setLoading] = useState(false)\n const [progress, setProgress] = useState(0)\n const [text, setText] = useState('')\n const [error, setError] = useState<string | undefined>(undefined)\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const load = useCallback(async (): Promise<WebLLMModel | undefined> => {\n if (!isWebGPUAvailable()) {\n setError('WebGPU is not available in this browser.')\n return undefined\n }\n setLoading(true)\n setError(undefined)\n setProgress(0)\n setText('')\n try {\n const { create = createWebLLMModel, ...modelOptions } = optionsRef.current ?? {}\n const built = await create(modelId, {\n ...modelOptions,\n // Drive preload here (below) so download progress is reported the same\n // way whether `create` is the core's `createWebLLMModel` or an injected\n // factory (e.g. a statically-imported `webLLM`, needed under bundlers).\n preload: false,\n initProgressCallback: (report) => {\n setProgress(report.progress)\n setText(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 await preloadWebLLMModel(built)\n setModel(built)\n return built\n } catch (err) {\n setError(errMessage(err))\n return undefined\n } finally {\n setLoading(false)\n }\n }, [modelId])\n\n return {\n model,\n load,\n loading,\n progress,\n text,\n error,\n supported: isWebGPUAvailable(),\n ready: model !== undefined,\n }\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 } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { useOptionalAgentContext } from '../context.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { AlertIcon } from './icons.js'\nimport { Composer } from './Composer.js'\nimport { MessageList } from './MessageList.js'\nimport { ModelLoadBar } from './ModelLoadBar.js'\nimport { StepList } from './StepList.js'\nimport { UsageBadge } from './UsageBadge.js'\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 placeholder?: string\n /** Render the internal plan/step activity while the agent works (default true). */\n showActivity?: boolean\n /** Render the token-usage badge in the footer (default true). */\n showUsage?: boolean\n /** Content shown before the first message. */\n emptyState?: ReactNode\n className?: string\n /** Inline styles on the root — handy for sizing (e.g. `{ height: 520 }`). */\n style?: CSSProperties\n}\n\nconst statusLabel = (status: UseAgentReturn['status']): string => {\n switch (status) {\n case 'initializing':\n return 'Loading model…'\n case 'running':\n return 'Working…'\n case 'error':\n return 'Failed to start'\n default:\n return 'Ready'\n }\n}\n\n/**\n * A drop-in chat panel: transcript, live plan/step activity with tool calls, a\n * streamed final answer, model-load progress, token usage, and a composer with\n * a stop button. Give it a `controller` from {@link useAgent}, or wrap it in an\n * {@link AgentProvider} and it will find one.\n *\n * ```tsx\n * <AgentProvider config={{ model, tools, credentials }}>\n * <AgentChat title=\"Assistant\" />\n * </AgentProvider>\n * ```\n */\nexport const AgentChat = ({\n controller,\n title,\n placeholder,\n showActivity = true,\n showUsage = true,\n emptyState = 'Ask the agent to do something.',\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\n const bodyRef = useRef<HTMLDivElement>(null)\n useEffect(() => {\n const el = bodyRef.current\n if (el) el.scrollTop = el.scrollHeight\n }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad])\n\n const showReplan = agent.replan && agent.replan.mode !== 'continue'\n const loading = agent.modelLoad && agent.modelLoad.progress < 1 && agent.isRunning === false\n\n return (\n <div className={['awr-chat', className].filter(Boolean).join(' ')} style={style}>\n {title && <div className=\"awr-chat__title\">{title}</div>}\n\n <div className=\"awr-chat__body\" ref={bodyRef}>\n <MessageList messages={agent.messages} empty={emptyState} />\n\n {showActivity && (agent.steps.length > 0 || agent.planThought) && (\n <div className=\"awr-activity\">\n {agent.planThought.trim() && (\n <details className=\"awr-activity__plan\">\n <summary>Plan</summary>\n <p className=\"awr-activity__thought\">{agent.planThought}</p>\n </details>\n )}\n <StepList steps={agent.steps} />\n {showReplan && (\n <div className=\"awr-activity__replan\">\n Replanned ({agent.replan!.mode}): {agent.replan!.reason}\n </div>\n )}\n </div>\n )}\n\n {agent.modelLoad && (loading || agent.isRunning) && agent.modelLoad.progress < 1 && (\n <ModelLoadBar load={agent.modelLoad} />\n )}\n </div>\n\n {agent.error && agent.status === 'error' && (\n <div className=\"awr-chat__error\">\n <AlertIcon size={14} /> {agent.error}\n </div>\n )}\n\n <div className=\"awr-chat__footer\">\n <div className=\"awr-chat__meta\">\n <span className={`awr-status awr-status--${agent.status}`}>\n <span className=\"awr-status__dot\" />\n {statusLabel(agent.status)}\n </span>\n {showUsage && <UsageBadge usage={agent.usage} />}\n </div>\n <Composer\n onSubmit={(text) => void agent.run(text)}\n busy={agent.isRunning}\n onStop={agent.stop}\n disabled={!agent.isReady && !agent.isRunning}\n placeholder={placeholder}\n />\n </div>\n </div>\n )\n}\n","// Tiny inline SVG icons — no icon-font or image dependency. Each inherits the\n// current text color (`stroke=\"currentColor\"`) and takes an optional size.\n\nexport interface IconProps {\n size?: number\n className?: string\n}\n\nconst base = (size = 16) => ({\n width: size,\n height: size,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round' as const,\n strokeLinejoin: 'round' as const,\n 'aria-hidden': true,\n})\n\nexport const SendIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M22 2 11 13\" />\n <path d=\"M22 2 15 22l-4-9-9-4Z\" />\n </svg>\n)\n\nexport const StopIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n </svg>\n)\n\nexport const SpinnerIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={['awr-spin', className].filter(Boolean).join(' ')}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </svg>\n)\n\nexport const CheckIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n)\n\nexport const AlertIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </svg>\n)\n\nexport const ToolIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z\" />\n </svg>\n)\n\nexport const ChevronIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n)\n","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 { ReactNode } from 'react'\nimport type { ChatMessage } from '../types.js'\nimport { SpinnerIcon } from './icons.js'\n\nexport interface MessageListProps {\n messages: ChatMessage[]\n /** Rendered when there are no messages yet. */\n empty?: ReactNode\n className?: string\n}\n\n/** The chat transcript: user and assistant turns, with a streaming indicator. */\nexport const MessageList = ({ messages, empty, className }: MessageListProps) => {\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 <div key={m.id} className={`awr-msg awr-msg--${m.role}`}>\n <div className=\"awr-msg__bubble\">\n {m.content}\n {m.pending && !m.content && <SpinnerIcon size={14} className=\"awr-msg__pending\" />}\n </div>\n </div>\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","/** 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","import type { StepView, ToolCallView } from '../types.js'\nimport { previewValue } from './format.js'\nimport { AlertIcon, CheckIcon, SpinnerIcon, ToolIcon } from './icons.js'\n\nconst ToolCallRow = ({ call }: { call: ToolCallView }) => {\n const state = call.status === 'calling' ? 'calling' : call.ok === false ? 'failed' : 'ok'\n return (\n <li className={`awr-tool awr-tool--${state}`}>\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\">failed</span>\n )}\n </li>\n )\n}\n\nconst StepItem = ({ step }: { step: StepView }) => (\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 {step.text.trim() && <p className=\"awr-step__text\">{step.text.trim()}</p>}\n {step.toolCalls.length > 0 && (\n <ul className=\"awr-step__tools\">\n {step.toolCalls.map((call, i) => (\n <ToolCallRow key={i} call={call} />\n ))}\n </ul>\n )}\n {step.blocked && step.summary && <p className=\"awr-step__blocked\">{step.summary}</p>}\n </li>\n)\n\nexport interface StepListProps {\n steps: StepView[]\n className?: string\n}\n\n/** The live execution: each step, its streamed text, and its tool calls. */\nexport const StepList = ({ steps, className }: StepListProps) => {\n if (steps.length === 0) return null\n return (\n <ol className={['awr-steps', className].filter(Boolean).join(' ')}>\n {steps.map((step) => (\n <StepItem key={step.id} step={step} />\n ))}\n </ol>\n )\n}\n","import type { IUsage } from '@dudko.dev/agent-web'\n\nexport interface UsageBadgeProps {\n usage: IUsage\n className?: string\n}\n\nconst fmt = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n)\n\n/** A compact token-usage readout (in → out, and total on hover). */\nexport const UsageBadge = ({ usage, className }: UsageBadgeProps) => {\n if (usage.totalTokens === 0) return null\n return (\n <span\n className={['awr-usage', className].filter(Boolean).join(' ')}\n title={`${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`}\n >\n {fmt(usage.inputTokens)}↑ {fmt(usage.outputTokens)}↓\n </span>\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 { useEffect, useState } from 'react'\nimport type { UseCredentialsReturn } from '../hooks/use-credentials.js'\nimport { CheckIcon } from './icons.js'\n\nexport interface ApiKeyFormProps {\n /** The value returned by {@link useCredentials}. */\n credentials: UseCredentialsReturn\n /** The ref id under which the key is stored (matches your `credentialRef`). */\n credentialRef: string\n label?: string\n placeholder?: string\n /** Called after a key is saved or removed (e.g. to `reload()` the agent). */\n onChange?: (present: boolean) => void\n className?: string\n}\n\n/**\n * A BYOK key input that stores the key **encrypted at rest** via\n * {@link useCredentials}. Shows a \"saved\" state when a key already exists and\n * lets the user replace or remove it. The plaintext key never leaves the form.\n */\nexport const ApiKeyForm = ({\n credentials,\n credentialRef,\n label = 'API key',\n placeholder = 'sk-…',\n onChange,\n className,\n}: ApiKeyFormProps) => {\n const [value, setValue] = useState('')\n const [present, setPresent] = useState(false)\n const [busy, setBusy] = useState(false)\n\n useEffect(() => {\n let active = true\n credentials.hasKey(credentialRef).then((has) => {\n if (active) setPresent(has)\n })\n return () => {\n active = false\n }\n }, [credentials, credentialRef, credentials.version])\n\n const save = async () => {\n const key = value.trim()\n if (!key) return\n setBusy(true)\n try {\n await credentials.setKey(credentialRef, key)\n setValue('')\n setPresent(true)\n onChange?.(true)\n } finally {\n setBusy(false)\n }\n }\n\n const remove = async () => {\n setBusy(true)\n try {\n await credentials.removeKey(credentialRef)\n setPresent(false)\n onChange?.(false)\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <div className={['awr-keyform', className].filter(Boolean).join(' ')}>\n <label className=\"awr-keyform__label\">\n {label}\n {present && (\n <span className=\"awr-keyform__saved\">\n <CheckIcon size={12} /> stored, encrypted\n </span>\n )}\n </label>\n <div className=\"awr-keyform__row\">\n <input\n className=\"awr-keyform__input\"\n type=\"password\"\n autoComplete=\"off\"\n value={value}\n placeholder={present ? '•••••••• (replace)' : placeholder}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n void save()\n }\n }}\n disabled={busy}\n />\n <button\n type=\"button\"\n className=\"awr-keyform__btn\"\n onClick={() => void save()}\n disabled={busy || !value.trim()}\n >\n Save\n </button>\n {present && (\n <button\n type=\"button\"\n className=\"awr-keyform__btn awr-keyform__btn--ghost\"\n onClick={() => void remove()}\n disabled={busy}\n >\n Remove\n </button>\n )}\n </div>\n </div>\n )\n}\n","// ── Hooks ────────────────────────────────────────────────────────────────────\nexport { useAgent } from './hooks/use-agent.js'\nexport type { UseAgentOptions, UseAgentReturn } from './hooks/use-agent.js'\nexport { useCredentials } from './hooks/use-credentials.js'\nexport type { UseCredentialsReturn } from './hooks/use-credentials.js'\nexport { useWebLLMModel } from './hooks/use-webllm-model.js'\nexport type {\n UseWebLLMModelReturn,\n UseWebLLMModelOptions,\n WebLLMModelFactory,\n} from './hooks/use-webllm-model.js'\n\n// ── Context ──────────────────────────────────────────────────────────────────\nexport { AgentProvider, useAgentContext, useOptionalAgentContext } from './context.js'\nexport type { AgentProviderProps } from './context.js'\n\n// ── Headless state (the pure event → UI reducer, for custom UIs) ─────────────\nexport { agentStateReducer, createInitialAgentState } from './state.js'\nexport type { AgentAction } from './state.js'\nexport type {\n AgentUiState,\n AgentStatus,\n ChatMessage,\n StepView,\n ToolCallView,\n ModelLoadState,\n ReplanState,\n} from './types.js'\n\n// ── Components (optional, pre-styled — import '@dudko.dev/agent-web-react/styles.css') ─\nexport { AgentChat } from './components/AgentChat.js'\nexport type { AgentChatProps } from './components/AgentChat.js'\nexport { MessageList } from './components/MessageList.js'\nexport type { MessageListProps } from './components/MessageList.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 } from './components/StepList.js'\nexport type { StepListProps } from './components/StepList.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 createWebLLMModel,\n preloadWebLLMModel,\n unloadWebLLMModel,\n isWebGPUAvailable,\n VaultCredentialStore,\n MemoryCredentialStore,\n} from '@dudko.dev/agent-web'\nexport type {\n Agent,\n RunOptions,\n RunResult,\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} from '@dudko.dev/agent-web'\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,YAAY,QAAQ,gBAAgB;AAErE;AAAA,EACE;AAAA,OAKK;;;ACSP,IAAM,aAAa,OAAe,EAAE,aAAa,GAAG,cAAc,GAAG,aAAa,EAAE;AAEpF,IAAM,WAAW,CAAC,GAAW,OAAuB;AAAA,EAClD,aAAa,EAAE,cAAc,EAAE;AAAA,EAC/B,cAAc,EAAE,eAAe,EAAE;AAAA,EACjC,aAAa,EAAE,cAAc,EAAE;AACjC;AAGO,IAAM,0BAA0B,OAAqB;AAAA,EAC1D,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO,CAAC;AAAA,EACR,WAAW;AAAA,EACX,OAAO,WAAW;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,SAAS;AAAA,EACT,UAAU,CAAC;AAAA,EACX,QAAQ,CAAC;AAAA,EACT,KAAK;AACP;AAGA,IAAM,WAAW,CAAC,WAAuC;AAAA,EACvD,GAAG,wBAAwB;AAAA,EAC3B,QAAQ,MAAM;AAAA,EACd,UAAU,MAAM;AAAA,EAChB,KAAK,MAAM;AACb;AAGA,IAAM,YAAY,CAAC,OAAmB,IAAY,OAChD,MAAM,IAAI,CAAC,MAAO,EAAE,OAAO,KAAK,GAAG,CAAC,IAAI,CAAE;AAG5C,IAAM,oBAAoB,CAAC,UAAyB,YAAmC;AACrF,WAAS,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;AAC7C,UAAM,IAAI,SAAS,CAAC;AACpB,QAAI,EAAE,SAAS,eAAe,EAAE,SAAS;AACvC,YAAM,OAAO,SAAS,MAAM;AAC5B,WAAK,CA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,EACA,wBAAAC;AAAA,EACA;AAAA,OACK;","names":["base","useCallback","useState","useCallback","useRef","useState","useState","useRef","useCallback","useEffect","useRef","jsx","useState","jsx","jsxs","useState","jsx","jsxs","jsx","jsxs","jsx","jsxs","jsxs","jsx","jsxs","useRef","useEffect","jsx","jsxs","useEffect","useState","jsx","jsxs","useState","useEffect","createAgent","createWebLLMModel","preloadWebLLMModel","isWebGPUAvailable","VaultCredentialStore"]}
1
+ {"version":3,"sources":["../src/hooks/use-agent.ts","../src/state.ts","../src/util.ts","../src/hooks/use-credentials.ts","../src/hooks/use-mcp.ts","../src/hooks/use-webllm-model.ts","../src/context.tsx","../src/components/AgentChat.tsx","../src/components/icons.tsx","../src/components/Composer.tsx","../src/components/MessageList.tsx","../src/components/ModelLoadBar.tsx","../src/components/format.ts","../src/components/StepList.tsx","../src/components/UsageBadge.tsx","../src/components/PlanView.tsx","../src/components/ApiKeyForm.tsx","../src/index.ts"],"sourcesContent":["import { useCallback, useEffect, useReducer, useRef, useState } from 'react'\nimport type { DependencyList } from 'react'\nimport {\n createAgent,\n type Agent,\n type AgentEventHandler,\n type BrowserAgentConfig,\n type RunResult,\n} from '@dudko.dev/agent-web'\nimport { agentStateReducer, createInitialAgentState } from '../state.js'\nimport type { AgentUiState } 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\nexport interface UseAgentReturn extends AgentUiState {\n /** Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. */\n run: (goal: string) => Promise<RunResult | undefined>\n /** Abort the in-flight run (observed between phases and mid-stream). */\n stop: () => void\n /** Clear the whole conversation — transcript and current run. */\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}\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, streamed final answer, token\n * usage, model-load progress and a chat transcript), and exposes `run` / `stop`\n * / `reset` / `reload`.\n *\n * ```tsx\n * const agent = useAgent({\n * model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },\n * credentials,\n * tools,\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 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 const reload = useCallback(() => setGeneration((g) => g + 1), [])\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 dispatch({ type: 'status', status: 'idle' })\n return\n }\n let cancelled = false\n dispatch({ type: 'status', status: 'initializing' })\n createAgent(cfg)\n .then((agent) => {\n if (cancelled) return\n agentRef.current = agent\n dispatch({ type: 'status', status: 'ready' })\n })\n .catch((err) => {\n if (cancelled) return\n dispatch({ type: 'status', 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 when the component unmounts.\n useEffect(() => () => abortRef.current?.abort(), [])\n\n const run = useCallback(async (goal: string): 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 dispatch({ type: 'status', status: 'running' })\n try {\n return await agent.run(goal, {\n signal: controller.signal,\n onEvent: (event) => {\n dispatch({ type: 'event', event, maxEvents: optionsRef.current.maxEvents })\n try {\n optionsRef.current.onEvent?.(event)\n } catch {\n /* a bad host handler must not break the run */\n }\n },\n })\n } catch (err) {\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 dispatch({ type: 'status', status: 'ready' })\n }\n }, [])\n\n const stop = useCallback(() => abortRef.current?.abort(), [])\n const reset = useCallback(() => dispatch({ type: 'reset' }), [])\n\n return {\n ...state,\n run,\n stop,\n reset,\n reload,\n agent: agentRef.current,\n isRunning: state.status === 'running',\n isReady: state.status === 'ready',\n }\n}\n","import type { AgentEvent, IUsage } from '@dudko.dev/agent-web'\nimport type { AgentUiState, ChatMessage, StepView, ToolCallView } 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`), so it can be\n * unit-tested in isolation and reused to 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 /** Fold one streamed agent event into the view. */\n | { type: 'event'; event: AgentEvent; maxEvents?: number }\n\nconst emptyUsage = (): IUsage => ({ inputTokens: 0, outputTokens: 0, totalTokens: 0 })\n\nconst addUsage = (a: IUsage, b: IUsage): IUsage => ({\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n})\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 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, status and seq counter. */\nconst resetRun = (state: AgentUiState): AgentUiState => ({\n ...createInitialAgentState(),\n status: state.status,\n messages: state.messages,\n seq: state.seq,\n})\n\n/** Apply `fn` to the step whose id matches, leaving the rest untouched. */\nconst patchStep = (steps: StepView[], id: string, fn: (s: StepView) => StepView): StepView[] =>\n steps.map((s) => (s.id === id ? fn(s) : s))\n\n/** Finalize the trailing pending assistant message with the given content. */\nconst finalizeAssistant = (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: content || m.content, pending: false }\n return next\n }\n }\n return messages\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): 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 messages: [\n ...base.messages,\n { id: userId, role: 'user', content: event.goal, pending: false },\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 { ...state, plan: event.plan, replan: { mode: 'revise', reason: event.reason } }\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 toolCalls: [],\n status: 'running',\n blocked: false,\n }\n return { ...state, steps: [...state.steps, view] }\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 = { name: event.name, input: event.input, status: 'calling' }\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 { ...c, output: event.output, ok: event.ok, status: 'done' as const }\n }\n return c\n })\n .reverse()\n return { ...s, toolCalls }\n }),\n }\n\n case 'step.complete':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n status: 'done',\n summary: event.result.summary,\n blocked: event.result.blocked,\n // The result carries the authoritative, ordered tool-call list.\n toolCalls: event.result.toolCalls.map((c) => ({\n name: c.name,\n input: c.input,\n output: c.output,\n ok: c.ok,\n status: 'done' as const,\n })),\n })),\n }\n\n case 'replan.decision':\n return { ...state, replan: { mode: event.mode, reason: event.reason } }\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),\n }\n\n case 'usage':\n return { ...state, usage: addUsage(state.usage, event.usage) }\n\n case 'stopped':\n return {\n ...state,\n stopped: true,\n messages: finalizeAssistant(state.messages, state.finalText || 'Stopped.'),\n }\n\n case 'error':\n // A per-step ('execute'/'plan'/...) error does not end the run — only a\n // top-level 'run' error does, and it arrives with no trailing `final`.\n return event.phase === 'run'\n ? {\n ...state,\n error: event.error,\n messages: finalizeAssistant(state.messages, state.finalText || `Error: ${event.error}`),\n }\n : { ...state, error: event.error }\n\n case 'retry':\n return state\n\n default:\n return state\n }\n}\n\nexport const agentStateReducer = (state: AgentUiState, action: AgentAction): AgentUiState => {\n switch (action.type) {\n case 'reset':\n // A full \"new conversation\" clear — unlike run.start, this also drops the\n // transcript. Keep status (the agent is still built) and the seq counter\n // (so ids stay unique across resets).\n return { ...createInitialAgentState(), status: state.status, seq: state.seq }\n case 'status':\n return {\n ...state,\n status: action.status,\n error: action.status === 'error' ? action.error : undefined,\n }\n case 'event': {\n const next = applyEvent(state, action.event)\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 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, 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 { useCallback, useEffect, useRef, useState } from 'react'\nimport type { AgentToolSet } from '@dudko.dev/agent-web'\nimport type {\n BrowserOAuthProvider,\n ConnectedMcp,\n McpCatalogEntry,\n McpModule,\n McpOAuthCallback,\n McpServerResult,\n} from '../mcp-types.js'\n\nexport type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error'\n\nexport interface McpConnectOptions {\n /** The server's StreamableHTTP endpoint. */\n url: string\n /** Prefix for the discovered tool names (\"<name>__<tool>\"). Default 'mcp'. */\n name?: string\n /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */\n headers?: Record<string, string>\n /**\n * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core\n * that ships the OAuth provider; check `oauthSupported` before offering it.\n */\n oauth?: boolean | { redirectUrl?: string; scope?: string; clientName?: string }\n}\n\nexport interface UseMcpOptions {\n /** Client name reported to the MCP server during initialize. */\n clientName?: string\n /** Called with connector log lines — handy while debugging a server. */\n onLog?: (level: string, message: string) => void\n}\n\nexport interface UseMcpReturn {\n status: McpStatus\n /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */\n tools?: AgentToolSet\n catalog: McpCatalogEntry[]\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n /**\n * Whether the installed core exposes the OAuth API. `undefined` until the\n * optional subpath has been loaded once — call `checkOAuthSupport()` to\n * resolve it before offering OAuth in your UI.\n */\n oauthSupported?: boolean\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n connect: (options: McpConnectOptions) => Promise<void>\n disconnect: () => Promise<void>\n /** Navigate to the authorization server. Call it from a user gesture. */\n authorize: () => void\n /** Drop the stored tokens and dynamic registration for the current server. */\n forgetAuthorization: () => Promise<void>\n /** Load the optional subpath and report whether it can do OAuth. */\n checkOAuthSupport: () => Promise<boolean>\n}\n\nconst OAUTH_UNSUPPORTED =\n 'The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.'\n\nconst PENDING_KEY = 'agent-web-react:mcp:pending'\nconst OAUTH_KEY = 'agent-web-react:mcp:oauth'\n\ninterface OAuthRecord {\n url: string\n name?: string\n redirectUrl: string\n scope?: string\n clientName?: string\n /** When the redirect was started, so a stale record can't claim a callback. */\n startedAt?: number\n}\n\n// A round-trip to an authorization server and back takes seconds. Anything\n// older than this is not the flow that produced the ?code= we are looking at —\n// most likely another sign-in on the same page — so we leave it alone.\nconst PENDING_TTL_MS = 10 * 60 * 1000\n\nlet modulePromise: Promise<McpModule> | undefined\n\n/**\n * Load the core's optional `./mcp` subpath. Kept dynamic so apps that never\n * touch MCP don't pull `@modelcontextprotocol/sdk` into their bundle, and so a\n * core without the OAuth half degrades to a clear message instead of a crash.\n */\nconst loadMcp = (): Promise<McpModule> => {\n modulePromise ??= import('@dudko.dev/agent-web/mcp')\n .then((m) => m as unknown as McpModule)\n .catch((err: unknown) => {\n // A rejected promise is neither null nor undefined, so ??= would cache\n // the failure forever — one flaky chunk fetch would kill MCP for the tab.\n modulePromise = undefined\n throw err\n })\n return modulePromise\n}\n\n/** Map a single server's connect outcome onto the hook's status. Pure. */\nexport const describeMcpResult = (\n result: McpServerResult | undefined,\n): { status: McpStatus; error?: string } => {\n if (!result) return { status: 'error', error: 'The connector returned no result for the server' }\n if (result.connected) return { status: 'connected' }\n if (result.needsAuthorization) return { status: 'needs-authorization' }\n return { status: 'error', error: result.error ?? 'Could not connect to the MCP server' }\n}\n\nconst OAUTH_PARAMS = ['code', 'state', 'error', 'error_description', 'iss']\n\n/**\n * Read the authorization-code parameters out of a URL **synchronously**.\n *\n * The core exports an equivalent, but it lives behind a dynamic import: by the\n * time that import resolves, React has flushed the rest of the app's effects,\n * and any one of them may have rewritten `location` (the demo's own view\n * router did exactly that). The callback has to be captured before the first\n * await, so this parser is duplicated here on purpose.\n *\n * Reads the query string and, for hash-routed apps, the fragment. Returns\n * undefined when neither a `code` nor an `error` is present.\n */\nexport const readCallbackParams = (href?: string): McpOAuthCallback | undefined => {\n const target =\n href ?? (typeof globalThis.location !== 'undefined' ? globalThis.location.href : undefined)\n if (!target) return undefined\n let url: URL\n try {\n url = new URL(target)\n } catch {\n return undefined\n }\n const params = new URLSearchParams(url.search)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {\n if (!params.has(k)) params.set(k, v)\n }\n }\n const code = params.get('code') ?? undefined\n const error = params.get('error') ?? undefined\n if (!code && !error) return undefined\n return {\n code,\n state: params.get('state') ?? undefined,\n error,\n errorDescription: params.get('error_description') ?? undefined,\n }\n}\n\n/**\n * Remove the OAuth response parameters from a URL, leaving the rest intact —\n * query string and fragment alike. The code is single-use and lands in history,\n * referrers and screenshots, so it goes as soon as it has been read.\n */\nexport const stripOAuthParams = (href: string): string => {\n const url = new URL(href)\n for (const key of OAUTH_PARAMS) url.searchParams.delete(key)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n const params = new URLSearchParams(hash.slice(q + 1))\n for (const key of OAUTH_PARAMS) params.delete(key)\n const rest = params.toString()\n url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q)\n }\n return url.toString()\n}\n\n// An authorization code is single-use, and React StrictMode mounts every effect\n// twice in development. Claiming happens synchronously, before any await, so\n// the second pass cannot race the first into the token endpoint (where it would\n// lose the state check and report a CSRF failure on a perfectly good flow).\nconst claimedCallbacks = new Set<string>()\n\nexport const claimOAuthCallback = (callback: McpOAuthCallback): boolean => {\n const key = `${callback.code ?? ''}|${callback.state ?? ''}|${callback.error ?? ''}`\n if (claimedCallbacks.has(key)) return false\n claimedCallbacks.add(key)\n return true\n}\n\nconst readRecord = <T>(key: string): T | undefined => {\n try {\n const raw = globalThis.localStorage?.getItem(key)\n return raw ? (JSON.parse(raw) as T) : undefined\n } catch {\n return undefined\n }\n}\n\nconst writeRecord = (key: string, value: unknown): void => {\n try {\n if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value))\n else globalThis.localStorage?.removeItem(key)\n } catch {\n // Private mode / storage disabled: the OAuth round-trip simply won't\n // resume automatically, which the UI already handles.\n }\n}\n\n// A redirect_uri must not carry a fragment (RFC 6749 §3.1.2), and it has to\n// match the registered value byte-for-byte, so query and hash are dropped.\nconst defaultRedirectUrl = (): string =>\n typeof globalThis.location === 'undefined'\n ? ''\n : `${globalThis.location.origin}${globalThis.location.pathname}`\n\n/**\n * Did this error come from the server refusing our authorization?\n *\n * Identity, not strings: the SDK's `UnauthorizedError` never assigns\n * `this.name` (so it reads as \"Error\"), and its message would also match a\n * tool whose own error text mentions \"unauthorized\" — the connector throws a\n * failing tool's text verbatim. The class is re-exported by the core's `./mcp`\n * subpath for exactly this; `constructor.name` is the fallback for a core too\n * old to export it.\n */\nexport const isUnauthorizedError = (err: unknown, mod?: McpModule): boolean => {\n if (!(err instanceof Error)) return false\n if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true\n return err.constructor?.name === 'UnauthorizedError'\n}\n\n/**\n * Wrap each tool so a mid-session authorization failure is visible. Without\n * this the panel keeps reporting \"connected\" while every call fails: the core\n * refreshes silently on a 401, but once the refresh token is gone (revoked,\n * expired) it can only ask for a new authorization.\n */\nconst watchAuthorization = (\n tools: AgentToolSet,\n mod: McpModule,\n onUnauthorized: () => void,\n): AgentToolSet => {\n const entries = Object.entries(tools as Record<string, unknown>).map(([name, value]) => {\n const tool = value as { execute?: (args: unknown, options: unknown) => unknown }\n if (typeof tool.execute !== 'function') return [name, value]\n const execute = tool.execute.bind(tool)\n const watched = (args: unknown, options: unknown): unknown => {\n // Deliberately not an async function: the AI SDK inspects what `execute`\n // returns SYNCHRONOUSLY to decide whether a tool streams (isAsyncIterable),\n // so wrapping everything in a promise would collapse a streaming tool into\n // a single opaque result.\n try {\n const out = execute(args, options)\n if (out && typeof (out as Promise<unknown>).then === 'function') {\n return (out as Promise<unknown>).then(undefined, (err: unknown) => {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n })\n }\n return out\n } catch (err) {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n }\n }\n return [name, { ...(value as object), execute: watched }]\n })\n return Object.fromEntries(entries) as AgentToolSet\n}\n\n/**\n * Connect the browser agent to a remote MCP server the user names at runtime —\n * static header, or full OAuth 2.1 with dynamic client registration.\n *\n * The OAuth round-trip leaves the page, so the hook persists what it needs to\n * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL\n * and reconnects, all before the app renders anything MCP-related.\n *\n * ```tsx\n * const mcp = useMcp()\n * // await mcp.connect({ url, oauth: true })\n * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>\n * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>\n * ```\n */\nexport const useMcp = (options: UseMcpOptions = {}): UseMcpReturn => {\n const [status, setStatus] = useState<McpStatus>('idle')\n const [tools, setTools] = useState<AgentToolSet | undefined>(undefined)\n const [catalog, setCatalog] = useState<McpCatalogEntry[]>([])\n const [error, setError] = useState<string | undefined>(undefined)\n const [authorizationUrl, setAuthorizationUrl] = useState<string | undefined>(undefined)\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompletingAuthorization] = useState(\n () => readCallbackParams() !== undefined,\n )\n\n const connectionRef = useRef<ConnectedMcp | undefined>(undefined)\n const providerRef = useRef<BrowserOAuthProvider | undefined>(undefined)\n // Bumped by every connect / disconnect / unmount. A handshake that finishes\n // after its epoch has passed closes itself instead of writing state or\n // leaking an open MCP session onto a dead component.\n const epochRef = useRef(0)\n // Options land in a ref so `connect` keeps a stable identity: it is a natural\n // dependency of effects in host components.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const closeConnection = useCallback(async () => {\n const open = connectionRef.current\n connectionRef.current = undefined\n if (open) await open.close().catch(() => {})\n }, [])\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n const connect = useCallback(\n async (opts: McpConnectOptions) => {\n const epoch = ++epochRef.current\n const current = () => epochRef.current === epoch\n await closeConnection()\n if (!current()) return\n setStatus('connecting')\n setError(undefined)\n setAuthorizationUrl(undefined)\n setTools(undefined)\n setCatalog([])\n\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n const name = opts.name ?? 'mcp'\n let authProvider: BrowserOAuthProvider | undefined\n\n if (opts.oauth) {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n const oauth = typeof opts.oauth === 'object' ? opts.oauth : {}\n const record: OAuthRecord = {\n url: opts.url,\n name,\n redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),\n scope: oauth.scope,\n clientName: oauth.clientName ?? optionsRef.current.clientName,\n startedAt: Date.now(),\n }\n authProvider = new mod.BrowserOAuthProvider({\n serverUrl: record.url,\n redirectUrl: record.redirectUrl,\n clientName: record.clientName,\n scope: record.scope,\n })\n providerRef.current = authProvider\n // `pending` resumes the redirect; `oauth` outlives it so tokens stay\n // addressable for forgetAuthorization() after a reload.\n writeRecord(PENDING_KEY, record)\n writeRecord(OAUTH_KEY, record)\n } else {\n providerRef.current = undefined\n }\n\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: opts.url,\n headers: opts.oauth ? undefined : opts.headers,\n authProvider,\n },\n },\n { clientName: optionsRef.current.clientName, onLog: optionsRef.current.onLog },\n )\n\n if (!current()) {\n // Unmounted, or another connect started while we were shaking hands.\n await connection.close().catch(() => {})\n return\n }\n\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = authProvider?.authorizationUrl\n setAuthorizationUrl(url ? String(url) : undefined)\n setStatus('needs-authorization')\n return\n }\n throw new Error(outcome.error)\n }\n\n connectionRef.current = connection\n // The round-trip is over: a stale record would later make an unrelated\n // ?code= on this page look like ours.\n writeRecord(PENDING_KEY, undefined)\n setTools(\n watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = providerRef.current?.authorizationUrl\n if (url) setAuthorizationUrl(String(url))\n setStatus('needs-authorization')\n }),\n )\n setCatalog(connection.catalog)\n setStatus('connected')\n } catch (err) {\n if (!current()) return\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n }\n },\n [closeConnection],\n )\n\n const disconnect = useCallback(async () => {\n epochRef.current++\n await closeConnection()\n setTools(undefined)\n setCatalog([])\n setAuthorizationUrl(undefined)\n setError(undefined)\n setStatus('idle')\n }, [closeConnection])\n\n const authorize = useCallback(() => {\n if (authorizationUrl && typeof globalThis.location !== 'undefined') {\n globalThis.location.href = authorizationUrl\n }\n }, [authorizationUrl])\n\n const forgetAuthorization = useCallback(async () => {\n const record = readRecord<OAuthRecord>(OAUTH_KEY)\n writeRecord(PENDING_KEY, undefined)\n writeRecord(OAUTH_KEY, undefined)\n // After a reload there is no live provider, but the tokens are still in the\n // vault — rebuild one for the same server so \"forget\" actually forgets\n // rather than only resetting the UI.\n let provider = providerRef.current\n if (!provider && record) {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n provider = new mod.BrowserOAuthProvider({\n serverUrl: record.url,\n redirectUrl: record.redirectUrl,\n clientName: record.clientName,\n scope: record.scope,\n })\n }\n }\n await provider?.reset().catch(() => {})\n providerRef.current = undefined\n await disconnect()\n }, [disconnect])\n\n // Resume an OAuth round-trip: the authorization server has just sent the user\n // back with ?code=… and this component is mounting for the first time.\n useEffect(() => {\n // Everything up to the first await runs synchronously, on purpose: React\n // flushes the remaining passive effects (which may rewrite location) before\n // an awaited continuation resumes, and StrictMode runs this effect twice.\n const callback = readCallbackParams()\n if (!callback) {\n setCompletingAuthorization(false)\n return\n }\n const pending = readRecord<OAuthRecord>(PENDING_KEY)\n // A record only proves that WE started a flow, not that THIS callback is\n // its answer — so an expired one is treated as somebody else's. Either way\n // the URL is left exactly as we found it: another sign-in flow on this page\n // may still need those parameters.\n const fresh =\n pending !== undefined &&\n (pending.startedAt === undefined || Date.now() - pending.startedAt < PENDING_TTL_MS)\n if (!pending || !fresh) {\n if (pending) writeRecord(PENDING_KEY, undefined)\n setCompletingAuthorization(false)\n return\n }\n if (!claimOAuthCallback(callback)) {\n setCompletingAuthorization(false)\n return\n }\n // Ours, and claimed: the code is in hand, so clear it from the address bar\n // now rather than after the reconnect.\n if (typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n\n void (async () => {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const provider = new mod.BrowserOAuthProvider({\n serverUrl: pending.url,\n redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),\n clientName: pending.clientName,\n scope: pending.scope,\n })\n providerRef.current = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(PENDING_KEY, undefined)\n // NOT gated on `cancelled`. StrictMode's simulated cleanup sets it in\n // development, and the second setup cannot take over — the code has\n // already been claimed and stripped from the URL — so bailing here\n // would finish the authorization and then never connect. `connect` is\n // epoch-guarded and a setState after a real unmount is a no-op, so\n // letting it run is safe either way.\n //\n // Hand back to `connect`, which owns the status from here — a slow or\n // hung handshake must not leave the UI stuck on \"finishing\".\n setCompletingAuthorization(false)\n await connect({ url: pending.url, name: pending.name, oauth: true })\n } catch (err) {\n writeRecord(PENDING_KEY, undefined)\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n } finally {\n setCompletingAuthorization(false)\n }\n })()\n // Runs once: `connect` is stable and the callback exists only on first load.\n }, [connect])\n\n useEffect(\n () => () => {\n epochRef.current++\n void closeConnection()\n },\n [closeConnection],\n )\n\n return {\n status,\n tools,\n catalog,\n error,\n authorizationUrl,\n oauthSupported,\n completingAuthorization,\n connect,\n disconnect,\n authorize,\n forgetAuthorization,\n checkOAuthSupport,\n }\n}\n","import { useCallback, useRef, useState } from 'react'\nimport {\n createWebLLMModel,\n isWebGPUAvailable,\n preloadWebLLMModel,\n type WebLLMModelOptions,\n} from '@dudko.dev/agent-web'\nimport { errMessage } from '../util.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\nexport interface UseWebLLMModelReturn {\n /** The built model once loaded — pass to `createAgent({ model })`. */\n model: WebLLMModel | undefined\n /** Start the download / engine init. Idempotent-ish: safe to call again to retry. */\n load: () => Promise<WebLLMModel | undefined>\n /** True while weights are downloading / the engine is initializing. */\n loading: boolean\n /** Load progress, 0..1. */\n progress: number\n /** Human-readable progress text from WebLLM. */\n text: string\n /** Error message if the load failed. */\n error: string | undefined\n /** Whether WebGPU is available (required for local models). */\n supported: boolean\n /** True once the model is ready. */\n ready: boolean\n}\n\n/**\n * Load a local WebGPU model with WebLLM and track its download progress.\n * Nothing downloads until you call `load()` (models are large), so you can\n * gate it behind a user action. `load()` eagerly initializes the engine (via\n * the core's `preloadWebLLMModel`), so `ready` means \"ready to chat\" and\n * progress fills during the load rather than silently on the first message.\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 const [model, setModel] = useState<WebLLMModel | undefined>(undefined)\n const [loading, setLoading] = useState(false)\n const [progress, setProgress] = useState(0)\n const [text, setText] = useState('')\n const [error, setError] = useState<string | undefined>(undefined)\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const load = useCallback(async (): Promise<WebLLMModel | undefined> => {\n if (!isWebGPUAvailable()) {\n setError('WebGPU is not available in this browser.')\n return undefined\n }\n setLoading(true)\n setError(undefined)\n setProgress(0)\n setText('')\n try {\n const { create = createWebLLMModel, ...modelOptions } = optionsRef.current ?? {}\n const built = await create(modelId, {\n ...modelOptions,\n // Drive preload here (below) so download progress is reported the same\n // way whether `create` is the core's `createWebLLMModel` or an injected\n // factory (e.g. a statically-imported `webLLM`, needed under bundlers).\n preload: false,\n initProgressCallback: (report) => {\n setProgress(report.progress)\n setText(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 await preloadWebLLMModel(built)\n setModel(built)\n return built\n } catch (err) {\n setError(errMessage(err))\n return undefined\n } finally {\n setLoading(false)\n }\n }, [modelId])\n\n return {\n model,\n load,\n loading,\n progress,\n text,\n error,\n supported: isWebGPUAvailable(),\n ready: model !== undefined,\n }\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 } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { useOptionalAgentContext } from '../context.js'\nimport type { UseAgentReturn } from '../hooks/use-agent.js'\nimport { AlertIcon } from './icons.js'\nimport { Composer } from './Composer.js'\nimport { MessageList } from './MessageList.js'\nimport { ModelLoadBar } from './ModelLoadBar.js'\nimport { StepList } from './StepList.js'\nimport { UsageBadge } from './UsageBadge.js'\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 placeholder?: string\n /** Render the internal plan/step activity while the agent works (default true). */\n showActivity?: boolean\n /** Render the token-usage badge in the footer (default true). */\n showUsage?: boolean\n /** Content shown before the first message. */\n emptyState?: ReactNode\n className?: string\n /** Inline styles on the root — handy for sizing (e.g. `{ height: 520 }`). */\n style?: CSSProperties\n}\n\nconst statusLabel = (status: UseAgentReturn['status']): string => {\n switch (status) {\n case 'initializing':\n return 'Loading model…'\n case 'running':\n return 'Working…'\n case 'error':\n return 'Failed to start'\n default:\n return 'Ready'\n }\n}\n\n/**\n * A drop-in chat panel: transcript, live plan/step activity with tool calls, a\n * streamed final answer, model-load progress, token usage, and a composer with\n * a stop button. Give it a `controller` from {@link useAgent}, or wrap it in an\n * {@link AgentProvider} and it will find one.\n *\n * ```tsx\n * <AgentProvider config={{ model, tools, credentials }}>\n * <AgentChat title=\"Assistant\" />\n * </AgentProvider>\n * ```\n */\nexport const AgentChat = ({\n controller,\n title,\n placeholder,\n showActivity = true,\n showUsage = true,\n emptyState = 'Ask the agent to do something.',\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\n const bodyRef = useRef<HTMLDivElement>(null)\n useEffect(() => {\n const el = bodyRef.current\n if (el) el.scrollTop = el.scrollHeight\n }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad])\n\n const showReplan = agent.replan && agent.replan.mode !== 'continue'\n const loading = agent.modelLoad && agent.modelLoad.progress < 1 && agent.isRunning === false\n\n return (\n <div className={['awr-chat', className].filter(Boolean).join(' ')} style={style}>\n {title && <div className=\"awr-chat__title\">{title}</div>}\n\n <div className=\"awr-chat__body\" ref={bodyRef}>\n <MessageList messages={agent.messages} empty={emptyState} />\n\n {showActivity && (agent.steps.length > 0 || agent.planThought) && (\n <div className=\"awr-activity\">\n {agent.planThought.trim() && (\n <details className=\"awr-activity__plan\">\n <summary>Plan</summary>\n <p className=\"awr-activity__thought\">{agent.planThought}</p>\n </details>\n )}\n <StepList steps={agent.steps} />\n {showReplan && (\n <div className=\"awr-activity__replan\">\n Replanned ({agent.replan!.mode}): {agent.replan!.reason}\n </div>\n )}\n </div>\n )}\n\n {agent.modelLoad && (loading || agent.isRunning) && agent.modelLoad.progress < 1 && (\n <ModelLoadBar load={agent.modelLoad} />\n )}\n </div>\n\n {agent.error && agent.status === 'error' && (\n <div className=\"awr-chat__error\">\n <AlertIcon size={14} /> {agent.error}\n </div>\n )}\n\n <div className=\"awr-chat__footer\">\n <div className=\"awr-chat__meta\">\n <span className={`awr-status awr-status--${agent.status}`}>\n <span className=\"awr-status__dot\" />\n {statusLabel(agent.status)}\n </span>\n {showUsage && <UsageBadge usage={agent.usage} />}\n </div>\n <Composer\n onSubmit={(text) => void agent.run(text)}\n busy={agent.isRunning}\n onStop={agent.stop}\n disabled={!agent.isReady && !agent.isRunning}\n placeholder={placeholder}\n />\n </div>\n </div>\n )\n}\n","// Tiny inline SVG icons — no icon-font or image dependency. Each inherits the\n// current text color (`stroke=\"currentColor\"`) and takes an optional size.\n\nexport interface IconProps {\n size?: number\n className?: string\n}\n\nconst base = (size = 16) => ({\n width: size,\n height: size,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round' as const,\n strokeLinejoin: 'round' as const,\n 'aria-hidden': true,\n})\n\nexport const SendIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M22 2 11 13\" />\n <path d=\"M22 2 15 22l-4-9-9-4Z\" />\n </svg>\n)\n\nexport const StopIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n </svg>\n)\n\nexport const SpinnerIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={['awr-spin', className].filter(Boolean).join(' ')}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </svg>\n)\n\nexport const CheckIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n)\n\nexport const AlertIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </svg>\n)\n\nexport const ToolIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z\" />\n </svg>\n)\n\nexport const ChevronIcon = ({ size, className }: IconProps) => (\n <svg {...base(size)} className={className}>\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n)\n","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 { ReactNode } from 'react'\nimport type { ChatMessage } from '../types.js'\nimport { SpinnerIcon } from './icons.js'\n\nexport interface MessageListProps {\n messages: ChatMessage[]\n /** Rendered when there are no messages yet. */\n empty?: ReactNode\n className?: string\n}\n\n/** The chat transcript: user and assistant turns, with a streaming indicator. */\nexport const MessageList = ({ messages, empty, className }: MessageListProps) => {\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 <div key={m.id} className={`awr-msg awr-msg--${m.role}`}>\n <div className=\"awr-msg__bubble\">\n {m.content}\n {m.pending && !m.content && <SpinnerIcon size={14} className=\"awr-msg__pending\" />}\n </div>\n </div>\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","/** 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","import type { StepView, ToolCallView } from '../types.js'\nimport { previewValue } from './format.js'\nimport { AlertIcon, CheckIcon, SpinnerIcon, ToolIcon } from './icons.js'\n\nconst ToolCallRow = ({ call }: { call: ToolCallView }) => {\n const state = call.status === 'calling' ? 'calling' : call.ok === false ? 'failed' : 'ok'\n return (\n <li className={`awr-tool awr-tool--${state}`}>\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\">failed</span>\n )}\n </li>\n )\n}\n\nconst StepItem = ({ step }: { step: StepView }) => (\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 {step.text.trim() && <p className=\"awr-step__text\">{step.text.trim()}</p>}\n {step.toolCalls.length > 0 && (\n <ul className=\"awr-step__tools\">\n {step.toolCalls.map((call, i) => (\n <ToolCallRow key={i} call={call} />\n ))}\n </ul>\n )}\n {step.blocked && step.summary && <p className=\"awr-step__blocked\">{step.summary}</p>}\n </li>\n)\n\nexport interface StepListProps {\n steps: StepView[]\n className?: string\n}\n\n/** The live execution: each step, its streamed text, and its tool calls. */\nexport const StepList = ({ steps, className }: StepListProps) => {\n if (steps.length === 0) return null\n return (\n <ol className={['awr-steps', className].filter(Boolean).join(' ')}>\n {steps.map((step) => (\n <StepItem key={step.id} step={step} />\n ))}\n </ol>\n )\n}\n","import type { IUsage } from '@dudko.dev/agent-web'\n\nexport interface UsageBadgeProps {\n usage: IUsage\n className?: string\n}\n\nconst fmt = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n)\n\n/** A compact token-usage readout (in → out, and total on hover). */\nexport const UsageBadge = ({ usage, className }: UsageBadgeProps) => {\n if (usage.totalTokens === 0) return null\n return (\n <span\n className={['awr-usage', className].filter(Boolean).join(' ')}\n title={`${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`}\n >\n {fmt(usage.inputTokens)}↑ {fmt(usage.outputTokens)}↓\n </span>\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 { useEffect, useState } from 'react'\nimport type { UseCredentialsReturn } from '../hooks/use-credentials.js'\nimport { CheckIcon } from './icons.js'\n\nexport interface ApiKeyFormProps {\n /** The value returned by {@link useCredentials}. */\n credentials: UseCredentialsReturn\n /** The ref id under which the key is stored (matches your `credentialRef`). */\n credentialRef: string\n label?: string\n placeholder?: string\n /** Called after a key is saved or removed (e.g. to `reload()` the agent). */\n onChange?: (present: boolean) => void\n className?: string\n}\n\n/**\n * A BYOK key input that stores the key **encrypted at rest** via\n * {@link useCredentials}. Shows a \"saved\" state when a key already exists and\n * lets the user replace or remove it. The plaintext key never leaves the form.\n */\nexport const ApiKeyForm = ({\n credentials,\n credentialRef,\n label = 'API key',\n placeholder = 'sk-…',\n onChange,\n className,\n}: ApiKeyFormProps) => {\n const [value, setValue] = useState('')\n const [present, setPresent] = useState(false)\n const [busy, setBusy] = useState(false)\n\n useEffect(() => {\n let active = true\n credentials.hasKey(credentialRef).then((has) => {\n if (active) setPresent(has)\n })\n return () => {\n active = false\n }\n }, [credentials, credentialRef, credentials.version])\n\n const save = async () => {\n const key = value.trim()\n if (!key) return\n setBusy(true)\n try {\n await credentials.setKey(credentialRef, key)\n setValue('')\n setPresent(true)\n onChange?.(true)\n } finally {\n setBusy(false)\n }\n }\n\n const remove = async () => {\n setBusy(true)\n try {\n await credentials.removeKey(credentialRef)\n setPresent(false)\n onChange?.(false)\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <div className={['awr-keyform', className].filter(Boolean).join(' ')}>\n <label className=\"awr-keyform__label\">\n {label}\n {present && (\n <span className=\"awr-keyform__saved\">\n <CheckIcon size={12} /> stored, encrypted\n </span>\n )}\n </label>\n <div className=\"awr-keyform__row\">\n <input\n className=\"awr-keyform__input\"\n type=\"password\"\n autoComplete=\"off\"\n value={value}\n placeholder={present ? '•••••••• (replace)' : placeholder}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n void save()\n }\n }}\n disabled={busy}\n />\n <button\n type=\"button\"\n className=\"awr-keyform__btn\"\n onClick={() => void save()}\n disabled={busy || !value.trim()}\n >\n Save\n </button>\n {present && (\n <button\n type=\"button\"\n className=\"awr-keyform__btn awr-keyform__btn--ghost\"\n onClick={() => void remove()}\n disabled={busy}\n >\n Remove\n </button>\n )}\n </div>\n </div>\n )\n}\n","// ── Hooks ────────────────────────────────────────────────────────────────────\nexport { useAgent } from './hooks/use-agent.js'\nexport type { UseAgentOptions, UseAgentReturn } from './hooks/use-agent.js'\nexport { useCredentials } from './hooks/use-credentials.js'\nexport type { UseCredentialsReturn } from './hooks/use-credentials.js'\nexport {\n useMcp,\n claimOAuthCallback,\n describeMcpResult,\n isUnauthorizedError,\n readCallbackParams,\n stripOAuthParams,\n} from './hooks/use-mcp.js'\nexport type { McpConnectOptions, McpStatus, UseMcpOptions, UseMcpReturn } from './hooks/use-mcp.js'\nexport type {\n ConnectedMcp,\n McpCatalogEntry,\n McpOAuthCallback,\n McpServerResult,\n McpModule,\n} from './mcp-types.js'\nexport { useWebLLMModel } from './hooks/use-webllm-model.js'\nexport type {\n UseWebLLMModelReturn,\n UseWebLLMModelOptions,\n WebLLMModelFactory,\n} from './hooks/use-webllm-model.js'\n\n// ── Context ──────────────────────────────────────────────────────────────────\nexport { AgentProvider, useAgentContext, useOptionalAgentContext } from './context.js'\nexport type { AgentProviderProps } from './context.js'\n\n// ── Headless state (the pure event → UI reducer, for custom UIs) ─────────────\nexport { agentStateReducer, createInitialAgentState } from './state.js'\nexport type { AgentAction } from './state.js'\nexport type {\n AgentUiState,\n AgentStatus,\n ChatMessage,\n StepView,\n ToolCallView,\n ModelLoadState,\n ReplanState,\n} from './types.js'\n\n// ── Components (optional, pre-styled — import '@dudko.dev/agent-web-react/styles.css') ─\nexport { AgentChat } from './components/AgentChat.js'\nexport type { AgentChatProps } from './components/AgentChat.js'\nexport { MessageList } from './components/MessageList.js'\nexport type { MessageListProps } from './components/MessageList.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 } from './components/StepList.js'\nexport type { StepListProps } from './components/StepList.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 createWebLLMModel,\n preloadWebLLMModel,\n unloadWebLLMModel,\n isWebGPUAvailable,\n VaultCredentialStore,\n MemoryCredentialStore,\n} from '@dudko.dev/agent-web'\nexport type {\n Agent,\n RunOptions,\n RunResult,\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} from '@dudko.dev/agent-web'\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,YAAY,QAAQ,gBAAgB;AAErE;AAAA,EACE;AAAA,OAKK;;;ACSP,IAAM,aAAa,OAAe,EAAE,aAAa,GAAG,cAAc,GAAG,aAAa,EAAE;AAEpF,IAAM,WAAW,CAAC,GAAW,OAAuB;AAAA,EAClD,aAAa,EAAE,cAAc,EAAE;AAAA,EAC/B,cAAc,EAAE,eAAe,EAAE;AAAA,EACjC,aAAa,EAAE,cAAc,EAAE;AACjC;AAGO,IAAM,0BAA0B,OAAqB;AAAA,EAC1D,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO,CAAC;AAAA,EACR,WAAW;AAAA,EACX,OAAO,WAAW;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR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AClDA;AAAA,EACE,eAAAI;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,OACK;","names":["base","useCallback","useState","useCallback","useEffect","useRef","useState","useCallback","useRef","useState","useState","useRef","useCallback","useEffect","useRef","jsx","useState","jsx","jsxs","useState","jsx","jsxs","jsx","jsxs","jsx","jsxs","jsxs","jsx","jsxs","useRef","useEffect","jsx","jsxs","useEffect","useState","jsx","jsxs","useState","useEffect","createAgent","createWebLLMModel","preloadWebLLMModel","isWebGPUAvailable","VaultCredentialStore"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent-web-react",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "React bindings for @dudko.dev/agent-web: a headless useAgent hook, an AgentProvider context, and optional pre-styled components (chat panel, plan/step view, BYOK key form, WebLLM load bar) that connect the in-browser LLM agent to any React site. UI you can drop in — or a headless reducer you can build your own around.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -38,7 +38,8 @@
38
38
  "format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"tests/**/*.ts\"",
39
39
  "test": "node --test --experimental-strip-types --disable-warning=ExperimentalWarning tests/*.test.ts",
40
40
  "prepublishOnly": "npm run typecheck && npm test && npm run build",
41
- "pretest": "npm run build"
41
+ "pretest": "npm run build",
42
+ "test:e2e": "playwright test"
42
43
  },
43
44
  "keywords": [
44
45
  "agent",
@@ -104,12 +105,14 @@
104
105
  "node": ">=18"
105
106
  },
106
107
  "peerDependencies": {
107
- "@dudko.dev/agent-web": ">=0.0.6",
108
+ "@dudko.dev/agent-web": ">=0.0.12",
108
109
  "react": ">=18",
109
110
  "react-dom": ">=18"
110
111
  },
111
112
  "devDependencies": {
112
- "@dudko.dev/agent-web": "^0.0.7",
113
+ "@dudko.dev/agent-web": "^0.0.12",
114
+ "@modelcontextprotocol/sdk": "^1.30.0",
115
+ "@playwright/test": "^1.62.1",
113
116
  "@types/node": "^22.9.0",
114
117
  "@types/react": "^19.2.18",
115
118
  "@types/react-dom": "^19.2.4",