@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.
package/dist/index.cjs ADDED
@@ -0,0 +1,832 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AgentChat: () => AgentChat,
24
+ AgentProvider: () => AgentProvider,
25
+ ApiKeyForm: () => ApiKeyForm,
26
+ Composer: () => Composer,
27
+ MemoryCredentialStore: () => import_agent_web4.MemoryCredentialStore,
28
+ MessageList: () => MessageList,
29
+ ModelLoadBar: () => ModelLoadBar,
30
+ PlanView: () => PlanView,
31
+ StepList: () => StepList,
32
+ UsageBadge: () => UsageBadge,
33
+ VaultCredentialStore: () => import_agent_web4.VaultCredentialStore,
34
+ agentStateReducer: () => agentStateReducer,
35
+ createAgent: () => import_agent_web4.createAgent,
36
+ createInitialAgentState: () => createInitialAgentState,
37
+ createWebLLMModel: () => import_agent_web4.createWebLLMModel,
38
+ defineTool: () => import_agent_web4.defineTool,
39
+ isWebGPUAvailable: () => import_agent_web4.isWebGPUAvailable,
40
+ useAgent: () => useAgent,
41
+ useAgentContext: () => useAgentContext,
42
+ useCredentials: () => useCredentials,
43
+ useOptionalAgentContext: () => useOptionalAgentContext,
44
+ useWebLLMModel: () => useWebLLMModel
45
+ });
46
+ module.exports = __toCommonJS(src_exports);
47
+
48
+ // src/hooks/use-agent.ts
49
+ var import_react = require("react");
50
+ var import_agent_web = require("@dudko.dev/agent-web");
51
+
52
+ // src/state.ts
53
+ var emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, totalTokens: 0 });
54
+ var addUsage = (a, b) => ({
55
+ inputTokens: a.inputTokens + b.inputTokens,
56
+ outputTokens: a.outputTokens + b.outputTokens,
57
+ totalTokens: a.totalTokens + b.totalTokens
58
+ });
59
+ var createInitialAgentState = () => ({
60
+ status: "idle",
61
+ goal: void 0,
62
+ plan: void 0,
63
+ planThought: "",
64
+ steps: [],
65
+ finalText: "",
66
+ usage: emptyUsage(),
67
+ modelLoad: void 0,
68
+ replan: void 0,
69
+ error: void 0,
70
+ stopped: false,
71
+ messages: [],
72
+ events: [],
73
+ seq: 0
74
+ });
75
+ var resetRun = (state) => ({
76
+ ...createInitialAgentState(),
77
+ status: state.status,
78
+ messages: state.messages,
79
+ seq: state.seq
80
+ });
81
+ var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
82
+ var finalizeAssistant = (messages, content) => {
83
+ for (let i = messages.length - 1; i >= 0; i--) {
84
+ const m = messages[i];
85
+ if (m.role === "assistant" && m.pending) {
86
+ const next = messages.slice();
87
+ next[i] = { ...m, content: content || m.content, pending: false };
88
+ return next;
89
+ }
90
+ }
91
+ return messages;
92
+ };
93
+ var streamAssistant = (messages, content) => {
94
+ for (let i = messages.length - 1; i >= 0; i--) {
95
+ const m = messages[i];
96
+ if (m.role === "assistant" && m.pending) {
97
+ const next = messages.slice();
98
+ next[i] = { ...m, content };
99
+ return next;
100
+ }
101
+ }
102
+ return messages;
103
+ };
104
+ var applyEvent = (state, event) => {
105
+ switch (event.type) {
106
+ case "run.start": {
107
+ const base2 = resetRun(state);
108
+ const userId = `msg-${base2.seq}`;
109
+ const assistantId = `msg-${base2.seq + 1}`;
110
+ return {
111
+ ...base2,
112
+ goal: event.goal,
113
+ messages: [
114
+ ...base2.messages,
115
+ { id: userId, role: "user", content: event.goal, pending: false },
116
+ { id: assistantId, role: "assistant", content: "", pending: true }
117
+ ],
118
+ seq: base2.seq + 2
119
+ };
120
+ }
121
+ case "model.load":
122
+ return { ...state, modelLoad: { progress: event.progress, text: event.text } };
123
+ case "plan.thought-delta":
124
+ return { ...state, planThought: state.planThought + event.delta };
125
+ case "plan.created":
126
+ return {
127
+ ...state,
128
+ plan: event.plan,
129
+ planThought: state.planThought || event.plan.thought
130
+ };
131
+ case "plan.revised":
132
+ return { ...state, plan: event.plan, replan: { mode: "revise", reason: event.reason } };
133
+ case "plan.step-added":
134
+ return state;
135
+ case "step.start": {
136
+ const view = {
137
+ id: event.step.id,
138
+ index: event.index,
139
+ total: event.total,
140
+ step: event.step,
141
+ text: "",
142
+ toolCalls: [],
143
+ status: "running",
144
+ blocked: false
145
+ };
146
+ return { ...state, steps: [...state.steps, view] };
147
+ }
148
+ case "step.text-delta":
149
+ return {
150
+ ...state,
151
+ steps: patchStep(state.steps, event.step.id, (s) => ({ ...s, text: s.text + event.delta }))
152
+ };
153
+ case "step.tool-call": {
154
+ const call = { name: event.name, input: event.input, status: "calling" };
155
+ return {
156
+ ...state,
157
+ steps: patchStep(state.steps, event.step.id, (s) => ({
158
+ ...s,
159
+ toolCalls: [...s.toolCalls, call]
160
+ }))
161
+ };
162
+ }
163
+ case "step.tool-result":
164
+ return {
165
+ ...state,
166
+ steps: patchStep(state.steps, event.step.id, (s) => {
167
+ let done = false;
168
+ const toolCalls = s.toolCalls.slice().reverse().map((c) => {
169
+ if (!done && c.status === "calling" && c.name === event.name) {
170
+ done = true;
171
+ return { ...c, output: event.output, ok: event.ok, status: "done" };
172
+ }
173
+ return c;
174
+ }).reverse();
175
+ return { ...s, toolCalls };
176
+ })
177
+ };
178
+ case "step.complete":
179
+ return {
180
+ ...state,
181
+ steps: patchStep(state.steps, event.step.id, (s) => ({
182
+ ...s,
183
+ status: "done",
184
+ summary: event.result.summary,
185
+ blocked: event.result.blocked,
186
+ // The result carries the authoritative, ordered tool-call list.
187
+ toolCalls: event.result.toolCalls.map((c) => ({
188
+ name: c.name,
189
+ input: c.input,
190
+ output: c.output,
191
+ ok: c.ok,
192
+ status: "done"
193
+ }))
194
+ }))
195
+ };
196
+ case "replan.decision":
197
+ return { ...state, replan: { mode: event.mode, reason: event.reason } };
198
+ case "final.text-delta": {
199
+ const finalText = state.finalText + event.delta;
200
+ return { ...state, finalText, messages: streamAssistant(state.messages, finalText) };
201
+ }
202
+ case "final":
203
+ return {
204
+ ...state,
205
+ finalText: event.text,
206
+ messages: finalizeAssistant(state.messages, event.text)
207
+ };
208
+ case "usage":
209
+ return { ...state, usage: addUsage(state.usage, event.usage) };
210
+ case "stopped":
211
+ return {
212
+ ...state,
213
+ stopped: true,
214
+ messages: finalizeAssistant(state.messages, state.finalText || "Stopped.")
215
+ };
216
+ case "error":
217
+ return event.phase === "run" ? {
218
+ ...state,
219
+ error: event.error,
220
+ messages: finalizeAssistant(state.messages, state.finalText || `Error: ${event.error}`)
221
+ } : { ...state, error: event.error };
222
+ case "retry":
223
+ return state;
224
+ default:
225
+ return state;
226
+ }
227
+ };
228
+ var agentStateReducer = (state, action) => {
229
+ switch (action.type) {
230
+ case "reset":
231
+ return { ...createInitialAgentState(), status: state.status, seq: state.seq };
232
+ case "status":
233
+ return {
234
+ ...state,
235
+ status: action.status,
236
+ error: action.status === "error" ? action.error : void 0
237
+ };
238
+ case "event": {
239
+ const next = applyEvent(state, action.event);
240
+ const cap = action.maxEvents ?? 200;
241
+ const events = cap > 0 ? [...state.events, action.event].slice(-cap) : [...state.events, action.event];
242
+ return { ...next, events };
243
+ }
244
+ default:
245
+ return state;
246
+ }
247
+ };
248
+
249
+ // src/util.ts
250
+ var errMessage = (err) => err instanceof Error ? err.message : String(err);
251
+
252
+ // src/hooks/use-agent.ts
253
+ var useAgent = (config, options = {}) => {
254
+ const [state, dispatch] = (0, import_react.useReducer)(agentStateReducer, void 0, createInitialAgentState);
255
+ const agentRef = (0, import_react.useRef)(void 0);
256
+ const abortRef = (0, import_react.useRef)(void 0);
257
+ const [generation, setGeneration] = (0, import_react.useState)(0);
258
+ const configRef = (0, import_react.useRef)(config);
259
+ configRef.current = config;
260
+ const optionsRef = (0, import_react.useRef)(options);
261
+ optionsRef.current = options;
262
+ const reload = (0, import_react.useCallback)(() => setGeneration((g) => g + 1), []);
263
+ const { autoStart, deps } = options;
264
+ (0, import_react.useEffect)(() => {
265
+ agentRef.current = void 0;
266
+ const cfg = configRef.current;
267
+ const shouldBuild = (autoStart !== false || generation > 0) && Boolean(cfg.model);
268
+ if (!shouldBuild) {
269
+ dispatch({ type: "status", status: "idle" });
270
+ return;
271
+ }
272
+ let cancelled = false;
273
+ dispatch({ type: "status", status: "initializing" });
274
+ (0, import_agent_web.createAgent)(cfg).then((agent) => {
275
+ if (cancelled) return;
276
+ agentRef.current = agent;
277
+ dispatch({ type: "status", status: "ready" });
278
+ }).catch((err) => {
279
+ if (cancelled) return;
280
+ dispatch({ type: "status", status: "error", error: errMessage(err) });
281
+ });
282
+ return () => {
283
+ cancelled = true;
284
+ };
285
+ }, [generation, autoStart, ...deps ?? []]);
286
+ (0, import_react.useEffect)(() => () => abortRef.current?.abort(), []);
287
+ const run = (0, import_react.useCallback)(async (goal) => {
288
+ const agent = agentRef.current;
289
+ if (!agent || abortRef.current) return void 0;
290
+ const controller = new AbortController();
291
+ abortRef.current = controller;
292
+ dispatch({ type: "status", status: "running" });
293
+ try {
294
+ return await agent.run(goal, {
295
+ signal: controller.signal,
296
+ onEvent: (event) => {
297
+ dispatch({ type: "event", event, maxEvents: optionsRef.current.maxEvents });
298
+ try {
299
+ optionsRef.current.onEvent?.(event);
300
+ } catch {
301
+ }
302
+ }
303
+ });
304
+ } catch (err) {
305
+ dispatch({
306
+ type: "event",
307
+ event: { type: "error", phase: "run", error: errMessage(err) },
308
+ maxEvents: optionsRef.current.maxEvents
309
+ });
310
+ return void 0;
311
+ } finally {
312
+ abortRef.current = void 0;
313
+ dispatch({ type: "status", status: "ready" });
314
+ }
315
+ }, []);
316
+ const stop = (0, import_react.useCallback)(() => abortRef.current?.abort(), []);
317
+ const reset = (0, import_react.useCallback)(() => dispatch({ type: "reset" }), []);
318
+ return {
319
+ ...state,
320
+ run,
321
+ stop,
322
+ reset,
323
+ reload,
324
+ agent: agentRef.current,
325
+ isRunning: state.status === "running",
326
+ isReady: state.status === "ready"
327
+ };
328
+ };
329
+
330
+ // src/hooks/use-credentials.ts
331
+ var import_react2 = require("react");
332
+ var import_agent_web2 = require("@dudko.dev/agent-web");
333
+ var useCredentials = (store) => {
334
+ const resolved = (0, import_react2.useMemo)(() => store ?? new import_agent_web2.VaultCredentialStore(), [store]);
335
+ const [version, setVersion] = (0, import_react2.useState)(0);
336
+ const setKey = (0, import_react2.useCallback)(
337
+ async (ref, key) => {
338
+ await resolved.setApiKey(ref, key);
339
+ setVersion((v) => v + 1);
340
+ },
341
+ [resolved]
342
+ );
343
+ const removeKey = (0, import_react2.useCallback)(
344
+ async (ref) => {
345
+ await resolved.deleteApiKey(ref);
346
+ setVersion((v) => v + 1);
347
+ },
348
+ [resolved]
349
+ );
350
+ const hasKey = (0, import_react2.useCallback)(
351
+ async (ref) => await resolved.getApiKey(ref) !== void 0,
352
+ [resolved]
353
+ );
354
+ return { store: resolved, setKey, removeKey, hasKey, version };
355
+ };
356
+
357
+ // src/hooks/use-webllm-model.ts
358
+ var import_react3 = require("react");
359
+ var import_agent_web3 = require("@dudko.dev/agent-web");
360
+ var useWebLLMModel = (modelId, options) => {
361
+ const [model, setModel] = (0, import_react3.useState)(void 0);
362
+ const [loading, setLoading] = (0, import_react3.useState)(false);
363
+ const [progress, setProgress] = (0, import_react3.useState)(0);
364
+ const [text, setText] = (0, import_react3.useState)("");
365
+ const [error, setError] = (0, import_react3.useState)(void 0);
366
+ const optionsRef = (0, import_react3.useRef)(options);
367
+ optionsRef.current = options;
368
+ const load = (0, import_react3.useCallback)(async () => {
369
+ if (!(0, import_agent_web3.isWebGPUAvailable)()) {
370
+ setError("WebGPU is not available in this browser.");
371
+ return void 0;
372
+ }
373
+ setLoading(true);
374
+ setError(void 0);
375
+ try {
376
+ const built = await (0, import_agent_web3.createWebLLMModel)(modelId, {
377
+ ...optionsRef.current,
378
+ initProgressCallback: (report) => {
379
+ setProgress(report.progress);
380
+ setText(report.text);
381
+ optionsRef.current?.initProgressCallback?.(report);
382
+ }
383
+ });
384
+ setModel(built);
385
+ return built;
386
+ } catch (err) {
387
+ setError(errMessage(err));
388
+ return void 0;
389
+ } finally {
390
+ setLoading(false);
391
+ }
392
+ }, [modelId]);
393
+ return {
394
+ model,
395
+ load,
396
+ loading,
397
+ progress,
398
+ text,
399
+ error,
400
+ supported: (0, import_agent_web3.isWebGPUAvailable)(),
401
+ ready: model !== void 0
402
+ };
403
+ };
404
+
405
+ // src/context.tsx
406
+ var import_react4 = require("react");
407
+ var import_jsx_runtime = require("react/jsx-runtime");
408
+ var AgentContext = (0, import_react4.createContext)(null);
409
+ var AgentProvider = ({ config, children, ...options }) => {
410
+ const agent = useAgent(config, options);
411
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentContext.Provider, { value: agent, children });
412
+ };
413
+ var useAgentContext = () => {
414
+ const ctx = (0, import_react4.useContext)(AgentContext);
415
+ if (!ctx) throw new Error("useAgentContext must be used within an <AgentProvider>");
416
+ return ctx;
417
+ };
418
+ var useOptionalAgentContext = () => (0, import_react4.useContext)(AgentContext);
419
+
420
+ // src/components/AgentChat.tsx
421
+ var import_react6 = require("react");
422
+
423
+ // src/components/icons.tsx
424
+ var import_jsx_runtime2 = require("react/jsx-runtime");
425
+ var base = (size = 16) => ({
426
+ width: size,
427
+ height: size,
428
+ viewBox: "0 0 24 24",
429
+ fill: "none",
430
+ stroke: "currentColor",
431
+ strokeWidth: 2,
432
+ strokeLinecap: "round",
433
+ strokeLinejoin: "round",
434
+ "aria-hidden": true
435
+ });
436
+ var SendIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("svg", { ...base(size), className, children: [
437
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M22 2 11 13" }),
438
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M22 2 15 22l-4-9-9-4Z" })
439
+ ] });
440
+ var StopIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { ...base(size), className, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2" }) });
441
+ var SpinnerIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { ...base(size), className: ["awr-spin", className].filter(Boolean).join(" "), children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }) });
442
+ var CheckIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { ...base(size), className, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M20 6 9 17l-5-5" }) });
443
+ var AlertIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("svg", { ...base(size), className, children: [
444
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("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" }),
445
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M12 9v4" }),
446
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M12 17h.01" })
447
+ ] });
448
+ var ToolIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { ...base(size), className, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("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" }) });
449
+
450
+ // src/components/Composer.tsx
451
+ var import_react5 = require("react");
452
+ var import_jsx_runtime3 = require("react/jsx-runtime");
453
+ var Composer = ({
454
+ onSubmit,
455
+ busy = false,
456
+ onStop,
457
+ disabled = false,
458
+ placeholder = "Ask the agent to do something\u2026",
459
+ className
460
+ }) => {
461
+ const [text, setText] = (0, import_react5.useState)("");
462
+ const submit = () => {
463
+ const value = text.trim();
464
+ if (!value || busy || disabled) return;
465
+ setText("");
466
+ onSubmit(value);
467
+ };
468
+ const onKeyDown = (e) => {
469
+ if (e.key === "Enter" && !e.shiftKey) {
470
+ e.preventDefault();
471
+ submit();
472
+ }
473
+ };
474
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
475
+ "form",
476
+ {
477
+ className: ["awr-composer", className].filter(Boolean).join(" "),
478
+ onSubmit: (e) => {
479
+ e.preventDefault();
480
+ submit();
481
+ },
482
+ children: [
483
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
484
+ "textarea",
485
+ {
486
+ className: "awr-composer__input",
487
+ value: text,
488
+ onChange: (e) => setText(e.target.value),
489
+ onKeyDown,
490
+ placeholder,
491
+ disabled,
492
+ rows: 1
493
+ }
494
+ ),
495
+ busy ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
496
+ "button",
497
+ {
498
+ type: "button",
499
+ className: "awr-composer__btn awr-composer__btn--stop",
500
+ onClick: onStop,
501
+ "aria-label": "Stop",
502
+ children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StopIcon, { size: 18 })
503
+ }
504
+ ) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
505
+ "button",
506
+ {
507
+ type: "submit",
508
+ className: "awr-composer__btn",
509
+ disabled: disabled || !text.trim(),
510
+ "aria-label": "Send",
511
+ children: disabled ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(SpinnerIcon, { size: 18 }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(SendIcon, { size: 18 })
512
+ }
513
+ )
514
+ ]
515
+ }
516
+ );
517
+ };
518
+
519
+ // src/components/MessageList.tsx
520
+ var import_jsx_runtime4 = require("react/jsx-runtime");
521
+ var MessageList = ({ messages, empty, className }) => {
522
+ if (messages.length === 0) {
523
+ return empty ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "awr-messages__empty", children: empty }) : null;
524
+ }
525
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: ["awr-messages", className].filter(Boolean).join(" "), children: messages.map((m) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: `awr-msg awr-msg--${m.role}`, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "awr-msg__bubble", children: [
526
+ m.content,
527
+ m.pending && !m.content && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(SpinnerIcon, { size: 14, className: "awr-msg__pending" })
528
+ ] }) }, m.id)) });
529
+ };
530
+
531
+ // src/components/ModelLoadBar.tsx
532
+ var import_jsx_runtime5 = require("react/jsx-runtime");
533
+ var ModelLoadBar = ({ load, className }) => {
534
+ const pct = Math.round(Math.max(0, Math.min(1, load.progress)) * 100);
535
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: ["awr-modelload", className].filter(Boolean).join(" "), children: [
536
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "awr-modelload__head", children: [
537
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "awr-modelload__text", children: load.text || "Loading model\u2026" }),
538
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "awr-modelload__pct", children: [
539
+ pct,
540
+ "%"
541
+ ] })
542
+ ] }),
543
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "awr-modelload__track", role: "progressbar", "aria-valuenow": pct, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "awr-modelload__fill", style: { width: `${pct}%` } }) })
544
+ ] });
545
+ };
546
+
547
+ // src/components/format.ts
548
+ var previewValue = (value, max = 140) => {
549
+ if (value === void 0) return "";
550
+ let text;
551
+ if (typeof value === "string") text = value;
552
+ else {
553
+ try {
554
+ text = JSON.stringify(value);
555
+ } catch {
556
+ text = String(value);
557
+ }
558
+ }
559
+ text = text.replace(/\s+/g, " ").trim();
560
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
561
+ };
562
+
563
+ // src/components/StepList.tsx
564
+ var import_jsx_runtime6 = require("react/jsx-runtime");
565
+ var ToolCallRow = ({ call }) => {
566
+ const state = call.status === "calling" ? "calling" : call.ok === false ? "failed" : "ok";
567
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("li", { className: `awr-tool awr-tool--${state}`, children: [
568
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ToolIcon, { size: 13, className: "awr-tool__icon" }),
569
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("code", { className: "awr-tool__name", children: call.name }),
570
+ previewValue(call.input) && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "awr-tool__args", children: previewValue(call.input) }),
571
+ call.status === "calling" && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SpinnerIcon, { size: 12, className: "awr-tool__spin" }),
572
+ call.status === "done" && call.ok === false && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "awr-tool__badge", children: "failed" })
573
+ ] });
574
+ };
575
+ var StepItem = ({ step }) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("li", { className: `awr-step awr-step--${step.blocked ? "blocked" : step.status}`, children: [
576
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "awr-step__head", children: [
577
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "awr-step__marker", children: step.status === "running" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SpinnerIcon, { size: 14 }) : step.blocked ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(AlertIcon, { size: 14 }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CheckIcon, { size: 14 }) }),
578
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("span", { className: "awr-step__index", children: [
579
+ step.index,
580
+ "/",
581
+ step.total
582
+ ] }),
583
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "awr-step__desc", children: step.step.description })
584
+ ] }),
585
+ step.text.trim() && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "awr-step__text", children: step.text.trim() }),
586
+ step.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("ul", { className: "awr-step__tools", children: step.toolCalls.map((call, i) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ToolCallRow, { call }, i)) }),
587
+ step.blocked && step.summary && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "awr-step__blocked", children: step.summary })
588
+ ] });
589
+ var StepList = ({ steps, className }) => {
590
+ if (steps.length === 0) return null;
591
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("ol", { className: ["awr-steps", className].filter(Boolean).join(" "), children: steps.map((step) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StepItem, { step }, step.id)) });
592
+ };
593
+
594
+ // src/components/UsageBadge.tsx
595
+ var import_jsx_runtime7 = require("react/jsx-runtime");
596
+ var fmt = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
597
+ var UsageBadge = ({ usage, className }) => {
598
+ if (usage.totalTokens === 0) return null;
599
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
600
+ "span",
601
+ {
602
+ className: ["awr-usage", className].filter(Boolean).join(" "),
603
+ title: `${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`,
604
+ children: [
605
+ fmt(usage.inputTokens),
606
+ "\u2191 ",
607
+ fmt(usage.outputTokens),
608
+ "\u2193"
609
+ ]
610
+ }
611
+ );
612
+ };
613
+
614
+ // src/components/AgentChat.tsx
615
+ var import_jsx_runtime8 = require("react/jsx-runtime");
616
+ var statusLabel = (status) => {
617
+ switch (status) {
618
+ case "initializing":
619
+ return "Loading model\u2026";
620
+ case "running":
621
+ return "Working\u2026";
622
+ case "error":
623
+ return "Failed to start";
624
+ default:
625
+ return "Ready";
626
+ }
627
+ };
628
+ var AgentChat = ({
629
+ controller,
630
+ title,
631
+ placeholder,
632
+ showActivity = true,
633
+ showUsage = true,
634
+ emptyState = "Ask the agent to do something.",
635
+ className,
636
+ style
637
+ }) => {
638
+ const ctx = useOptionalAgentContext();
639
+ const agent = controller ?? ctx;
640
+ if (!agent) {
641
+ throw new Error(
642
+ "<AgentChat> needs a `controller` prop from useAgent(), or an enclosing <AgentProvider>."
643
+ );
644
+ }
645
+ const bodyRef = (0, import_react6.useRef)(null);
646
+ (0, import_react6.useEffect)(() => {
647
+ const el = bodyRef.current;
648
+ if (el) el.scrollTop = el.scrollHeight;
649
+ }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad]);
650
+ const showReplan = agent.replan && agent.replan.mode !== "continue";
651
+ const loading = agent.modelLoad && agent.modelLoad.progress < 1 && agent.isRunning === false;
652
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: ["awr-chat", className].filter(Boolean).join(" "), style, children: [
653
+ title && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: "awr-chat__title", children: title }),
654
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "awr-chat__body", ref: bodyRef, children: [
655
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(MessageList, { messages: agent.messages, empty: emptyState }),
656
+ showActivity && (agent.steps.length > 0 || agent.planThought) && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "awr-activity", children: [
657
+ agent.planThought.trim() && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("details", { className: "awr-activity__plan", children: [
658
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("summary", { children: "Plan" }),
659
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { className: "awr-activity__thought", children: agent.planThought })
660
+ ] }),
661
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(StepList, { steps: agent.steps }),
662
+ showReplan && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "awr-activity__replan", children: [
663
+ "Replanned (",
664
+ agent.replan.mode,
665
+ "): ",
666
+ agent.replan.reason
667
+ ] })
668
+ ] }),
669
+ agent.modelLoad && (loading || agent.isRunning) && agent.modelLoad.progress < 1 && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(ModelLoadBar, { load: agent.modelLoad })
670
+ ] }),
671
+ agent.error && agent.status === "error" && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "awr-chat__error", children: [
672
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(AlertIcon, { size: 14 }),
673
+ " ",
674
+ agent.error
675
+ ] }),
676
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "awr-chat__footer", children: [
677
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "awr-chat__meta", children: [
678
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("span", { className: `awr-status awr-status--${agent.status}`, children: [
679
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "awr-status__dot" }),
680
+ statusLabel(agent.status)
681
+ ] }),
682
+ showUsage && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(UsageBadge, { usage: agent.usage })
683
+ ] }),
684
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
685
+ Composer,
686
+ {
687
+ onSubmit: (text) => void agent.run(text),
688
+ busy: agent.isRunning,
689
+ onStop: agent.stop,
690
+ disabled: !agent.isReady && !agent.isRunning,
691
+ placeholder
692
+ }
693
+ )
694
+ ] })
695
+ ] });
696
+ };
697
+
698
+ // src/components/PlanView.tsx
699
+ var import_jsx_runtime9 = require("react/jsx-runtime");
700
+ var PlanView = ({ plan, showThought = true, className }) => {
701
+ if (!plan.steps.length && !plan.thought) return null;
702
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: ["awr-plan", className].filter(Boolean).join(" "), children: [
703
+ showThought && plan.thought.trim() && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "awr-plan__thought", children: plan.thought }),
704
+ plan.steps.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("ol", { className: "awr-plan__steps", children: plan.steps.map((step) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("li", { className: "awr-plan__step", children: step.description }, step.id)) })
705
+ ] });
706
+ };
707
+
708
+ // src/components/ApiKeyForm.tsx
709
+ var import_react7 = require("react");
710
+ var import_jsx_runtime10 = require("react/jsx-runtime");
711
+ var ApiKeyForm = ({
712
+ credentials,
713
+ credentialRef,
714
+ label = "API key",
715
+ placeholder = "sk-\u2026",
716
+ onChange,
717
+ className
718
+ }) => {
719
+ const [value, setValue] = (0, import_react7.useState)("");
720
+ const [present, setPresent] = (0, import_react7.useState)(false);
721
+ const [busy, setBusy] = (0, import_react7.useState)(false);
722
+ (0, import_react7.useEffect)(() => {
723
+ let active = true;
724
+ credentials.hasKey(credentialRef).then((has) => {
725
+ if (active) setPresent(has);
726
+ });
727
+ return () => {
728
+ active = false;
729
+ };
730
+ }, [credentials, credentialRef, credentials.version]);
731
+ const save = async () => {
732
+ const key = value.trim();
733
+ if (!key) return;
734
+ setBusy(true);
735
+ try {
736
+ await credentials.setKey(credentialRef, key);
737
+ setValue("");
738
+ setPresent(true);
739
+ onChange?.(true);
740
+ } finally {
741
+ setBusy(false);
742
+ }
743
+ };
744
+ const remove = async () => {
745
+ setBusy(true);
746
+ try {
747
+ await credentials.removeKey(credentialRef);
748
+ setPresent(false);
749
+ onChange?.(false);
750
+ } finally {
751
+ setBusy(false);
752
+ }
753
+ };
754
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: ["awr-keyform", className].filter(Boolean).join(" "), children: [
755
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("label", { className: "awr-keyform__label", children: [
756
+ label,
757
+ present && /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("span", { className: "awr-keyform__saved", children: [
758
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(CheckIcon, { size: 12 }),
759
+ " stored, encrypted"
760
+ ] })
761
+ ] }),
762
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "awr-keyform__row", children: [
763
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
764
+ "input",
765
+ {
766
+ className: "awr-keyform__input",
767
+ type: "password",
768
+ autoComplete: "off",
769
+ value,
770
+ placeholder: present ? "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 (replace)" : placeholder,
771
+ onChange: (e) => setValue(e.target.value),
772
+ onKeyDown: (e) => {
773
+ if (e.key === "Enter") {
774
+ e.preventDefault();
775
+ void save();
776
+ }
777
+ },
778
+ disabled: busy
779
+ }
780
+ ),
781
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
782
+ "button",
783
+ {
784
+ type: "button",
785
+ className: "awr-keyform__btn",
786
+ onClick: () => void save(),
787
+ disabled: busy || !value.trim(),
788
+ children: "Save"
789
+ }
790
+ ),
791
+ present && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
792
+ "button",
793
+ {
794
+ type: "button",
795
+ className: "awr-keyform__btn awr-keyform__btn--ghost",
796
+ onClick: () => void remove(),
797
+ disabled: busy,
798
+ children: "Remove"
799
+ }
800
+ )
801
+ ] })
802
+ ] });
803
+ };
804
+
805
+ // src/index.ts
806
+ var import_agent_web4 = require("@dudko.dev/agent-web");
807
+ // Annotate the CommonJS export names for ESM import in node:
808
+ 0 && (module.exports = {
809
+ AgentChat,
810
+ AgentProvider,
811
+ ApiKeyForm,
812
+ Composer,
813
+ MemoryCredentialStore,
814
+ MessageList,
815
+ ModelLoadBar,
816
+ PlanView,
817
+ StepList,
818
+ UsageBadge,
819
+ VaultCredentialStore,
820
+ agentStateReducer,
821
+ createAgent,
822
+ createInitialAgentState,
823
+ createWebLLMModel,
824
+ defineTool,
825
+ isWebGPUAvailable,
826
+ useAgent,
827
+ useAgentContext,
828
+ useCredentials,
829
+ useOptionalAgentContext,
830
+ useWebLLMModel
831
+ });
832
+ //# sourceMappingURL=index.cjs.map