@dudko.dev/agent-web-react 0.0.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../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"],"sourcesContent":["// ── 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 { UseWebLLMModelReturn } 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 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 IPlan,\n IPlanStep,\n IStepResult,\n IToolCall,\n IUsage,\n} from '@dudko.dev/agent-web'\n","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 { createWebLLMModel, isWebGPUAvailable, type WebLLMModelOptions } 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\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.\n *\n * ```tsx\n * const local = useWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC')\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?: WebLLMModelOptions,\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 try {\n const built = await createWebLLMModel(modelId, {\n ...optionsRef.current,\n initProgressCallback: (report) => {\n setProgress(report.progress)\n setText(report.text)\n optionsRef.current?.initProgressCallback?.(report)\n },\n })\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqE;AAErE,uBAMO;;;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,SAA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AS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,OAAO;AAAA,UAC3B,UAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OAEJ;AAAA,KACF;AAEJ;;;AhBtEA,IAAAC,oBAOO;","names":["base","import_react","import_agent_web","import_react","import_agent_web","import_react","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_react","import_jsx_runtime","import_agent_web"]}
@@ -0,0 +1,354 @@
1
+ import * as react from 'react';
2
+ import { DependencyList, ReactNode, CSSProperties } from 'react';
3
+ import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunResult, Agent, AgentEventHandler, BrowserAgentConfig, CredentialStore, createWebLLMModel, WebLLMModelOptions } from '@dudko.dev/agent-web';
4
+ export { Agent, AgentEvent, AgentEventHandler, AgentTool, AgentToolSet, BrowserAgentConfig, CredentialStore, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, MemoryCredentialStore, ModelInput, ProviderModelSpec, ProviderType, RunOptions, RunResult, VaultCredentialStore, createAgent, createWebLLMModel, defineTool, isWebGPUAvailable } from '@dudko.dev/agent-web';
5
+
6
+ /**
7
+ * Lifecycle of the agent instance the hook owns.
8
+ * - `idle` — no config yet, nothing built.
9
+ * - `initializing` — building the agent (dynamic provider imports, vault key
10
+ * fetch, and — for WebLLM — weight download).
11
+ * - `ready` — the agent is built and can run.
12
+ * - `running` — a run is in flight.
13
+ * - `error` — the agent failed to build (a run error keeps it `ready`).
14
+ */
15
+ type AgentStatus = 'idle' | 'initializing' | 'ready' | 'running' | 'error';
16
+ /** One turn of the chat transcript that a chat UI renders. */
17
+ interface ChatMessage {
18
+ id: string;
19
+ role: 'user' | 'assistant';
20
+ content: string;
21
+ /** An assistant message that is still streaming (no final/stopped/error yet). */
22
+ pending: boolean;
23
+ }
24
+ /** A single tool call as it appears in a step, streamed then finalized. */
25
+ interface ToolCallView {
26
+ name: string;
27
+ input: unknown;
28
+ output?: unknown;
29
+ ok?: boolean;
30
+ status: 'calling' | 'done';
31
+ }
32
+ /** An execution step with its accumulated text and tool calls. */
33
+ interface StepView {
34
+ id: string;
35
+ index: number;
36
+ total: number;
37
+ step: IPlanStep;
38
+ /** Streamed executor text for this step (step.text-delta). */
39
+ text: string;
40
+ toolCalls: ToolCallView[];
41
+ status: 'running' | 'done';
42
+ summary?: string;
43
+ blocked: boolean;
44
+ }
45
+ /** WebLLM weight-download / engine-init progress (model.load events). */
46
+ interface ModelLoadState {
47
+ progress: number;
48
+ text: string;
49
+ }
50
+ interface ReplanState {
51
+ mode: ReplanMode;
52
+ reason: string;
53
+ }
54
+ /**
55
+ * The whole UI-facing view of an agent run, rebuilt purely from the stream of
56
+ * `AgentEvent`s by {@link agentStateReducer}. `status` is owned by the hook
57
+ * (build/run lifecycle) and layered on top; everything else here is derived
58
+ * only from events, so the reducer is deterministic and testable without React.
59
+ */
60
+ interface AgentUiState {
61
+ status: AgentStatus;
62
+ /** The goal of the current / most recent run. */
63
+ goal?: string;
64
+ /** The last plan the agent produced (created or revised). */
65
+ plan?: IPlan;
66
+ /** Streamed planner "thinking" text (plan.thought-delta). */
67
+ planThought: string;
68
+ /** Execution steps, in order, with their tool calls. */
69
+ steps: StepView[];
70
+ /** The final answer (streamed via final.text-delta, finalized on final). */
71
+ finalText: string;
72
+ /** Running token total across the current run. */
73
+ usage: IUsage;
74
+ /** WebLLM progress, present only while a local model is loading. */
75
+ modelLoad?: ModelLoadState;
76
+ /** The most recent replan decision, if any. */
77
+ replan?: ReplanState;
78
+ /** Error message from the last run error / build failure. */
79
+ error?: string;
80
+ /** True when the last run was aborted via stop(). */
81
+ stopped: boolean;
82
+ /** A chat-style transcript built from every run, for chat UIs. */
83
+ messages: ChatMessage[];
84
+ /** The raw event log (most recent last), capped by `maxEvents`. */
85
+ events: AgentEvent[];
86
+ /** Monotonic counter; mints stable message ids without Date/Math.random. */
87
+ seq: number;
88
+ }
89
+
90
+ interface UseAgentOptions {
91
+ /**
92
+ * Rebuild the agent when any of these values change — compared like a
93
+ * `useEffect` dependency array (so it must keep a stable length across
94
+ * renders). Default: build once on mount. Bump this when you switch
95
+ * model/provider so a fresh agent is constructed with the new config.
96
+ *
97
+ * Keep dynamic config (`tools`, `describeState`) referentially stable across
98
+ * renders (e.g. via `useRef`/`useCallback`) so it survives without a rebuild.
99
+ */
100
+ deps?: DependencyList;
101
+ /** Invoked for every raw agent event, after the internal reducer folds it. */
102
+ onEvent?: AgentEventHandler;
103
+ /** Build the agent immediately on mount (default `true`). */
104
+ autoStart?: boolean;
105
+ /** Cap the retained raw event log length (default 200; 0 = unbounded). */
106
+ maxEvents?: number;
107
+ }
108
+ interface UseAgentReturn extends AgentUiState {
109
+ /** Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. */
110
+ run: (goal: string) => Promise<RunResult | undefined>;
111
+ /** Abort the in-flight run (observed between phases and mid-stream). */
112
+ stop: () => void;
113
+ /** Clear the whole conversation — transcript and current run. */
114
+ reset: () => void;
115
+ /** Rebuild the agent now (e.g. after the user stores a new API key). */
116
+ reload: () => void;
117
+ /** The built agent, once ready. */
118
+ agent: Agent | undefined;
119
+ isRunning: boolean;
120
+ isReady: boolean;
121
+ }
122
+ /**
123
+ * The primary React binding for `@dudko.dev/agent-web`. Builds the agent from a
124
+ * {@link BrowserAgentConfig}, streams its typed events into a renderable
125
+ * {@link AgentUiState} (plan, steps, tool calls, streamed final answer, token
126
+ * usage, model-load progress and a chat transcript), and exposes `run` / `stop`
127
+ * / `reset` / `reload`.
128
+ *
129
+ * ```tsx
130
+ * const agent = useAgent({
131
+ * model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },
132
+ * credentials,
133
+ * tools,
134
+ * })
135
+ * // <button disabled={!agent.isReady} onClick={() => agent.run(text)}>Run</button>
136
+ * ```
137
+ */
138
+ declare const useAgent: (config: BrowserAgentConfig, options?: UseAgentOptions) => UseAgentReturn;
139
+
140
+ interface UseCredentialsReturn {
141
+ /** The underlying store — pass this straight to `createAgent({ credentials })`. */
142
+ store: CredentialStore;
143
+ /** Store (encrypted at rest) an API key under a ref id. */
144
+ setKey: (ref: string, key: string) => Promise<void>;
145
+ /** Remove a stored key. */
146
+ removeKey: (ref: string) => Promise<void>;
147
+ /** Resolve whether a key is currently present for a ref. */
148
+ hasKey: (ref: string) => Promise<boolean>;
149
+ /**
150
+ * Bumped whenever a key is written or removed — depend on it in an effect to
151
+ * re-query `hasKey` and reflect the change in your UI.
152
+ */
153
+ version: number;
154
+ }
155
+ /**
156
+ * Manage BYOK API keys in the agent's encrypted vault (WebCrypto AES-GCM key in
157
+ * IndexedDB). Defaults to a fresh {@link VaultCredentialStore}; pass your own
158
+ * {@link CredentialStore} (e.g. a short-lived-token fetcher) to override.
159
+ *
160
+ * ```tsx
161
+ * const creds = useCredentials()
162
+ * // await creds.setKey('openai', userInput)
163
+ * // <AgentProvider config={{ model, credentials: creds.store }}>…
164
+ * ```
165
+ */
166
+ declare const useCredentials: (store?: CredentialStore) => UseCredentialsReturn;
167
+
168
+ /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
169
+ type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
170
+ interface UseWebLLMModelReturn {
171
+ /** The built model once loaded — pass to `createAgent({ model })`. */
172
+ model: WebLLMModel | undefined;
173
+ /** Start the download / engine init. Idempotent-ish: safe to call again to retry. */
174
+ load: () => Promise<WebLLMModel | undefined>;
175
+ /** True while weights are downloading / the engine is initializing. */
176
+ loading: boolean;
177
+ /** Load progress, 0..1. */
178
+ progress: number;
179
+ /** Human-readable progress text from WebLLM. */
180
+ text: string;
181
+ /** Error message if the load failed. */
182
+ error: string | undefined;
183
+ /** Whether WebGPU is available (required for local models). */
184
+ supported: boolean;
185
+ /** True once the model is ready. */
186
+ ready: boolean;
187
+ }
188
+ /**
189
+ * Load a local WebGPU model with WebLLM and track its download progress.
190
+ * Nothing downloads until you call `load()` (models are large), so you can
191
+ * gate it behind a user action.
192
+ *
193
+ * ```tsx
194
+ * const local = useWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC')
195
+ * // <button disabled={!local.supported || local.loading} onClick={local.load}>Load</button>
196
+ * // {local.loading && <ModelLoadBar load={{ progress: local.progress, text: local.text }} />}
197
+ * // local.ready && <AgentProvider config={{ model: local.model! }}>…
198
+ * ```
199
+ */
200
+ declare const useWebLLMModel: (modelId: string, options?: WebLLMModelOptions) => UseWebLLMModelReturn;
201
+
202
+ interface AgentProviderProps extends UseAgentOptions {
203
+ /** The agent configuration (see `@dudko.dev/agent-web`). */
204
+ config: BrowserAgentConfig;
205
+ children: ReactNode;
206
+ }
207
+ /**
208
+ * Build one agent with {@link useAgent} and share it with the subtree, so a
209
+ * chat panel, a plan view and a usage badge can all read the same live run.
210
+ *
211
+ * ```tsx
212
+ * <AgentProvider config={{ model, tools, credentials }}>
213
+ * <AgentChat />
214
+ * </AgentProvider>
215
+ * ```
216
+ */
217
+ declare const AgentProvider: ({ config, children, ...options }: AgentProviderProps) => react.JSX.Element;
218
+ /** Read the shared agent. Throws if used outside an {@link AgentProvider}. */
219
+ declare const useAgentContext: () => UseAgentReturn;
220
+ /** Non-throwing variant: returns `null` when outside a provider. */
221
+ declare const useOptionalAgentContext: () => UseAgentReturn | null;
222
+
223
+ /**
224
+ * The reducer that turns the agent's `AgentEvent` stream into a renderable
225
+ * {@link AgentUiState}. It is a pure function of (state, action) with no React,
226
+ * no clock and no randomness (ids come from a monotonic `seq`), so it can be
227
+ * unit-tested in isolation and reused to build a fully custom UI.
228
+ */
229
+ type AgentAction =
230
+ /** Clear the whole conversation (transcript + current run), keeping status. */
231
+ {
232
+ type: 'reset';
233
+ }
234
+ /** Set the lifecycle status (owned by the hook). */
235
+ | {
236
+ type: 'status';
237
+ status: AgentUiState['status'];
238
+ error?: string;
239
+ }
240
+ /** Fold one streamed agent event into the view. */
241
+ | {
242
+ type: 'event';
243
+ event: AgentEvent;
244
+ maxEvents?: number;
245
+ };
246
+ /** A fresh, empty view. */
247
+ declare const createInitialAgentState: () => AgentUiState;
248
+ declare const agentStateReducer: (state: AgentUiState, action: AgentAction) => AgentUiState;
249
+
250
+ interface AgentChatProps {
251
+ /**
252
+ * An explicit controller from {@link useAgent}. If omitted, the component
253
+ * reads the shared controller from an enclosing `<AgentProvider>`.
254
+ */
255
+ controller?: UseAgentReturn;
256
+ title?: ReactNode;
257
+ placeholder?: string;
258
+ /** Render the internal plan/step activity while the agent works (default true). */
259
+ showActivity?: boolean;
260
+ /** Render the token-usage badge in the footer (default true). */
261
+ showUsage?: boolean;
262
+ /** Content shown before the first message. */
263
+ emptyState?: ReactNode;
264
+ className?: string;
265
+ /** Inline styles on the root — handy for sizing (e.g. `{ height: 520 }`). */
266
+ style?: CSSProperties;
267
+ }
268
+ /**
269
+ * A drop-in chat panel: transcript, live plan/step activity with tool calls, a
270
+ * streamed final answer, model-load progress, token usage, and a composer with
271
+ * a stop button. Give it a `controller` from {@link useAgent}, or wrap it in an
272
+ * {@link AgentProvider} and it will find one.
273
+ *
274
+ * ```tsx
275
+ * <AgentProvider config={{ model, tools, credentials }}>
276
+ * <AgentChat title="Assistant" />
277
+ * </AgentProvider>
278
+ * ```
279
+ */
280
+ declare const AgentChat: ({ controller, title, placeholder, showActivity, showUsage, emptyState, className, style, }: AgentChatProps) => react.JSX.Element;
281
+
282
+ interface MessageListProps {
283
+ messages: ChatMessage[];
284
+ /** Rendered when there are no messages yet. */
285
+ empty?: ReactNode;
286
+ className?: string;
287
+ }
288
+ /** The chat transcript: user and assistant turns, with a streaming indicator. */
289
+ declare const MessageList: ({ messages, empty, className }: MessageListProps) => react.JSX.Element | null;
290
+
291
+ interface ComposerProps {
292
+ /** Called with the trimmed text when the user submits. */
293
+ onSubmit: (text: string) => void;
294
+ /** A run is in flight — show a stop button instead of send. */
295
+ busy?: boolean;
296
+ /** Called when the stop button is pressed (only shown while `busy`). */
297
+ onStop?: () => void;
298
+ /** Disable input (e.g. while the agent is still initializing). */
299
+ disabled?: boolean;
300
+ placeholder?: string;
301
+ className?: string;
302
+ }
303
+ /** A textarea + send/stop button. Enter submits; Shift+Enter inserts a newline. */
304
+ declare const Composer: ({ onSubmit, busy, onStop, disabled, placeholder, className, }: ComposerProps) => react.JSX.Element;
305
+
306
+ interface PlanViewProps {
307
+ plan: IPlan;
308
+ /** Also render the planner's reasoning ("thought"). Default true. */
309
+ showThought?: boolean;
310
+ className?: string;
311
+ }
312
+ /** The plan the agent produced: its reasoning and the ordered step list. */
313
+ declare const PlanView: ({ plan, showThought, className }: PlanViewProps) => react.JSX.Element | null;
314
+
315
+ interface StepListProps {
316
+ steps: StepView[];
317
+ className?: string;
318
+ }
319
+ /** The live execution: each step, its streamed text, and its tool calls. */
320
+ declare const StepList: ({ steps, className }: StepListProps) => react.JSX.Element | null;
321
+
322
+ interface ModelLoadBarProps {
323
+ load: ModelLoadState;
324
+ className?: string;
325
+ }
326
+ /** A progress bar for WebLLM weight download / engine init (0..1). */
327
+ declare const ModelLoadBar: ({ load, className }: ModelLoadBarProps) => react.JSX.Element;
328
+
329
+ interface UsageBadgeProps {
330
+ usage: IUsage;
331
+ className?: string;
332
+ }
333
+ /** A compact token-usage readout (in → out, and total on hover). */
334
+ declare const UsageBadge: ({ usage, className }: UsageBadgeProps) => react.JSX.Element | null;
335
+
336
+ interface ApiKeyFormProps {
337
+ /** The value returned by {@link useCredentials}. */
338
+ credentials: UseCredentialsReturn;
339
+ /** The ref id under which the key is stored (matches your `credentialRef`). */
340
+ credentialRef: string;
341
+ label?: string;
342
+ placeholder?: string;
343
+ /** Called after a key is saved or removed (e.g. to `reload()` the agent). */
344
+ onChange?: (present: boolean) => void;
345
+ className?: string;
346
+ }
347
+ /**
348
+ * A BYOK key input that stores the key **encrypted at rest** via
349
+ * {@link useCredentials}. Shows a "saved" state when a key already exists and
350
+ * lets the user replace or remove it. The plaintext key never leaves the form.
351
+ */
352
+ declare const ApiKeyForm: ({ credentials, credentialRef, label, placeholder, onChange, className, }: ApiKeyFormProps) => react.JSX.Element;
353
+
354
+ export { type AgentAction, AgentChat, type AgentChatProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, type ChatMessage, Composer, type ComposerProps, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, PlanView, type PlanViewProps, type ReplanState, StepList, type StepListProps, type StepView, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseCredentialsReturn, type UseWebLLMModelReturn, agentStateReducer, createInitialAgentState, useAgent, useAgentContext, useCredentials, useOptionalAgentContext, useWebLLMModel };