@dudko.dev/agent-web-react 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,7 +82,7 @@ export function Assistant() {
82
82
  return (
83
83
  <AgentProvider
84
84
  config={{
85
- model: { providerType: 'google', model: 'gemini-2.0-flash', credentialRef: 'google' },
85
+ model: { providerType: 'google', model: 'gemini-3.5-flash', credentialRef: 'google' },
86
86
  credentials: credentials.store,
87
87
  tools,
88
88
  describeState: () => serializeMyState(), // optional grounding
@@ -94,6 +94,14 @@ export function Assistant() {
94
94
  }
95
95
  ```
96
96
 
97
+ > **Using a bundler (Vite, Next, CRA)?** A provider **spec** like the one above
98
+ > asks the core to `import('@ai-sdk/google')` at runtime — but browser bundlers
99
+ > can't resolve that bare, `@vite-ignore`d import, so it fails with
100
+ > _“Provider package … is not installed”_ (and WebLLM fails with _“webLLM is not
101
+ > a function”_). Build the model yourself and pass it **directly** instead — see
102
+ > [Models in a bundler](#models-in-a-bundler-vite-next-cra). It's a few extra
103
+ > lines and works in every bundler.
104
+
97
105
  Store the user's key once (encrypted at rest), e.g. from a settings form:
98
106
 
99
107
  ```tsx
@@ -112,7 +120,9 @@ import { useAgent } from '@dudko.dev/agent-web-react'
112
120
 
113
121
  function Custom() {
114
122
  const agent = useAgent({
115
- model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },
123
+ // In a bundler, pass a model you built (see “Models in a bundler”); a
124
+ // provider spec like this one only resolves where dynamic imports do.
125
+ model: { providerType: 'openai', model: 'gpt-5.4-mini', credentialRef: 'openai' },
116
126
  credentials,
117
127
  tools,
118
128
  })
@@ -168,12 +178,16 @@ switch), `onEvent` (tap the raw event stream), `autoStart`, `maxEvents`.
168
178
 
169
179
  ```tsx
170
180
  import { useAgent, useWebLLMModel, ModelLoadBar } from '@dudko.dev/agent-web-react'
181
+ import { webLLM } from '@browser-ai/web-llm' // your app's optional peer
182
+
183
+ // Build WebLLM in your own code so the bundler includes it (see note below).
184
+ const createLocalModel = (id: string, opts?: object) => Promise.resolve(webLLM(id, opts as never))
171
185
 
172
186
  function LocalAgent() {
173
- const local = useWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC')
187
+ const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create: createLocalModel })
174
188
  const agent = useAgent(
175
189
  { model: local.model!, tools },
176
- { deps: [local.ready], autoStart: local.ready }, // build once the model is loaded
190
+ { deps: [local.model] }, // build once the model is loaded
177
191
  )
178
192
 
179
193
  if (!local.ready) {
@@ -189,6 +203,55 @@ function LocalAgent() {
189
203
  }
190
204
  ```
191
205
 
206
+ > `load()` eagerly downloads the weights (so the progress bar fills during load,
207
+ > not silently on the first message) and `ready` flips only once the model can
208
+ > actually answer. The `create` option is what makes it work under a bundler —
209
+ > see below.
210
+
211
+ ## Models in a bundler (Vite, Next, CRA)
212
+
213
+ The core builds cloud providers with `import('@ai-sdk/<provider>')` and WebLLM
214
+ with `import('@browser-ai/web-llm')`. Those are **bare, `@vite-ignore`d dynamic
215
+ imports** — great for Node/SSR/import-map setups, but a browser bundler either
216
+ leaves them unresolvable at runtime (cloud → _“Provider package … is not
217
+ installed”_) or stubs them to an empty module (WebLLM → _“webLLM is not a
218
+ function”_).
219
+
220
+ The fix is the same for both: **build the model in your own code** (a static
221
+ import your bundler can see) and hand the agent a direct `LanguageModel`.
222
+
223
+ **Cloud** — construct the provider from the vault-stored key:
224
+
225
+ ```tsx
226
+ import { useEffect, useState } from 'react'
227
+ import { createGoogleGenerativeAI } from '@ai-sdk/google'
228
+ import type { LanguageModel } from 'ai'
229
+ import { useAgent, useCredentials } from '@dudko.dev/agent-web-react'
230
+
231
+ function CloudAgent() {
232
+ const credentials = useCredentials()
233
+ const [model, setModel] = useState<LanguageModel>()
234
+
235
+ useEffect(() => {
236
+ credentials.store.getApiKey('google').then((key) => {
237
+ setModel(key ? createGoogleGenerativeAI({ apiKey: key })('gemini-3.5-flash') : undefined)
238
+ })
239
+ }, [credentials.store, credentials.version])
240
+
241
+ const agent = useAgent({ model: model!, credentials: credentials.store, tools }, { deps: [model] })
242
+ // …render <AgentChat controller={agent} /> once model is set
243
+ }
244
+ ```
245
+
246
+ > Anthropic needs `headers: { 'anthropic-dangerous-direct-browser-access': 'true' }`
247
+ > passed to `createAnthropic({ … })` for direct browser calls.
248
+
249
+ **Local** — pass a statically-imported `webLLM` factory via `useWebLLMModel`'s
250
+ `create` option (see the WebLLM example above).
251
+
252
+ The [`demo/`](demo/) app does exactly this — see
253
+ [`demo/src/providers.ts`](demo/src/providers.ts).
254
+
192
255
  ## Components
193
256
 
194
257
  All components are optional and styled by `styles.css` (class-prefixed `awr-`,
package/dist/index.cjs CHANGED
@@ -37,6 +37,8 @@ __export(src_exports, {
37
37
  createWebLLMModel: () => import_agent_web4.createWebLLMModel,
38
38
  defineTool: () => import_agent_web4.defineTool,
39
39
  isWebGPUAvailable: () => import_agent_web4.isWebGPUAvailable,
40
+ preloadWebLLMModel: () => import_agent_web4.preloadWebLLMModel,
41
+ unloadWebLLMModel: () => import_agent_web4.unloadWebLLMModel,
40
42
  useAgent: () => useAgent,
41
43
  useAgentContext: () => useAgentContext,
42
44
  useCredentials: () => useCredentials,
@@ -372,15 +374,23 @@ var useWebLLMModel = (modelId, options) => {
372
374
  }
373
375
  setLoading(true);
374
376
  setError(void 0);
377
+ setProgress(0);
378
+ setText("");
375
379
  try {
376
- const built = await (0, import_agent_web3.createWebLLMModel)(modelId, {
377
- ...optionsRef.current,
380
+ const { create = import_agent_web3.createWebLLMModel, ...modelOptions } = optionsRef.current ?? {};
381
+ const built = await create(modelId, {
382
+ ...modelOptions,
383
+ // Drive preload here (below) so download progress is reported the same
384
+ // way whether `create` is the core's `createWebLLMModel` or an injected
385
+ // factory (e.g. a statically-imported `webLLM`, needed under bundlers).
386
+ preload: false,
378
387
  initProgressCallback: (report) => {
379
388
  setProgress(report.progress);
380
389
  setText(report.text);
381
- optionsRef.current?.initProgressCallback?.(report);
390
+ modelOptions.initProgressCallback?.(report);
382
391
  }
383
392
  });
393
+ await (0, import_agent_web3.preloadWebLLMModel)(built);
384
394
  setModel(built);
385
395
  return built;
386
396
  } catch (err) {
@@ -823,6 +833,8 @@ var import_agent_web4 = require("@dudko.dev/agent-web");
823
833
  createWebLLMModel,
824
834
  defineTool,
825
835
  isWebGPUAvailable,
836
+ preloadWebLLMModel,
837
+ unloadWebLLMModel,
826
838
  useAgent,
827
839
  useAgentContext,
828
840
  useCredentials,
@@ -1 +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;A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,UACxC,WAAW,CAAC,MAAM;AAChB,gBAAI,EAAE,QAAQ,SAAS;AACrB,gBAAE,eAAe;AACjB,mBAAK,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,UACA,UAAU;AAAA;AAAA,MACZ;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,OAAO;AAAA,UAC3B,UAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OAEJ;AAAA,KACF;AAEJ;;;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"]}
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 {\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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;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,M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,KAAK;AAAA,IACf;AAAA,EACF;AAEA,SACE,+CAAC,SAAI,WAAW,CAAC,eAAe,SAAS,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,GACjE;AAAA,mDAAC,WAAM,WAAU,sBACd;AAAA;AAAA,MACA,WACC,+CAAC,UAAK,WAAU,sBACd;AAAA,sDAAC,aAAU,MAAM,IAAI;AAAA,QAAE;AAAA,SACzB;AAAA,OAEJ;AAAA,IACA,+CAAC,SAAI,WAAU,oBACb;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,MAAK;AAAA,UACL,cAAa;AAAA,UACb;AAAA,UACA,aAAa,UAAU,+DAAuB;AAAA,UAC9C,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,UACxC,WAAW,CAAC,MAAM;AAChB,gBAAI,EAAE,QAAQ,SAAS;AACrB,gBAAE,eAAe;AACjB,mBAAK,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,UACA,UAAU;AAAA;AAAA,MACZ;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,OAAO;AAAA,UAC3B,UAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OAEJ;AAAA,KACF;AAEJ;;;AhBlEA,IAAAC,oBASO;","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"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
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';
3
+ import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunResult, Agent, AgentEventHandler, BrowserAgentConfig, CredentialStore, WebLLMModelOptions, createWebLLMModel } from '@dudko.dev/agent-web';
4
+ export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, BrowserAgentConfig, CredentialStore, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, LogLevel, MemoryCredentialStore, ModelInput, ProviderModelSpec, ProviderType, RunOptions, RunResult, VaultCredentialStore, createAgent, createWebLLMModel, defineTool, isWebGPUAvailable, preloadWebLLMModel, unloadWebLLMModel } from '@dudko.dev/agent-web';
5
5
 
6
6
  /**
7
7
  * Lifecycle of the agent instance the hook owns.
@@ -167,6 +167,29 @@ declare const useCredentials: (store?: CredentialStore) => UseCredentialsReturn;
167
167
 
168
168
  /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
169
169
  type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
170
+ /**
171
+ * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's
172
+ * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.
173
+ */
174
+ type WebLLMModelFactory = (modelId: string, options?: WebLLMModelOptions) => Promise<WebLLMModel>;
175
+ interface UseWebLLMModelOptions extends WebLLMModelOptions {
176
+ /**
177
+ * Override how the model is built. **Bundled browser apps (Vite, Next, …)
178
+ * usually need this**: the core builds WebLLM via `await import('@browser-ai/
179
+ * web-llm')`, and a bundler frequently stubs that dynamic import to an empty
180
+ * module — the failure surfaces as `webLLM is not a function`. Pass a factory
181
+ * that imports `webLLM` statically so the bundler includes it:
182
+ *
183
+ * ```ts
184
+ * import { webLLM } from '@browser-ai/web-llm'
185
+ * const create = (id, opts) => Promise.resolve(webLLM(id, opts))
186
+ * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
187
+ * ```
188
+ *
189
+ * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.
190
+ */
191
+ create?: WebLLMModelFactory;
192
+ }
170
193
  interface UseWebLLMModelReturn {
171
194
  /** The built model once loaded — pass to `createAgent({ model })`. */
172
195
  model: WebLLMModel | undefined;
@@ -188,16 +211,20 @@ interface UseWebLLMModelReturn {
188
211
  /**
189
212
  * Load a local WebGPU model with WebLLM and track its download progress.
190
213
  * Nothing downloads until you call `load()` (models are large), so you can
191
- * gate it behind a user action.
214
+ * gate it behind a user action. `load()` eagerly initializes the engine (via
215
+ * the core's `preloadWebLLMModel`), so `ready` means "ready to chat" and
216
+ * progress fills during the load rather than silently on the first message.
192
217
  *
193
218
  * ```tsx
194
- * const local = useWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC')
219
+ * import { webLLM } from '@browser-ai/web-llm' // your app's optional peer
220
+ * const create = (id: string, opts?: WebLLMModelOptions) => Promise.resolve(webLLM(id, opts))
221
+ * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
195
222
  * // <button disabled={!local.supported || local.loading} onClick={local.load}>Load</button>
196
223
  * // {local.loading && <ModelLoadBar load={{ progress: local.progress, text: local.text }} />}
197
224
  * // local.ready && <AgentProvider config={{ model: local.model! }}>…
198
225
  * ```
199
226
  */
200
- declare const useWebLLMModel: (modelId: string, options?: WebLLMModelOptions) => UseWebLLMModelReturn;
227
+ declare const useWebLLMModel: (modelId: string, options?: UseWebLLMModelOptions) => UseWebLLMModelReturn;
201
228
 
202
229
  interface AgentProviderProps extends UseAgentOptions {
203
230
  /** The agent configuration (see `@dudko.dev/agent-web`). */
@@ -351,4 +378,4 @@ interface ApiKeyFormProps {
351
378
  */
352
379
  declare const ApiKeyForm: ({ credentials, credentialRef, label, placeholder, onChange, className, }: ApiKeyFormProps) => react.JSX.Element;
353
380
 
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 };
381
+ 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 UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, createInitialAgentState, useAgent, useAgentContext, useCredentials, useOptionalAgentContext, useWebLLMModel };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
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';
3
+ import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunResult, Agent, AgentEventHandler, BrowserAgentConfig, CredentialStore, WebLLMModelOptions, createWebLLMModel } from '@dudko.dev/agent-web';
4
+ export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, BrowserAgentConfig, CredentialStore, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, LogLevel, MemoryCredentialStore, ModelInput, ProviderModelSpec, ProviderType, RunOptions, RunResult, VaultCredentialStore, createAgent, createWebLLMModel, defineTool, isWebGPUAvailable, preloadWebLLMModel, unloadWebLLMModel } from '@dudko.dev/agent-web';
5
5
 
6
6
  /**
7
7
  * Lifecycle of the agent instance the hook owns.
@@ -167,6 +167,29 @@ declare const useCredentials: (store?: CredentialStore) => UseCredentialsReturn;
167
167
 
168
168
  /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
169
169
  type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
170
+ /**
171
+ * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's
172
+ * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.
173
+ */
174
+ type WebLLMModelFactory = (modelId: string, options?: WebLLMModelOptions) => Promise<WebLLMModel>;
175
+ interface UseWebLLMModelOptions extends WebLLMModelOptions {
176
+ /**
177
+ * Override how the model is built. **Bundled browser apps (Vite, Next, …)
178
+ * usually need this**: the core builds WebLLM via `await import('@browser-ai/
179
+ * web-llm')`, and a bundler frequently stubs that dynamic import to an empty
180
+ * module — the failure surfaces as `webLLM is not a function`. Pass a factory
181
+ * that imports `webLLM` statically so the bundler includes it:
182
+ *
183
+ * ```ts
184
+ * import { webLLM } from '@browser-ai/web-llm'
185
+ * const create = (id, opts) => Promise.resolve(webLLM(id, opts))
186
+ * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
187
+ * ```
188
+ *
189
+ * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.
190
+ */
191
+ create?: WebLLMModelFactory;
192
+ }
170
193
  interface UseWebLLMModelReturn {
171
194
  /** The built model once loaded — pass to `createAgent({ model })`. */
172
195
  model: WebLLMModel | undefined;
@@ -188,16 +211,20 @@ interface UseWebLLMModelReturn {
188
211
  /**
189
212
  * Load a local WebGPU model with WebLLM and track its download progress.
190
213
  * Nothing downloads until you call `load()` (models are large), so you can
191
- * gate it behind a user action.
214
+ * gate it behind a user action. `load()` eagerly initializes the engine (via
215
+ * the core's `preloadWebLLMModel`), so `ready` means "ready to chat" and
216
+ * progress fills during the load rather than silently on the first message.
192
217
  *
193
218
  * ```tsx
194
- * const local = useWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC')
219
+ * import { webLLM } from '@browser-ai/web-llm' // your app's optional peer
220
+ * const create = (id: string, opts?: WebLLMModelOptions) => Promise.resolve(webLLM(id, opts))
221
+ * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
195
222
  * // <button disabled={!local.supported || local.loading} onClick={local.load}>Load</button>
196
223
  * // {local.loading && <ModelLoadBar load={{ progress: local.progress, text: local.text }} />}
197
224
  * // local.ready && <AgentProvider config={{ model: local.model! }}>…
198
225
  * ```
199
226
  */
200
- declare const useWebLLMModel: (modelId: string, options?: WebLLMModelOptions) => UseWebLLMModelReturn;
227
+ declare const useWebLLMModel: (modelId: string, options?: UseWebLLMModelOptions) => UseWebLLMModelReturn;
201
228
 
202
229
  interface AgentProviderProps extends UseAgentOptions {
203
230
  /** The agent configuration (see `@dudko.dev/agent-web`). */
@@ -351,4 +378,4 @@ interface ApiKeyFormProps {
351
378
  */
352
379
  declare const ApiKeyForm: ({ credentials, credentialRef, label, placeholder, onChange, className, }: ApiKeyFormProps) => react.JSX.Element;
353
380
 
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 };
381
+ 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 UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, createInitialAgentState, useAgent, useAgentContext, useCredentials, useOptionalAgentContext, useWebLLMModel };
package/dist/index.js CHANGED
@@ -311,7 +311,11 @@ var useCredentials = (store) => {
311
311
 
312
312
  // src/hooks/use-webllm-model.ts
313
313
  import { useCallback as useCallback3, useRef as useRef2, useState as useState3 } from "react";
314
- import { createWebLLMModel, isWebGPUAvailable } from "@dudko.dev/agent-web";
314
+ import {
315
+ createWebLLMModel,
316
+ isWebGPUAvailable,
317
+ preloadWebLLMModel
318
+ } from "@dudko.dev/agent-web";
315
319
  var useWebLLMModel = (modelId, options) => {
316
320
  const [model, setModel] = useState3(void 0);
317
321
  const [loading, setLoading] = useState3(false);
@@ -327,15 +331,23 @@ var useWebLLMModel = (modelId, options) => {
327
331
  }
328
332
  setLoading(true);
329
333
  setError(void 0);
334
+ setProgress(0);
335
+ setText("");
330
336
  try {
331
- const built = await createWebLLMModel(modelId, {
332
- ...optionsRef.current,
337
+ const { create = createWebLLMModel, ...modelOptions } = optionsRef.current ?? {};
338
+ const built = await create(modelId, {
339
+ ...modelOptions,
340
+ // Drive preload here (below) so download progress is reported the same
341
+ // way whether `create` is the core's `createWebLLMModel` or an injected
342
+ // factory (e.g. a statically-imported `webLLM`, needed under bundlers).
343
+ preload: false,
333
344
  initProgressCallback: (report) => {
334
345
  setProgress(report.progress);
335
346
  setText(report.text);
336
- optionsRef.current?.initProgressCallback?.(report);
347
+ modelOptions.initProgressCallback?.(report);
337
348
  }
338
349
  });
350
+ await preloadWebLLMModel(built);
339
351
  setModel(built);
340
352
  return built;
341
353
  } catch (err) {
@@ -762,6 +774,8 @@ import {
762
774
  createAgent as createAgent2,
763
775
  defineTool,
764
776
  createWebLLMModel as createWebLLMModel2,
777
+ preloadWebLLMModel as preloadWebLLMModel2,
778
+ unloadWebLLMModel,
765
779
  isWebGPUAvailable as isWebGPUAvailable2,
766
780
  VaultCredentialStore as VaultCredentialStore2,
767
781
  MemoryCredentialStore
@@ -784,6 +798,8 @@ export {
784
798
  createWebLLMModel2 as createWebLLMModel,
785
799
  defineTool,
786
800
  isWebGPUAvailable2 as isWebGPUAvailable,
801
+ preloadWebLLMModel2 as preloadWebLLMModel,
802
+ unloadWebLLMModel,
787
803
  useAgent,
788
804
  useAgentContext,
789
805
  useCredentials,
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 { 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","// ── 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"],"mappings":";AAAA,SAAS,aAAa,WAAW,YAAY,QAAQ,gBAAgB;AAErE;AAAA,EACE;AAAA,OAKK;;;ACSP,IAAM,aAAa,OAAe,EAAE,aAAa,G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AA,UACV,MAAK;AAAA,UACL,cAAa;AAAA,UACb;AAAA,UACA,aAAa,UAAU,+DAAuB;AAAA,UAC9C,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,UACxC,WAAW,CAAC,MAAM;AAChB,gBAAI,EAAE,QAAQ,SAAS;AACrB,gBAAE,eAAe;AACjB,mBAAK,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,UACA,UAAU;AAAA;AAAA,MACZ;AAAA,MACA,gBAAAA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC,gBAAAA;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;;;ACtEA;AAAA,EACE,eAAAI;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,qBAAAC;AAAA,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","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-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,cA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BAAAC,MAAC,SAAI,WAAU,oBACb;AAAA,sBAAAD;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,MAAK;AAAA,UACL,cAAa;AAAA,UACb;AAAA,UACA,aAAa,UAAU,+DAAuB;AAAA,UAC9C,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA,UACxC,WAAW,CAAC,MAAM;AAChB,gBAAI,EAAE,QAAQ,SAAS;AACrB,gBAAE,eAAe;AACjB,mBAAK,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,UACA,UAAU;AAAA;AAAA,MACZ;AAAA,MACA,gBAAAA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,SAAS,MAAM,KAAK,KAAK;AAAA,UACzB,UAAU,QAAQ,CAAC,MAAM,KAAK;AAAA,UAC/B;AAAA;AAAA,MAED;AAAA,MACC,WACC,gBAAAA;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;;;AClEA;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","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.1",
3
+ "version": "0.0.2",
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": [
@@ -104,12 +104,12 @@
104
104
  "node": ">=18"
105
105
  },
106
106
  "peerDependencies": {
107
- "@dudko.dev/agent-web": ">=0.0.2",
107
+ "@dudko.dev/agent-web": ">=0.0.6",
108
108
  "react": ">=18",
109
109
  "react-dom": ">=18"
110
110
  },
111
111
  "devDependencies": {
112
- "@dudko.dev/agent-web": "^0.0.2",
112
+ "@dudko.dev/agent-web": "^0.0.7",
113
113
  "@types/node": "^22.9.0",
114
114
  "@types/react": "^19.0.0",
115
115
  "@types/react-dom": "^19.0.0",