@dudko.dev/agent-web-react 0.0.1

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