@dudko.dev/agent-web-react 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,11 +5,31 @@ import {
5
5
  } from "@dudko.dev/agent-web";
6
6
 
7
7
  // src/state.ts
8
- var emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, totalTokens: 0 });
8
+ var approxTokens = (value) => {
9
+ if (value === void 0) return 0;
10
+ let text;
11
+ try {
12
+ text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
13
+ } catch {
14
+ text = String(value);
15
+ }
16
+ return Math.ceil(text.length / 4);
17
+ };
18
+ var emptyUsage = () => ({
19
+ inputTokens: 0,
20
+ outputTokens: 0,
21
+ totalTokens: 0,
22
+ reasoningTokens: 0,
23
+ cachedInputTokens: 0,
24
+ cacheWriteTokens: 0
25
+ });
9
26
  var addUsage = (a, b) => ({
10
27
  inputTokens: a.inputTokens + b.inputTokens,
11
28
  outputTokens: a.outputTokens + b.outputTokens,
12
- totalTokens: a.totalTokens + b.totalTokens
29
+ totalTokens: a.totalTokens + b.totalTokens,
30
+ reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),
31
+ cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),
32
+ cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0)
13
33
  });
14
34
  var createInitialAgentState = () => ({
15
35
  status: "idle",
@@ -18,6 +38,16 @@ var createInitialAgentState = () => ({
18
38
  planThought: "",
19
39
  steps: [],
20
40
  finalText: "",
41
+ finalReasoning: "",
42
+ totalUsage: emptyUsage(),
43
+ runStartedAt: void 0,
44
+ runMessageId: void 0,
45
+ approvals: [],
46
+ subagents: [],
47
+ skills: [],
48
+ discoveredTools: [],
49
+ compactions: [],
50
+ budget: void 0,
21
51
  usage: emptyUsage(),
22
52
  modelLoad: void 0,
23
53
  replan: void 0,
@@ -31,20 +61,45 @@ var resetRun = (state) => ({
31
61
  ...createInitialAgentState(),
32
62
  status: state.status,
33
63
  messages: state.messages,
64
+ totalUsage: state.totalUsage,
34
65
  seq: state.seq
35
66
  });
36
67
  var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
37
- var finalizeAssistant = (messages, content) => {
68
+ var patchApproval = (approvals, id, fn) => approvals.map((a) => a.id === id ? fn(a) : a);
69
+ var patchSubagent = (subagents, id, fn) => subagents.map((s) => s.id === id ? fn(s) : s);
70
+ var runningStepId = (steps) => [...steps].reverse().find((s) => s.status === "running")?.id;
71
+ var applySubagentEvent = (view2, event) => {
72
+ switch (event.type) {
73
+ case "step.start":
74
+ return {
75
+ ...view2,
76
+ steps: view2.steps + 1,
77
+ activity: `step ${event.index}/${event.total}: ${event.step.description}`
78
+ };
79
+ case "step.tool-call":
80
+ return { ...view2, toolCalls: view2.toolCalls + 1, activity: `\u2192 ${event.name}` };
81
+ case "final.text-delta":
82
+ return { ...view2, text: view2.text + event.delta, activity: "writing the answer" };
83
+ case "final":
84
+ return { ...view2, text: event.text };
85
+ case "usage":
86
+ return { ...view2, usage: addUsage(view2.usage, event.usage) };
87
+ default:
88
+ return view2;
89
+ }
90
+ };
91
+ var finalizeAssistant = (messages, content, extra = {}) => {
38
92
  for (let i = messages.length - 1; i >= 0; i--) {
39
93
  const m = messages[i];
40
94
  if (m.role === "assistant" && m.pending) {
41
95
  const next = messages.slice();
42
- next[i] = { ...m, content: content || m.content, pending: false };
96
+ next[i] = { ...m, content: content || m.content, pending: false, ...extra };
43
97
  return next;
44
98
  }
45
99
  }
46
100
  return messages;
47
101
  };
102
+ var runDuration = (state, at) => at !== void 0 && state.runStartedAt !== void 0 ? { durationMs: Math.max(0, at - state.runStartedAt) } : {};
48
103
  var streamAssistant = (messages, content) => {
49
104
  for (let i = messages.length - 1; i >= 0; i--) {
50
105
  const m = messages[i];
@@ -56,7 +111,7 @@ var streamAssistant = (messages, content) => {
56
111
  }
57
112
  return messages;
58
113
  };
59
- var applyEvent = (state, event) => {
114
+ var applyEvent = (state, event, ctx) => {
60
115
  switch (event.type) {
61
116
  case "run.start": {
62
117
  const base2 = resetRun(state);
@@ -65,9 +120,17 @@ var applyEvent = (state, event) => {
65
120
  return {
66
121
  ...base2,
67
122
  goal: event.goal,
123
+ runStartedAt: ctx.at,
124
+ runMessageId: assistantId,
68
125
  messages: [
69
126
  ...base2.messages,
70
- { id: userId, role: "user", content: event.goal, pending: false },
127
+ {
128
+ id: userId,
129
+ role: "user",
130
+ content: event.goal,
131
+ pending: false,
132
+ ...ctx.attachments?.length ? { attachments: ctx.attachments } : {}
133
+ },
71
134
  { id: assistantId, role: "assistant", content: "", pending: true }
72
135
  ],
73
136
  seq: base2.seq + 2
@@ -88,25 +151,40 @@ var applyEvent = (state, event) => {
88
151
  case "plan.step-added":
89
152
  return state;
90
153
  case "step.start": {
91
- const view = {
154
+ const view2 = {
92
155
  id: event.step.id,
93
156
  index: event.index,
94
157
  total: event.total,
95
158
  step: event.step,
96
159
  text: "",
160
+ reasoning: "",
97
161
  toolCalls: [],
98
162
  status: "running",
99
163
  blocked: false
100
164
  };
101
- return { ...state, steps: [...state.steps, view] };
165
+ return { ...state, steps: [...state.steps, view2] };
102
166
  }
167
+ case "step.reasoning-delta":
168
+ return {
169
+ ...state,
170
+ steps: patchStep(state.steps, event.step.id, (s) => ({
171
+ ...s,
172
+ reasoning: s.reasoning + event.delta
173
+ }))
174
+ };
103
175
  case "step.text-delta":
104
176
  return {
105
177
  ...state,
106
178
  steps: patchStep(state.steps, event.step.id, (s) => ({ ...s, text: s.text + event.delta }))
107
179
  };
108
180
  case "step.tool-call": {
109
- const call = { name: event.name, input: event.input, status: "calling" };
181
+ const call = {
182
+ name: event.name,
183
+ input: event.input,
184
+ status: "calling",
185
+ inputTokens: approxTokens(event.input),
186
+ ...ctx.at !== void 0 ? { startedAt: ctx.at } : {}
187
+ };
110
188
  return {
111
189
  ...state,
112
190
  steps: patchStep(state.steps, event.step.id, (s) => ({
@@ -123,7 +201,14 @@ var applyEvent = (state, event) => {
123
201
  const toolCalls = s.toolCalls.slice().reverse().map((c) => {
124
202
  if (!done && c.status === "calling" && c.name === event.name) {
125
203
  done = true;
126
- return { ...c, output: event.output, ok: event.ok, status: "done" };
204
+ return {
205
+ ...c,
206
+ output: event.output,
207
+ ok: event.ok,
208
+ status: "done",
209
+ outputTokens: approxTokens(event.output),
210
+ ...ctx.at !== void 0 && c.startedAt !== void 0 ? { durationMs: Math.max(0, ctx.at - c.startedAt) } : {}
211
+ };
127
212
  }
128
213
  return c;
129
214
  }).reverse();
@@ -138,14 +223,27 @@ var applyEvent = (state, event) => {
138
223
  status: "done",
139
224
  summary: event.result.summary,
140
225
  blocked: event.result.blocked,
141
- // The result carries the authoritative, ordered tool-call list.
142
- toolCalls: event.result.toolCalls.map((c) => ({
143
- name: c.name,
144
- input: c.input,
145
- output: c.output,
146
- ok: c.ok,
147
- status: "done"
148
- }))
226
+ // The result carries the authoritative, ordered tool-call list; keep
227
+ // the timing the streamed calls measured (matched in order per name).
228
+ toolCalls: (() => {
229
+ const seen = /* @__PURE__ */ new Map();
230
+ return event.result.toolCalls.map((c) => {
231
+ const nth = seen.get(c.name) ?? 0;
232
+ seen.set(c.name, nth + 1);
233
+ const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth];
234
+ return {
235
+ name: c.name,
236
+ input: c.input,
237
+ output: c.output,
238
+ ok: c.ok,
239
+ status: "done",
240
+ inputTokens: approxTokens(c.input),
241
+ outputTokens: approxTokens(c.output),
242
+ ...streamed?.startedAt !== void 0 ? { startedAt: streamed.startedAt } : {},
243
+ ...streamed?.durationMs !== void 0 ? { durationMs: streamed.durationMs } : {}
244
+ };
245
+ });
246
+ })()
149
247
  }))
150
248
  };
151
249
  case "replan.decision":
@@ -158,21 +256,146 @@ var applyEvent = (state, event) => {
158
256
  return {
159
257
  ...state,
160
258
  finalText: event.text,
161
- messages: finalizeAssistant(state.messages, event.text)
259
+ messages: finalizeAssistant(state.messages, event.text, runDuration(state, ctx.at))
162
260
  };
261
+ case "final.reasoning-delta":
262
+ return { ...state, finalReasoning: state.finalReasoning + event.delta };
163
263
  case "usage":
164
- return { ...state, usage: addUsage(state.usage, event.usage) };
264
+ return {
265
+ ...state,
266
+ usage: addUsage(state.usage, event.usage),
267
+ totalUsage: addUsage(state.totalUsage, event.usage)
268
+ };
269
+ case "tool.approval-requested":
270
+ return {
271
+ ...state,
272
+ approvals: [
273
+ ...state.approvals,
274
+ {
275
+ id: event.id,
276
+ name: event.name,
277
+ input: event.input,
278
+ readOnly: event.readOnly,
279
+ stepId: event.step?.id,
280
+ status: "pending"
281
+ }
282
+ ]
283
+ };
284
+ case "tool.approval-resolved": {
285
+ const known = state.approvals.some((a) => a.id === event.id);
286
+ const decided = (a) => ({
287
+ ...a,
288
+ status: event.approved ? "approved" : "denied",
289
+ reason: event.reason,
290
+ automatic: event.automatic
291
+ });
292
+ return {
293
+ ...state,
294
+ approvals: known ? patchApproval(state.approvals, event.id, decided) : (
295
+ // A policy denial arrives without a request: record it too.
296
+ [
297
+ ...state.approvals,
298
+ decided({
299
+ id: event.id,
300
+ name: event.name,
301
+ input: void 0,
302
+ readOnly: false,
303
+ stepId: runningStepId(state.steps),
304
+ status: "pending"
305
+ })
306
+ ]
307
+ )
308
+ };
309
+ }
310
+ case "subagent.start":
311
+ return {
312
+ ...state,
313
+ subagents: [
314
+ ...state.subagents,
315
+ {
316
+ id: event.id,
317
+ name: event.name,
318
+ task: event.task,
319
+ status: "running",
320
+ stepId: runningStepId(state.steps),
321
+ activity: "starting",
322
+ steps: 0,
323
+ toolCalls: 0,
324
+ text: "",
325
+ usage: emptyUsage()
326
+ }
327
+ ]
328
+ };
329
+ case "subagent.event":
330
+ return {
331
+ ...state,
332
+ subagents: patchSubagent(
333
+ state.subagents,
334
+ event.id,
335
+ (s) => applySubagentEvent(s, event.event)
336
+ )
337
+ };
338
+ case "subagent.complete":
339
+ return {
340
+ ...state,
341
+ subagents: patchSubagent(state.subagents, event.id, (s) => ({
342
+ ...s,
343
+ status: "done",
344
+ activity: "done",
345
+ text: event.text,
346
+ usage: event.usage
347
+ }))
348
+ };
349
+ case "subagent.error":
350
+ return {
351
+ ...state,
352
+ subagents: patchSubagent(state.subagents, event.id, (s) => ({
353
+ ...s,
354
+ status: "error",
355
+ activity: "failed",
356
+ error: event.error
357
+ }))
358
+ };
359
+ case "skill.activated":
360
+ return state.skills.includes(event.name) ? state : { ...state, skills: [...state.skills, event.name] };
361
+ case "tools.discovered":
362
+ return {
363
+ ...state,
364
+ discoveredTools: [.../* @__PURE__ */ new Set([...state.discoveredTools, ...event.names])]
365
+ };
366
+ case "context.compacted":
367
+ return {
368
+ ...state,
369
+ compactions: [
370
+ ...state.compactions,
371
+ { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens }
372
+ ]
373
+ };
374
+ case "budget.exceeded":
375
+ return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } };
165
376
  case "stopped":
166
377
  return {
167
378
  ...state,
168
379
  stopped: true,
169
- messages: finalizeAssistant(state.messages, state.finalText || "Stopped.")
380
+ // Nothing is waiting any more once the run has stopped.
381
+ approvals: state.approvals.map(
382
+ (a) => a.status === "pending" ? { ...a, status: "denied", reason: "stopped" } : a
383
+ ),
384
+ messages: finalizeAssistant(
385
+ state.messages,
386
+ state.finalText || "Stopped.",
387
+ runDuration(state, ctx.at)
388
+ )
170
389
  };
171
390
  case "error":
172
391
  return event.phase === "run" ? {
173
392
  ...state,
174
393
  error: event.error,
175
- messages: finalizeAssistant(state.messages, state.finalText || `Error: ${event.error}`)
394
+ messages: finalizeAssistant(
395
+ state.messages,
396
+ state.finalText || `Error: ${event.error}`,
397
+ { ...runDuration(state, ctx.at), error: true }
398
+ )
176
399
  } : { ...state, error: event.error };
177
400
  case "retry":
178
401
  return state;
@@ -180,6 +403,27 @@ var applyEvent = (state, event) => {
180
403
  return state;
181
404
  }
182
405
  };
406
+ var syncRunMessage = (state) => {
407
+ const id = state.runMessageId;
408
+ if (!id) return state;
409
+ const i = state.messages.findIndex((m2) => m2.id === id);
410
+ if (i < 0) return state;
411
+ const m = state.messages[i];
412
+ const decided = state.approvals.filter((a) => a.status !== "pending");
413
+ const patch = {};
414
+ if (m.steps !== state.steps) patch.steps = state.steps;
415
+ if (m.subagents !== state.subagents) patch.subagents = state.subagents;
416
+ if (m.usage !== state.usage) patch.usage = state.usage;
417
+ if ((m.reasoning ?? "") !== state.finalReasoning) patch.reasoning = state.finalReasoning;
418
+ if (m.skills !== state.skills) patch.skills = state.skills;
419
+ if ((m.approvals?.length ?? 0) !== decided.length || decided.some((a, k) => m.approvals?.[k] !== a)) {
420
+ patch.approvals = decided;
421
+ }
422
+ if (Object.keys(patch).length === 0) return state;
423
+ const messages = state.messages.slice();
424
+ messages[i] = { ...m, ...patch };
425
+ return { ...state, messages };
426
+ };
183
427
  var agentStateReducer = (state, action) => {
184
428
  switch (action.type) {
185
429
  case "reset":
@@ -191,11 +435,26 @@ var agentStateReducer = (state, action) => {
191
435
  error: action.status === "error" ? action.error : void 0
192
436
  };
193
437
  case "event": {
194
- const next = applyEvent(state, action.event);
438
+ const next = syncRunMessage(
439
+ applyEvent(state, action.event, { at: action.at, attachments: action.attachments })
440
+ );
195
441
  const cap = action.maxEvents ?? 200;
196
442
  const events = cap > 0 ? [...state.events, action.event].slice(-cap) : [...state.events, action.event];
197
443
  return { ...next, events };
198
444
  }
445
+ case "load": {
446
+ const maxSeq = action.messages.reduce((n, m) => {
447
+ const k = Number(/^msg-(\d+)$/.exec(m.id)?.[1] ?? -1);
448
+ return Math.max(n, k + 1);
449
+ }, state.seq);
450
+ return {
451
+ ...createInitialAgentState(),
452
+ status: state.status,
453
+ messages: action.messages.map((m) => m.pending ? { ...m, pending: false } : m),
454
+ totalUsage: action.totalUsage ?? emptyUsage(),
455
+ seq: maxSeq
456
+ };
457
+ }
199
458
  default:
200
459
  return state;
201
460
  }
@@ -214,6 +473,31 @@ var useAgent = (config, options = {}) => {
214
473
  configRef.current = config;
215
474
  const optionsRef = useRef(options);
216
475
  optionsRef.current = options;
476
+ const resolversRef = useRef(/* @__PURE__ */ new Map());
477
+ const settleAll = useCallback((decision) => {
478
+ for (const resolve of resolversRef.current.values()) resolve(decision);
479
+ resolversRef.current.clear();
480
+ }, []);
481
+ const uiOnRequest = useCallback(
482
+ (req2) => new Promise((resolve) => {
483
+ resolversRef.current.set(req2.id, resolve);
484
+ }),
485
+ []
486
+ );
487
+ const [sessionId, setSessionId] = useState(config.sessionId ?? "default");
488
+ const sessionRef = useRef(sessionId);
489
+ sessionRef.current = sessionId;
490
+ const configMode = config.toolApproval?.mode ?? "autopilot";
491
+ const [approvalMode, setApprovalModeState] = useState(configMode);
492
+ const modeRef = useRef(configMode);
493
+ const setApprovalMode = useCallback((mode) => {
494
+ modeRef.current = mode;
495
+ agentRef.current?.setToolApprovalMode(mode);
496
+ setApprovalModeState(mode);
497
+ }, []);
498
+ useEffect(() => {
499
+ if (configMode !== modeRef.current) setApprovalMode(configMode);
500
+ }, [configMode, setApprovalMode]);
217
501
  const reload = useCallback(() => setGeneration((g) => g + 1), []);
218
502
  const { autoStart, deps } = options;
219
503
  useEffect(() => {
@@ -224,10 +508,16 @@ var useAgent = (config, options = {}) => {
224
508
  dispatch({ type: "status", status: "idle" });
225
509
  return;
226
510
  }
511
+ const routeApprovals = optionsRef.current.approvals !== false && !cfg.toolApproval?.onRequest;
512
+ const built = routeApprovals ? {
513
+ ...cfg,
514
+ toolApproval: { ...cfg.toolApproval, mode: modeRef.current, onRequest: uiOnRequest }
515
+ } : cfg;
227
516
  let cancelled = false;
228
517
  dispatch({ type: "status", status: "initializing" });
229
- createAgent(cfg).then((agent) => {
518
+ createAgent(built).then((agent) => {
230
519
  if (cancelled) return;
520
+ agent.setToolApprovalMode(modeRef.current);
231
521
  agentRef.current = agent;
232
522
  dispatch({ type: "status", status: "ready" });
233
523
  }).catch((err) => {
@@ -238,38 +528,106 @@ var useAgent = (config, options = {}) => {
238
528
  cancelled = true;
239
529
  };
240
530
  }, [generation, autoStart, ...deps ?? []]);
241
- useEffect(() => () => abortRef.current?.abort(), []);
242
- const run = useCallback(async (goal) => {
243
- const agent = agentRef.current;
244
- if (!agent || abortRef.current) return void 0;
245
- const controller = new AbortController();
246
- abortRef.current = controller;
247
- dispatch({ type: "status", status: "running" });
248
- try {
249
- return await agent.run(goal, {
250
- signal: controller.signal,
251
- onEvent: (event) => {
252
- dispatch({ type: "event", event, maxEvents: optionsRef.current.maxEvents });
253
- try {
254
- optionsRef.current.onEvent?.(event);
255
- } catch {
531
+ useEffect(
532
+ () => () => {
533
+ abortRef.current?.abort();
534
+ settleAll({ approved: false, reason: "the view was closed" });
535
+ },
536
+ [settleAll]
537
+ );
538
+ const run = useCallback(
539
+ async (goal, runOptions) => {
540
+ const agent = agentRef.current;
541
+ if (!agent || abortRef.current) return void 0;
542
+ const controller = new AbortController();
543
+ abortRef.current = controller;
544
+ dispatch({ type: "status", status: "running" });
545
+ try {
546
+ return await agent.run(goal, {
547
+ signal: controller.signal,
548
+ sessionId: sessionRef.current,
549
+ ...runOptions?.images?.length ? { images: runOptions.images } : {},
550
+ ...runOptions?.files?.length ? { files: runOptions.files } : {},
551
+ onEvent: (event) => {
552
+ const start = event.type === "run.start";
553
+ const shown = start && runOptions?.label ? { ...event, goal: runOptions.label } : event;
554
+ dispatch({
555
+ type: "event",
556
+ event: shown,
557
+ maxEvents: optionsRef.current.maxEvents,
558
+ at: Date.now(),
559
+ ...start && runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}
560
+ });
561
+ try {
562
+ optionsRef.current.onEvent?.(event);
563
+ } catch {
564
+ }
256
565
  }
257
- }
258
- });
259
- } catch (err) {
566
+ });
567
+ } catch (err) {
568
+ dispatch({
569
+ type: "event",
570
+ event: { type: "error", phase: "run", error: errMessage(err) },
571
+ maxEvents: optionsRef.current.maxEvents
572
+ });
573
+ return void 0;
574
+ } finally {
575
+ abortRef.current = void 0;
576
+ settleAll({ approved: false, reason: "the run ended" });
577
+ dispatch({ type: "status", status: "ready" });
578
+ }
579
+ },
580
+ [settleAll]
581
+ );
582
+ const stop = useCallback(() => {
583
+ abortRef.current?.abort();
584
+ settleAll({ approved: false, reason: "stopped by the user" });
585
+ }, [settleAll]);
586
+ const reset = useCallback(() => {
587
+ dispatch({ type: "reset" });
588
+ void configRef.current.memory?.clear(sessionRef.current).catch(() => {
589
+ });
590
+ }, []);
591
+ const loadChat = useCallback(
592
+ (chat) => {
593
+ abortRef.current?.abort();
594
+ sessionRef.current = chat.sessionId;
595
+ setSessionId(chat.sessionId);
596
+ dispatch({ type: "load", messages: chat.messages ?? [], totalUsage: chat.totalUsage });
597
+ },
598
+ []
599
+ );
600
+ const approve = useCallback((id, opts) => {
601
+ const resolve = resolversRef.current.get(id);
602
+ if (!resolve) return;
603
+ resolversRef.current.delete(id);
604
+ resolve({ approved: true, remember: opts?.remember });
605
+ }, []);
606
+ const deny = useCallback((id, reason) => {
607
+ const resolve = resolversRef.current.get(id);
608
+ if (!resolve) return;
609
+ resolversRef.current.delete(id);
610
+ resolve({ approved: false, reason });
611
+ }, []);
612
+ const compact = useCallback(async () => {
613
+ const agent = agentRef.current;
614
+ if (!agent) return void 0;
615
+ const result = await agent.compact({ sessionId: sessionRef.current });
616
+ if (result.compacted) {
260
617
  dispatch({
261
618
  type: "event",
262
- event: { type: "error", phase: "run", error: errMessage(err) },
263
- maxEvents: optionsRef.current.maxEvents
619
+ event: {
620
+ type: "context.compacted",
621
+ scope: "history",
622
+ beforeTokens: result.beforeTokens,
623
+ afterTokens: result.afterTokens
624
+ },
625
+ maxEvents: optionsRef.current.maxEvents,
626
+ at: Date.now()
264
627
  });
265
- return void 0;
266
- } finally {
267
- abortRef.current = void 0;
268
- dispatch({ type: "status", status: "ready" });
269
628
  }
629
+ return result;
270
630
  }, []);
271
- const stop = useCallback(() => abortRef.current?.abort(), []);
272
- const reset = useCallback(() => dispatch({ type: "reset" }), []);
273
631
  return {
274
632
  ...state,
275
633
  run,
@@ -278,31 +636,311 @@ var useAgent = (config, options = {}) => {
278
636
  reload,
279
637
  agent: agentRef.current,
280
638
  isRunning: state.status === "running",
281
- isReady: state.status === "ready"
639
+ isReady: state.status === "ready",
640
+ pendingApprovals: state.approvals.filter((a) => a.status === "pending"),
641
+ approve,
642
+ deny,
643
+ approvalMode,
644
+ setApprovalMode,
645
+ compact,
646
+ sessionId,
647
+ loadChat
648
+ };
649
+ };
650
+
651
+ // src/hooks/use-chat-history.ts
652
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo, useRef as useRef2, useState as useState2 } from "react";
653
+
654
+ // src/chat-history.ts
655
+ var DB_VERSION = 1;
656
+ var req = (r) => new Promise((resolve, reject) => {
657
+ r.onsuccess = () => resolve(r.result);
658
+ r.onerror = () => reject(r.error);
659
+ });
660
+ var ChatHistoryStore = class {
661
+ dbName;
662
+ storeName;
663
+ memory;
664
+ db;
665
+ constructor(opts = {}) {
666
+ this.dbName = opts.dbName ?? "agent-web-react";
667
+ this.storeName = opts.storeName ?? "chats";
668
+ if (opts.memory || typeof indexedDB === "undefined") this.memory = /* @__PURE__ */ new Map();
669
+ }
670
+ open() {
671
+ this.db ??= new Promise((resolve, reject) => {
672
+ const r = indexedDB.open(this.dbName, DB_VERSION);
673
+ r.onupgradeneeded = () => {
674
+ if (!r.result.objectStoreNames.contains(this.storeName)) {
675
+ r.result.createObjectStore(this.storeName, { keyPath: "id" });
676
+ }
677
+ };
678
+ r.onsuccess = () => resolve(r.result);
679
+ r.onerror = () => reject(r.error);
680
+ }).catch((err) => {
681
+ this.db = void 0;
682
+ throw err;
683
+ });
684
+ return this.db;
685
+ }
686
+ async tx(mode) {
687
+ const db = await this.open();
688
+ return db.transaction(this.storeName, mode).objectStore(this.storeName);
689
+ }
690
+ async list() {
691
+ const all = this.memory ? [...this.memory.values()] : await req((await this.tx("readonly")).getAll());
692
+ return all.map(({ messages, ...rest }) => ({ ...rest, messageCount: messages.length })).sort((a, b) => b.updatedAt - a.updatedAt);
693
+ }
694
+ async get(id) {
695
+ if (this.memory) return this.memory.get(id);
696
+ return req((await this.tx("readonly")).get(id));
697
+ }
698
+ async put(record) {
699
+ if (this.memory) {
700
+ this.memory.set(record.id, structuredClone(record));
701
+ return;
702
+ }
703
+ await req((await this.tx("readwrite")).put(record));
704
+ }
705
+ async delete(id) {
706
+ if (this.memory) {
707
+ this.memory.delete(id);
708
+ return;
709
+ }
710
+ await req((await this.tx("readwrite")).delete(id));
711
+ }
712
+ async clear() {
713
+ if (this.memory) {
714
+ this.memory.clear();
715
+ return;
716
+ }
717
+ await req((await this.tx("readwrite")).clear());
718
+ }
719
+ };
720
+ var chatTitle = (messages) => {
721
+ const first = messages.find((m) => m.role === "user")?.content.replace(/\s+/g, " ").trim();
722
+ if (!first) return "New chat";
723
+ return first.length > 60 ? `${first.slice(0, 59)}\u2026` : first;
724
+ };
725
+ var newChatId = () => `chat-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
726
+
727
+ // src/hooks/use-chat-history.ts
728
+ var useChatHistory = (agent, options = {}) => {
729
+ const enabled = options.enabled !== false;
730
+ const store = useMemo(() => options.store ?? new ChatHistoryStore(), [options.store]);
731
+ const [chats, setChats] = useState2([]);
732
+ const [loading, setLoading] = useState2(enabled);
733
+ const createdRef = useRef2(/* @__PURE__ */ new Map());
734
+ const agentRef = useRef2(agent);
735
+ agentRef.current = agent;
736
+ const refresh = useCallback2(async () => {
737
+ try {
738
+ setChats(await store.list());
739
+ } catch {
740
+ }
741
+ }, [store]);
742
+ const newChat = useCallback2(() => {
743
+ agentRef.current.loadChat({ sessionId: newChatId(), messages: [] });
744
+ }, []);
745
+ const select = useCallback2(
746
+ async (id) => {
747
+ const record = await store.get(id).catch(() => void 0);
748
+ if (!record) return;
749
+ createdRef.current.set(id, record.createdAt);
750
+ agentRef.current.loadChat({
751
+ sessionId: record.id,
752
+ messages: record.messages,
753
+ totalUsage: record.totalUsage
754
+ });
755
+ },
756
+ [store]
757
+ );
758
+ const remove = useCallback2(
759
+ async (id) => {
760
+ await store.delete(id).catch(() => {
761
+ });
762
+ if (id === agentRef.current.sessionId) newChat();
763
+ await refresh();
764
+ },
765
+ [store, newChat, refresh]
766
+ );
767
+ useEffect2(() => {
768
+ if (!enabled) return;
769
+ let active = true;
770
+ void (async () => {
771
+ const list = await store.list().catch(() => []);
772
+ if (!active) return;
773
+ setChats(list);
774
+ if (options.resumeLatest !== false && list[0]) await select(list[0].id);
775
+ else newChat();
776
+ setLoading(false);
777
+ })();
778
+ return () => {
779
+ active = false;
780
+ };
781
+ }, [enabled, store]);
782
+ const { messages, totalUsage, sessionId, isRunning } = agent;
783
+ useEffect2(() => {
784
+ if (!enabled || loading || isRunning || messages.length === 0) return;
785
+ const now = Date.now();
786
+ const createdAt = createdRef.current.get(sessionId) ?? now;
787
+ createdRef.current.set(sessionId, createdAt);
788
+ const record = {
789
+ id: sessionId,
790
+ title: chatTitle(messages),
791
+ createdAt,
792
+ updatedAt: now,
793
+ messages,
794
+ totalUsage
795
+ };
796
+ void store.put(record).then(refresh).catch(() => {
797
+ });
798
+ }, [enabled, loading, isRunning, messages, totalUsage, sessionId, store, refresh]);
799
+ return { chats, currentId: sessionId, loading, select, newChat, remove };
800
+ };
801
+
802
+ // src/hooks/use-virtual-files.ts
803
+ import { useCallback as useCallback3, useEffect as useEffect3, useState as useState3 } from "react";
804
+ var readDataUrl = (file) => new Promise((resolve, reject) => {
805
+ const r = new FileReader();
806
+ r.onload = () => resolve(String(r.result));
807
+ r.onerror = () => reject(r.error ?? new Error("could not read the file"));
808
+ r.readAsDataURL(file);
809
+ });
810
+ var useVirtualFiles = (vfs, prefix = "/") => {
811
+ const [files, setFiles] = useState3([]);
812
+ const [loading, setLoading] = useState3(Boolean(vfs));
813
+ const [error, setError] = useState3();
814
+ const refresh = useCallback3(async () => {
815
+ if (!vfs) return;
816
+ try {
817
+ setFiles(await vfs.list(prefix));
818
+ setError(void 0);
819
+ } catch (err) {
820
+ setError(err instanceof Error ? err.message : String(err));
821
+ } finally {
822
+ setLoading(false);
823
+ }
824
+ }, [vfs, prefix]);
825
+ useEffect3(() => {
826
+ if (!vfs) return;
827
+ void refresh();
828
+ return vfs.onChange(() => void refresh());
829
+ }, [vfs, refresh]);
830
+ const upload = useCallback3(
831
+ async (file, dir = "/uploads") => {
832
+ if (!vfs) return;
833
+ const path = `${dir.replace(/\/$/, "")}/${file.name.replace(/[^\w.-]+/g, "_") || "file"}`;
834
+ const type = file.type || "application/octet-stream";
835
+ if (type.startsWith("text/") || /json|xml|yaml|markdown|csv/.test(type)) {
836
+ await vfs.write(path, await file.text(), { mimeType: type });
837
+ } else {
838
+ await vfs.writeDataUrl(path, await readDataUrl(file));
839
+ }
840
+ },
841
+ [vfs]
842
+ );
843
+ const remove = useCallback3(
844
+ async (path) => {
845
+ await vfs?.delete(path);
846
+ },
847
+ [vfs]
848
+ );
849
+ const dataUrl = useCallback3(async (path) => vfs?.readDataUrl(path), [vfs]);
850
+ const text = useCallback3(
851
+ async (path) => {
852
+ const f = await vfs?.read(path);
853
+ return f && f.encoding === "utf8" ? f.content : void 0;
854
+ },
855
+ [vfs]
856
+ );
857
+ return { files, loading, error, refresh, upload, remove, dataUrl, text };
858
+ };
859
+
860
+ // src/hooks/use-speech-to-text.ts
861
+ import { useCallback as useCallback4, useEffect as useEffect4, useRef as useRef3, useState as useState4 } from "react";
862
+ var browserRecognizer = () => {
863
+ const g = globalThis;
864
+ const Ctor = g.SpeechRecognition ?? g.webkitSpeechRecognition;
865
+ return Ctor ? () => new Ctor() : void 0;
866
+ };
867
+ var useSpeechToText = (options = {}) => {
868
+ const optionsRef = useRef3(options);
869
+ optionsRef.current = options;
870
+ const factory = options.createRecognizer ?? browserRecognizer();
871
+ const [listening, setListening] = useState4(false);
872
+ const [interim, setInterim] = useState4("");
873
+ const [error, setError] = useState4();
874
+ const recRef = useRef3(void 0);
875
+ const stop = useCallback4(() => {
876
+ recRef.current?.stop();
877
+ }, []);
878
+ const start = useCallback4(() => {
879
+ if (!factory || recRef.current) return;
880
+ const rec = factory();
881
+ rec.lang = optionsRef.current.lang ?? (typeof navigator !== "undefined" ? navigator.language : void 0) ?? "en-US";
882
+ rec.continuous = optionsRef.current.continuous !== false;
883
+ rec.interimResults = true;
884
+ rec.onresult = (ev) => {
885
+ let pending = "";
886
+ for (let i = ev.resultIndex; i < ev.results.length; i += 1) {
887
+ const r = ev.results[i];
888
+ if (r.isFinal) optionsRef.current.onFinal?.(r[0].transcript.trim());
889
+ else pending += r[0].transcript;
890
+ }
891
+ setInterim(pending);
892
+ };
893
+ rec.onerror = (ev) => {
894
+ if (ev.error && ev.error !== "no-speech" && ev.error !== "aborted") setError(ev.error);
895
+ };
896
+ rec.onend = () => {
897
+ recRef.current = void 0;
898
+ setListening(false);
899
+ setInterim("");
900
+ };
901
+ recRef.current = rec;
902
+ setError(void 0);
903
+ try {
904
+ rec.start();
905
+ setListening(true);
906
+ } catch (err) {
907
+ recRef.current = void 0;
908
+ setError(err instanceof Error ? err.message : String(err));
909
+ }
910
+ }, [factory]);
911
+ useEffect4(() => () => recRef.current?.abort?.(), []);
912
+ return {
913
+ supported: Boolean(factory),
914
+ listening,
915
+ interim,
916
+ error,
917
+ start,
918
+ stop,
919
+ toggle: () => recRef.current ? stop() : start()
282
920
  };
283
921
  };
284
922
 
285
923
  // src/hooks/use-credentials.ts
286
- import { useCallback as useCallback2, useMemo, useState as useState2 } from "react";
924
+ import { useCallback as useCallback5, useMemo as useMemo2, useState as useState5 } from "react";
287
925
  import { VaultCredentialStore } from "@dudko.dev/agent-web";
288
926
  var useCredentials = (store) => {
289
- const resolved = useMemo(() => store ?? new VaultCredentialStore(), [store]);
290
- const [version, setVersion] = useState2(0);
291
- const setKey = useCallback2(
927
+ const resolved = useMemo2(() => store ?? new VaultCredentialStore(), [store]);
928
+ const [version, setVersion] = useState5(0);
929
+ const setKey = useCallback5(
292
930
  async (ref, key) => {
293
931
  await resolved.setApiKey(ref, key);
294
932
  setVersion((v) => v + 1);
295
933
  },
296
934
  [resolved]
297
935
  );
298
- const removeKey = useCallback2(
936
+ const removeKey = useCallback5(
299
937
  async (ref) => {
300
938
  await resolved.deleteApiKey(ref);
301
939
  setVersion((v) => v + 1);
302
940
  },
303
941
  [resolved]
304
942
  );
305
- const hasKey = useCallback2(
943
+ const hasKey = useCallback5(
306
944
  async (ref) => await resolved.getApiKey(ref) !== void 0,
307
945
  [resolved]
308
946
  );
@@ -310,7 +948,7 @@ var useCredentials = (store) => {
310
948
  };
311
949
 
312
950
  // src/hooks/use-mcp.ts
313
- import { useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2, useState as useState3 } from "react";
951
+ import { useCallback as useCallback6, useEffect as useEffect5, useRef as useRef4, useState as useState6 } from "react";
314
952
  var OAUTH_UNSUPPORTED = "The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.";
315
953
  var PENDING_KEY = "agent-web-react:mcp:pending";
316
954
  var OAUTH_KEY = "agent-web-react:mcp:oauth";
@@ -423,27 +1061,27 @@ var watchAuthorization = (tools, mod, onUnauthorized) => {
423
1061
  return Object.fromEntries(entries);
424
1062
  };
425
1063
  var useMcp = (options = {}) => {
426
- const [status, setStatus] = useState3("idle");
427
- const [tools, setTools] = useState3(void 0);
428
- const [catalog, setCatalog] = useState3([]);
429
- const [error, setError] = useState3(void 0);
430
- const [authorizationUrl, setAuthorizationUrl] = useState3(void 0);
431
- const [oauthSupported, setOauthSupported] = useState3(void 0);
432
- const [completingAuthorization, setCompletingAuthorization] = useState3(
1064
+ const [status, setStatus] = useState6("idle");
1065
+ const [tools, setTools] = useState6(void 0);
1066
+ const [catalog, setCatalog] = useState6([]);
1067
+ const [error, setError] = useState6(void 0);
1068
+ const [authorizationUrl, setAuthorizationUrl] = useState6(void 0);
1069
+ const [oauthSupported, setOauthSupported] = useState6(void 0);
1070
+ const [completingAuthorization, setCompletingAuthorization] = useState6(
433
1071
  () => readCallbackParams() !== void 0
434
1072
  );
435
- const connectionRef = useRef2(void 0);
436
- const providerRef = useRef2(void 0);
437
- const epochRef = useRef2(0);
438
- const optionsRef = useRef2(options);
1073
+ const connectionRef = useRef4(void 0);
1074
+ const providerRef = useRef4(void 0);
1075
+ const epochRef = useRef4(0);
1076
+ const optionsRef = useRef4(options);
439
1077
  optionsRef.current = options;
440
- const closeConnection = useCallback3(async () => {
1078
+ const closeConnection = useCallback6(async () => {
441
1079
  const open = connectionRef.current;
442
1080
  connectionRef.current = void 0;
443
1081
  if (open) await open.close().catch(() => {
444
1082
  });
445
1083
  }, []);
446
- const checkOAuthSupport = useCallback3(async () => {
1084
+ const checkOAuthSupport = useCallback6(async () => {
447
1085
  try {
448
1086
  const mod = await loadMcp();
449
1087
  const supported = typeof mod.BrowserOAuthProvider === "function";
@@ -454,7 +1092,7 @@ var useMcp = (options = {}) => {
454
1092
  return false;
455
1093
  }
456
1094
  }, []);
457
- const connect = useCallback3(
1095
+ const connect = useCallback6(
458
1096
  async (opts) => {
459
1097
  const epoch = ++epochRef.current;
460
1098
  const current = () => epochRef.current === epoch;
@@ -540,7 +1178,7 @@ var useMcp = (options = {}) => {
540
1178
  },
541
1179
  [closeConnection]
542
1180
  );
543
- const disconnect = useCallback3(async () => {
1181
+ const disconnect = useCallback6(async () => {
544
1182
  epochRef.current++;
545
1183
  await closeConnection();
546
1184
  setTools(void 0);
@@ -549,12 +1187,12 @@ var useMcp = (options = {}) => {
549
1187
  setError(void 0);
550
1188
  setStatus("idle");
551
1189
  }, [closeConnection]);
552
- const authorize = useCallback3(() => {
1190
+ const authorize = useCallback6(() => {
553
1191
  if (authorizationUrl && typeof globalThis.location !== "undefined") {
554
1192
  globalThis.location.href = authorizationUrl;
555
1193
  }
556
1194
  }, [authorizationUrl]);
557
- const forgetAuthorization = useCallback3(async () => {
1195
+ const forgetAuthorization = useCallback6(async () => {
558
1196
  const record = readRecord(OAUTH_KEY);
559
1197
  writeRecord(PENDING_KEY, void 0);
560
1198
  writeRecord(OAUTH_KEY, void 0);
@@ -575,7 +1213,7 @@ var useMcp = (options = {}) => {
575
1213
  providerRef.current = void 0;
576
1214
  await disconnect();
577
1215
  }, [disconnect]);
578
- useEffect2(() => {
1216
+ useEffect5(() => {
579
1217
  const callback = readCallbackParams();
580
1218
  if (!callback) {
581
1219
  setCompletingAuthorization(false);
@@ -620,7 +1258,7 @@ var useMcp = (options = {}) => {
620
1258
  }
621
1259
  })();
622
1260
  }, [connect]);
623
- useEffect2(
1261
+ useEffect5(
624
1262
  () => () => {
625
1263
  epochRef.current++;
626
1264
  void closeConnection();
@@ -643,86 +1281,691 @@ var useMcp = (options = {}) => {
643
1281
  };
644
1282
  };
645
1283
 
646
- // src/hooks/use-webllm-model.ts
647
- import { useCallback as useCallback4, useRef as useRef3, useState as useState4 } from "react";
648
- import {
649
- createWebLLMModel,
650
- isWebGPUAvailable,
651
- preloadWebLLMModel
652
- } from "@dudko.dev/agent-web";
653
- var useWebLLMModel = (modelId, options) => {
654
- const [model, setModel] = useState4(void 0);
655
- const [loading, setLoading] = useState4(false);
656
- const [progress, setProgress] = useState4(0);
657
- const [text, setText] = useState4("");
658
- const [error, setError] = useState4(void 0);
659
- const optionsRef = useRef3(options);
1284
+ // src/hooks/use-mcp-servers.ts
1285
+ import { useCallback as useCallback7, useEffect as useEffect6, useMemo as useMemo3, useRef as useRef5, useState as useState7 } from "react";
1286
+ var DEFAULT_KEY = "agent-web-react:mcp-servers";
1287
+ var sanitize = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 32) || "mcp";
1288
+ var view = (s, patch = {}) => ({
1289
+ name: s.name,
1290
+ url: s.url,
1291
+ auth: s.auth,
1292
+ status: "idle",
1293
+ catalog: [],
1294
+ ...patch
1295
+ });
1296
+ var useMcpServers = (options = {}) => {
1297
+ const storageKey = options.storageKey ?? DEFAULT_KEY;
1298
+ const pendingKey = `${storageKey}:pending`;
1299
+ const persist = options.persist !== false;
1300
+ const [servers, setServers] = useState7(
1301
+ () => persist ? (readRecord(storageKey) ?? []).map((s) => view(s)) : []
1302
+ );
1303
+ const [oauthSupported, setOauthSupported] = useState7(void 0);
1304
+ const [completingAuthorization, setCompleting] = useState7(
1305
+ () => readCallbackParams() !== void 0 && readRecord(pendingKey) !== void 0
1306
+ );
1307
+ const [toolsVersion, setToolsVersion] = useState7(0);
1308
+ const liveRef = useRef5(/* @__PURE__ */ new Map());
1309
+ const specsRef = useRef5(/* @__PURE__ */ new Map());
1310
+ if (specsRef.current.size === 0 && servers.length > 0) {
1311
+ for (const s of servers)
1312
+ specsRef.current.set(s.name, { name: s.name, url: s.url, auth: s.auth });
1313
+ }
1314
+ const optionsRef = useRef5(options);
660
1315
  optionsRef.current = options;
661
- const load = useCallback4(async () => {
662
- if (!isWebGPUAvailable()) {
663
- setError("WebGPU is not available in this browser.");
664
- return void 0;
1316
+ const unmountedRef = useRef5(false);
1317
+ const saveList = useCallback7(() => {
1318
+ if (!persist) return;
1319
+ writeRecord(storageKey, [...specsRef.current.values()]);
1320
+ }, [persist, storageKey]);
1321
+ const patch = useCallback7((name, p) => {
1322
+ if (unmountedRef.current) return;
1323
+ setServers((list) => list.map((s) => s.name === name ? { ...s, ...p } : s));
1324
+ }, []);
1325
+ const live = (name) => {
1326
+ let l = liveRef.current.get(name);
1327
+ if (!l) {
1328
+ l = { epoch: 0 };
1329
+ liveRef.current.set(name, l);
665
1330
  }
666
- setLoading(true);
667
- setError(void 0);
668
- setProgress(0);
669
- setText("");
670
- try {
671
- const { create = createWebLLMModel, ...modelOptions } = optionsRef.current ?? {};
672
- const built = await create(modelId, {
673
- ...modelOptions,
674
- // Drive preload here (below) so download progress is reported the same
675
- // way whether `create` is the core's `createWebLLMModel` or an injected
676
- // factory (e.g. a statically-imported `webLLM`, needed under bundlers).
677
- preload: false,
678
- initProgressCallback: (report) => {
679
- setProgress(report.progress);
680
- setText(report.text);
681
- modelOptions.initProgressCallback?.(report);
682
- }
683
- });
684
- await preloadWebLLMModel(built);
685
- setModel(built);
686
- return built;
687
- } catch (err) {
688
- setError(errMessage(err));
689
- return void 0;
690
- } finally {
691
- setLoading(false);
1331
+ return l;
1332
+ };
1333
+ const closeServer = useCallback7(async (name) => {
1334
+ const l = liveRef.current.get(name);
1335
+ if (!l) return;
1336
+ l.epoch += 1;
1337
+ const open = l.connection;
1338
+ l.connection = void 0;
1339
+ if (l.tools) {
1340
+ l.tools = void 0;
1341
+ setToolsVersion((v) => v + 1);
692
1342
  }
693
- }, [modelId]);
694
- return {
695
- model,
696
- load,
697
- loading,
698
- progress,
699
- text,
700
- error,
701
- supported: isWebGPUAvailable(),
702
- ready: model !== void 0
1343
+ if (open) await open.close().catch(() => {
1344
+ });
1345
+ }, []);
1346
+ const providerFor = (mod, spec) => {
1347
+ if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
1348
+ return new mod.BrowserOAuthProvider({
1349
+ serverUrl: spec.url,
1350
+ redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
1351
+ clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
1352
+ scope: spec.oauth?.scope
1353
+ });
703
1354
  };
704
- };
705
-
706
- // src/context.tsx
707
- import { createContext, useContext } from "react";
708
- import { jsx } from "react/jsx-runtime";
709
- var AgentContext = createContext(null);
710
- var AgentProvider = ({ config, children, ...options }) => {
711
- const agent = useAgent(config, options);
712
- return /* @__PURE__ */ jsx(AgentContext.Provider, { value: agent, children });
713
- };
714
- var useAgentContext = () => {
715
- const ctx = useContext(AgentContext);
716
- if (!ctx) throw new Error("useAgentContext must be used within an <AgentProvider>");
717
- return ctx;
718
- };
719
- var useOptionalAgentContext = () => useContext(AgentContext);
720
-
721
- // src/components/AgentChat.tsx
722
- import { useEffect as useEffect3, useRef as useRef4 } from "react";
723
-
1355
+ const connectServer = useCallback7(
1356
+ async (name) => {
1357
+ const spec = specsRef.current.get(name);
1358
+ if (!spec) return;
1359
+ await closeServer(name);
1360
+ const l = live(name);
1361
+ const epoch = ++l.epoch;
1362
+ const current = () => !unmountedRef.current && l.epoch === epoch;
1363
+ if (spec.auth === "bearer" && !l.token) {
1364
+ patch(name, { status: "idle", error: "Enter the bearer token to connect." });
1365
+ return;
1366
+ }
1367
+ patch(name, {
1368
+ status: "connecting",
1369
+ error: void 0,
1370
+ authorizationUrl: void 0,
1371
+ catalog: []
1372
+ });
1373
+ try {
1374
+ const mod = await loadMcp();
1375
+ setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
1376
+ let provider;
1377
+ if (spec.auth === "oauth") {
1378
+ provider = providerFor(mod, spec);
1379
+ l.provider = provider;
1380
+ }
1381
+ const connection = await mod.connectMcpHttp(
1382
+ {
1383
+ [name]: {
1384
+ url: spec.url,
1385
+ headers: spec.auth === "bearer" && l.token ? { Authorization: `Bearer ${l.token}` } : void 0,
1386
+ authProvider: provider,
1387
+ connectTimeoutMs: optionsRef.current.connectTimeoutMs
1388
+ }
1389
+ },
1390
+ {
1391
+ clientName: optionsRef.current.clientName,
1392
+ onLog: optionsRef.current.onLog,
1393
+ connectTimeoutMs: optionsRef.current.connectTimeoutMs
1394
+ }
1395
+ );
1396
+ if (!current()) {
1397
+ await connection.close().catch(() => {
1398
+ });
1399
+ return;
1400
+ }
1401
+ const outcome = describeMcpResult(connection.results[0]);
1402
+ if (outcome.status !== "connected") {
1403
+ await connection.close().catch(() => {
1404
+ });
1405
+ if (outcome.status === "needs-authorization") {
1406
+ const url = provider?.authorizationUrl;
1407
+ patch(name, {
1408
+ status: "needs-authorization",
1409
+ authorizationUrl: url ? String(url) : void 0
1410
+ });
1411
+ return;
1412
+ }
1413
+ throw new Error(outcome.error);
1414
+ }
1415
+ l.connection = connection;
1416
+ l.tools = watchAuthorization(connection.tools, mod, () => {
1417
+ if (!current()) return;
1418
+ const url = l.provider?.authorizationUrl;
1419
+ patch(name, {
1420
+ status: "needs-authorization",
1421
+ authorizationUrl: url ? String(url) : void 0
1422
+ });
1423
+ });
1424
+ setToolsVersion((v) => v + 1);
1425
+ patch(name, { status: "connected", catalog: connection.catalog });
1426
+ } catch (err) {
1427
+ if (!current()) return;
1428
+ patch(name, { status: "error", error: err instanceof Error ? err.message : String(err) });
1429
+ }
1430
+ },
1431
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1432
+ [closeServer, patch, pendingKey]
1433
+ );
1434
+ const add = useCallback7(
1435
+ async (input) => {
1436
+ let name = sanitize(input.name);
1437
+ const taken = specsRef.current.get(name);
1438
+ if (taken && taken.url !== input.url) {
1439
+ let n = 2;
1440
+ while (specsRef.current.has(`${name}_${n}`)) n += 1;
1441
+ name = `${name}_${n}`;
1442
+ }
1443
+ const spec = {
1444
+ name,
1445
+ url: input.url,
1446
+ auth: input.auth ?? "none",
1447
+ ...input.oauth ? { oauth: input.oauth } : {}
1448
+ };
1449
+ specsRef.current.set(name, spec);
1450
+ live(name).token = input.auth === "bearer" ? input.token : void 0;
1451
+ setServers(
1452
+ (list) => list.some((s) => s.name === name) ? list.map((s) => s.name === name ? view(spec) : s) : [...list, view(spec)]
1453
+ );
1454
+ saveList();
1455
+ await connectServer(name);
1456
+ return name;
1457
+ },
1458
+ [connectServer, saveList]
1459
+ );
1460
+ const remove = useCallback7(
1461
+ async (name) => {
1462
+ await closeServer(name);
1463
+ liveRef.current.delete(name);
1464
+ specsRef.current.delete(name);
1465
+ saveList();
1466
+ setServers((list) => list.filter((s) => s.name !== name));
1467
+ },
1468
+ [closeServer, saveList]
1469
+ );
1470
+ const reconnect = useCallback7(
1471
+ async (name, token) => {
1472
+ if (token !== void 0) live(name).token = token;
1473
+ await connectServer(name);
1474
+ },
1475
+ [connectServer]
1476
+ );
1477
+ const authorize = useCallback7(
1478
+ (name) => {
1479
+ const url = servers.find((s) => s.name === name)?.authorizationUrl;
1480
+ const spec = specsRef.current.get(name);
1481
+ if (!url || !spec || typeof globalThis.location === "undefined") return;
1482
+ const pending = {
1483
+ name,
1484
+ url: spec.url,
1485
+ redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
1486
+ scope: spec.oauth?.scope,
1487
+ clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
1488
+ startedAt: Date.now()
1489
+ };
1490
+ writeRecord(pendingKey, pending);
1491
+ globalThis.location.href = url;
1492
+ },
1493
+ [servers, pendingKey]
1494
+ );
1495
+ const forgetAuthorization = useCallback7(
1496
+ async (name) => {
1497
+ const spec = specsRef.current.get(name);
1498
+ const l = liveRef.current.get(name);
1499
+ let provider = l?.provider;
1500
+ if (!provider && spec?.auth === "oauth") {
1501
+ const mod = await loadMcp().catch(() => void 0);
1502
+ if (mod?.BrowserOAuthProvider) provider = providerFor(mod, spec);
1503
+ }
1504
+ await provider?.reset().catch(() => {
1505
+ });
1506
+ if (l) l.provider = void 0;
1507
+ const pending = readRecord(pendingKey);
1508
+ if (pending?.name === name) writeRecord(pendingKey, void 0);
1509
+ await closeServer(name);
1510
+ patch(name, { status: "idle", authorizationUrl: void 0, catalog: [], error: void 0 });
1511
+ },
1512
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1513
+ [closeServer, patch, pendingKey]
1514
+ );
1515
+ const checkOAuthSupport = useCallback7(async () => {
1516
+ try {
1517
+ const mod = await loadMcp();
1518
+ const supported = typeof mod.BrowserOAuthProvider === "function";
1519
+ setOauthSupported(supported);
1520
+ return supported;
1521
+ } catch {
1522
+ setOauthSupported(false);
1523
+ return false;
1524
+ }
1525
+ }, []);
1526
+ useEffect6(() => {
1527
+ unmountedRef.current = false;
1528
+ const callback = readCallbackParams();
1529
+ const pending = readRecord(pendingKey);
1530
+ const fresh = pending !== void 0 && Date.now() - pending.startedAt < PENDING_TTL_MS;
1531
+ const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback));
1532
+ if (callback && pending && !fresh) writeRecord(pendingKey, void 0);
1533
+ if (ours && typeof globalThis.history !== "undefined") {
1534
+ globalThis.history.replaceState(null, "", stripOAuthParams(globalThis.location.href));
1535
+ }
1536
+ const autoConnect = optionsRef.current.autoConnect !== false;
1537
+ void (async () => {
1538
+ if (ours && pending && callback) {
1539
+ try {
1540
+ const mod = await loadMcp();
1541
+ setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
1542
+ if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
1543
+ const spec = specsRef.current.get(pending.name) ?? {
1544
+ name: pending.name,
1545
+ url: pending.url,
1546
+ auth: "oauth"
1547
+ };
1548
+ if (!specsRef.current.has(spec.name)) {
1549
+ specsRef.current.set(spec.name, spec);
1550
+ setServers((list) => [...list, view(spec)]);
1551
+ saveList();
1552
+ }
1553
+ const provider = providerFor(mod, {
1554
+ ...spec,
1555
+ oauth: {
1556
+ redirectUrl: pending.redirectUrl,
1557
+ scope: pending.scope,
1558
+ clientName: pending.clientName
1559
+ }
1560
+ });
1561
+ live(spec.name).provider = provider;
1562
+ await mod.finishMcpOAuth(provider, callback);
1563
+ writeRecord(pendingKey, void 0);
1564
+ } catch (err) {
1565
+ writeRecord(pendingKey, void 0);
1566
+ patch(pending.name, {
1567
+ status: "error",
1568
+ error: err instanceof Error ? err.message : String(err)
1569
+ });
1570
+ }
1571
+ }
1572
+ setCompleting(false);
1573
+ if (autoConnect || ours) {
1574
+ await Promise.all(
1575
+ [...specsRef.current.keys()].filter((name) => autoConnect || name === pending?.name).map((name) => connectServer(name))
1576
+ );
1577
+ }
1578
+ })();
1579
+ return () => {
1580
+ unmountedRef.current = true;
1581
+ for (const name of liveRef.current.keys()) void closeServer(name);
1582
+ };
1583
+ }, []);
1584
+ const tools = useMemo3(() => {
1585
+ const merged = {};
1586
+ for (const l of liveRef.current.values()) if (l.tools) Object.assign(merged, l.tools);
1587
+ return merged;
1588
+ }, [toolsVersion]);
1589
+ const catalog = useMemo3(
1590
+ () => servers.filter((s) => s.status === "connected").flatMap((s) => s.catalog),
1591
+ [servers]
1592
+ );
1593
+ return {
1594
+ servers,
1595
+ tools,
1596
+ catalog,
1597
+ connectedCount: servers.filter((s) => s.status === "connected").length,
1598
+ completingAuthorization,
1599
+ oauthSupported,
1600
+ checkOAuthSupport,
1601
+ add,
1602
+ remove,
1603
+ reconnect,
1604
+ authorize,
1605
+ forgetAuthorization
1606
+ };
1607
+ };
1608
+
1609
+ // src/hooks/use-webllm-model.ts
1610
+ import { useCallback as useCallback8, useRef as useRef6, useState as useState8 } from "react";
1611
+ import {
1612
+ createWebLLMModel,
1613
+ isWebGPUAvailable,
1614
+ preloadWebLLMModel
1615
+ } from "@dudko.dev/agent-web";
1616
+ var useWebLLMModel = (modelId, options) => {
1617
+ const [model, setModel] = useState8(void 0);
1618
+ const [loading, setLoading] = useState8(false);
1619
+ const [progress, setProgress] = useState8(0);
1620
+ const [text, setText] = useState8("");
1621
+ const [error, setError] = useState8(void 0);
1622
+ const optionsRef = useRef6(options);
1623
+ optionsRef.current = options;
1624
+ const load = useCallback8(async () => {
1625
+ if (!isWebGPUAvailable()) {
1626
+ setError("WebGPU is not available in this browser.");
1627
+ return void 0;
1628
+ }
1629
+ setLoading(true);
1630
+ setError(void 0);
1631
+ setProgress(0);
1632
+ setText("");
1633
+ try {
1634
+ const { create = createWebLLMModel, ...modelOptions } = optionsRef.current ?? {};
1635
+ const built = await create(modelId, {
1636
+ ...modelOptions,
1637
+ // Drive preload here (below) so download progress is reported the same
1638
+ // way whether `create` is the core's `createWebLLMModel` or an injected
1639
+ // factory (e.g. a statically-imported `webLLM`, needed under bundlers).
1640
+ preload: false,
1641
+ initProgressCallback: (report) => {
1642
+ setProgress(report.progress);
1643
+ setText(report.text);
1644
+ modelOptions.initProgressCallback?.(report);
1645
+ }
1646
+ });
1647
+ await preloadWebLLMModel(built);
1648
+ setModel(built);
1649
+ return built;
1650
+ } catch (err) {
1651
+ setError(errMessage(err));
1652
+ return void 0;
1653
+ } finally {
1654
+ setLoading(false);
1655
+ }
1656
+ }, [modelId]);
1657
+ return {
1658
+ model,
1659
+ load,
1660
+ loading,
1661
+ progress,
1662
+ text,
1663
+ error,
1664
+ supported: isWebGPUAvailable(),
1665
+ ready: model !== void 0
1666
+ };
1667
+ };
1668
+
1669
+ // src/labels.tsx
1670
+ import { createContext, useContext, useMemo as useMemo4 } from "react";
1671
+
1672
+ // src/composer.ts
1673
+ var parseSlash = (text) => {
1674
+ const m = /^\/([\w-]*)(?:\s+([\s\S]*))?$/.exec(text.trimStart());
1675
+ return m ? { name: m[1].toLowerCase(), args: (m[2] ?? "").trim() } : void 0;
1676
+ };
1677
+ var filterCommands = (commands, query) => {
1678
+ const q = query.toLowerCase();
1679
+ if (!q) return commands;
1680
+ const starts = commands.filter((c) => c.name.toLowerCase().startsWith(q));
1681
+ const contains = commands.filter(
1682
+ (c) => !starts.includes(c) && (c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q))
1683
+ );
1684
+ return [...starts, ...contains];
1685
+ };
1686
+ var attachmentKindOf = (mediaType, name) => {
1687
+ if (mediaType.startsWith("image/")) return "image";
1688
+ if (mediaType === "application/pdf" || /\.pdf$/i.test(name)) return "pdf";
1689
+ if (mediaType.startsWith("text/") || /json|xml|yaml|javascript|typescript|csv|markdown|x-sh|sql|toml/.test(mediaType) || /\.(txt|md|markdown|json|csv|tsv|ya?ml|xml|html?|css|m?[jt]sx?|py|sh|log|sql|toml|ini|env)$/i.test(
1690
+ name
1691
+ )) {
1692
+ return "text";
1693
+ }
1694
+ return "file";
1695
+ };
1696
+ var withAttachments = (text, files) => {
1697
+ const texts = files.filter((f) => f.kind === "text" && f.text !== void 0);
1698
+ if (texts.length === 0) return text;
1699
+ const blocks = texts.map((f) => {
1700
+ const body = f.text;
1701
+ const fence = body.includes("```") ? "~~~" : "```";
1702
+ const where = f.path ? ` (also saved as ${f.path})` : "";
1703
+ return `### ${f.name}${where}
1704
+ ${fence}
1705
+ ${body}
1706
+ ${fence}`;
1707
+ });
1708
+ return `${text}
1709
+
1710
+ Attached file(s):
1711
+ ${blocks.join("\n\n")}`;
1712
+ };
1713
+ var attachmentRefusal = (kind, caps, canConvertPdf = false) => {
1714
+ if (kind === "text" || !caps) return void 0;
1715
+ if (kind === "image" && caps.images === false) {
1716
+ return "This model can't see images \u2014 switch to a vision-capable model (Gemini, Claude, GPT-4o/5) to attach one.";
1717
+ }
1718
+ if (kind === "pdf" && caps.pdf === false && !canConvertPdf) {
1719
+ return "This model can't read PDF files \u2014 convert it to text first, or switch to Gemini, Claude or GPT-4o/5.";
1720
+ }
1721
+ if (kind === "file" && caps.files === false) {
1722
+ return "This model can't take file attachments \u2014 paste the text instead.";
1723
+ }
1724
+ return void 0;
1725
+ };
1726
+ var formatElapsed = (ms) => {
1727
+ const s = Math.max(0, Math.floor(ms / 1e3));
1728
+ if (s < 60) return `${s}s`;
1729
+ const m = Math.floor(s / 60);
1730
+ if (m < 60) return `${m}m ${s % 60}s`;
1731
+ return `${Math.floor(m / 60)}h ${m % 60}m`;
1732
+ };
1733
+ var kTokens = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k` : `${n}`;
1734
+ var defaultNoticeTexts = {
1735
+ limit: (kind, used, cap) => {
1736
+ const calls = kind === "tool-calls";
1737
+ const what = calls ? "Tool-call" : `${kind[0].toUpperCase()}${kind.slice(1)}-token`;
1738
+ const amount = calls ? `${used}/${cap} calls` : `${kTokens(used)}/${kTokens(cap)} tokens`;
1739
+ return `${what} limit reached \xB7 ${amount} \u2014 the agent stopped early and answered with what it had`;
1740
+ },
1741
+ compacted: (scope, before, after) => `Context compacted (${scope}) \xB7 ${kTokens(before)} \u2192 ${kTokens(after)} tokens`
1742
+ };
1743
+ var noticesOf = (state, texts = {}) => {
1744
+ const t = { ...defaultNoticeTexts, ...texts };
1745
+ const out = [];
1746
+ if (state.status === "error" && state.error) {
1747
+ out.push({ id: `error:${state.error}`, tone: "error", text: state.error });
1748
+ }
1749
+ if (state.budget) {
1750
+ const b = state.budget;
1751
+ out.push({
1752
+ id: `budget:${state.goal ?? ""}:${b.kind}:${b.cap}`,
1753
+ tone: "warn",
1754
+ text: t.limit(b.kind, b.tokens, b.cap)
1755
+ });
1756
+ }
1757
+ const last = state.compactions.at(-1);
1758
+ if (last) {
1759
+ out.push({
1760
+ id: `compact:${state.compactions.length}:${last.beforeTokens}:${last.afterTokens}`,
1761
+ tone: "info",
1762
+ text: t.compacted(last.scope, last.beforeTokens, last.afterTokens)
1763
+ });
1764
+ }
1765
+ return out;
1766
+ };
1767
+
1768
+ // src/labels.tsx
1769
+ import { jsx } from "react/jsx-runtime";
1770
+ var plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
1771
+ var kb = (n) => n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`;
1772
+ var defaultLabels = {
1773
+ emptyState: "Ask the agent to do something.",
1774
+ status: {
1775
+ idle: "Idle",
1776
+ initializing: "Loading model\u2026",
1777
+ ready: "Ready",
1778
+ running: "Working\u2026",
1779
+ error: "Failed to start"
1780
+ },
1781
+ history: "Chats",
1782
+ newChat: "New chat",
1783
+ files: "Files",
1784
+ totalUsage: "Tokens this conversation used, by kind",
1785
+ showHistory: "Show chats",
1786
+ showFiles: "Show files",
1787
+ close: "Close",
1788
+ steps: (n) => plural(n, "step", "steps"),
1789
+ toolCalls: (n) => plural(n, "tool call", "tool calls"),
1790
+ subagents: (n) => plural(n, "subagent", "subagents"),
1791
+ skillsUsed: (names) => `skills: ${names}`,
1792
+ answerThoughts: "Thinking about the answer",
1793
+ stepThoughts: "Thoughts",
1794
+ usageTitle: "Tokens this answer spent, by kind",
1795
+ attachments: "Attachments",
1796
+ planned: "Plan",
1797
+ replanned: (mode, reason) => `Replanned (${mode}): ${reason}`,
1798
+ placeholder: "Ask the agent to do something\u2026 ( / for commands, Ctrl+V to paste an image )",
1799
+ listening: "Listening\u2026",
1800
+ message: "Message",
1801
+ dropHint: "Drop files or images to attach them",
1802
+ attach: "Attach files",
1803
+ attachTitle: "Attach files or images (or paste with Ctrl+V, or drop them here)",
1804
+ commands: "Commands",
1805
+ commandsTitle: "Commands and skills ( / )",
1806
+ send: "Send",
1807
+ stop: "Stop",
1808
+ dismiss: "Dismiss",
1809
+ remove: (name) => `Remove ${name}`,
1810
+ dictate: "Dictate (speech to text)",
1811
+ dictateTitle: "Dictate \u2014 speech to text in the browser",
1812
+ stopDictation: "Stop dictation",
1813
+ microphone: "Microphone",
1814
+ model: "Model",
1815
+ thinking: "Thinking",
1816
+ toolConsent: "Tool consent",
1817
+ modes: {
1818
+ autopilot: { label: "Auto", hint: "Autopilot \u2014 run every tool without asking" },
1819
+ "ask-writes": {
1820
+ label: "Ask",
1821
+ hint: "Run read-only tools freely; ask before anything that may change state"
1822
+ },
1823
+ "ask-all": { label: "Ask all", hint: "Ask before every tool call" },
1824
+ "read-only": {
1825
+ label: "Read-only",
1826
+ hint: "Only read-only tools; refuse changes without asking"
1827
+ }
1828
+ },
1829
+ timerRunning: "This run so far",
1830
+ timerLast: "The last run took",
1831
+ agents: (n) => plural(n, "agent", "agents"),
1832
+ agentsTitle: "Subagents running in this run",
1833
+ notices: defaultNoticeTexts,
1834
+ attachmentsOnly: "(attachments)",
1835
+ seeAttachments: "See the attachments.",
1836
+ tooLarge: (name, mb) => `${name} is larger than ${mb} MB.`,
1837
+ binaryText: (name) => `${name} looks binary \u2014 it can't be attached as text.`,
1838
+ commandGroups: { commands: "Commands", consent: "Consent", skills: "Skills" },
1839
+ commandDescriptions: {
1840
+ compact: "Summarise the conversation to free context",
1841
+ new: "Start a new conversation",
1842
+ stop: "Stop the current run",
1843
+ autopilot: "Run every tool without asking",
1844
+ ask: "Ask before tools that may change state",
1845
+ askAll: "Ask before every tool call",
1846
+ readOnly: "Only read; refuse changes",
1847
+ think: (levels) => `Set thinking: ${levels}`
1848
+ },
1849
+ thinkingLevels: { off: "Default", low: "Low", medium: "Medium", high: "High" },
1850
+ filesEmpty: "No files yet. Attachments and files the agent writes appear here.",
1851
+ upload: "Upload",
1852
+ download: "Download",
1853
+ delete: "Delete",
1854
+ preview: "Preview",
1855
+ bytes: kb,
1856
+ historyEmpty: "No saved chats yet.",
1857
+ deleteChat: "Delete chat",
1858
+ messagesCount: (n) => plural(n, "message", "messages"),
1859
+ approvalLead: "The agent wants to run",
1860
+ approve: "Allow once",
1861
+ alwaysAllow: "Always allow",
1862
+ deny: "Deny",
1863
+ declinedReason: "the user declined",
1864
+ readOnlyTool: "read-only",
1865
+ consentWaiting: "waiting for your consent",
1866
+ consentAllowed: "allowed",
1867
+ consentDenied: (reason) => `denied${reason ? ` \u2014 ${reason}` : ""}`,
1868
+ failed: "failed",
1869
+ toolCostTitle: "Estimated tokens of the arguments and of the result fed back to the model (chars / 4), and the call's duration"
1870
+ };
1871
+ var NESTED = [
1872
+ "status",
1873
+ "modes",
1874
+ "commandGroups",
1875
+ "commandDescriptions",
1876
+ "thinkingLevels"
1877
+ ];
1878
+ var mergeLabels = (base2, over) => {
1879
+ if (!over) return base2;
1880
+ const out = { ...base2, ...over };
1881
+ for (const key of NESTED) {
1882
+ if (over[key]) out[key] = { ...base2[key], ...over[key] };
1883
+ }
1884
+ return out;
1885
+ };
1886
+ var LabelsContext = createContext(defaultLabels);
1887
+ var AgentLabelsProvider = ({ labels, children }) => {
1888
+ const parent = useContext(LabelsContext);
1889
+ const value = useMemo4(() => mergeLabels(parent, labels), [parent, labels]);
1890
+ return /* @__PURE__ */ jsx(LabelsContext.Provider, { value, children });
1891
+ };
1892
+ var useLabels = (over) => {
1893
+ const ctx = useContext(LabelsContext);
1894
+ return useMemo4(() => mergeLabels(ctx, over), [ctx, over]);
1895
+ };
1896
+
1897
+ // src/image-resize.ts
1898
+ var canvasOf = (w, h) => {
1899
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(w, h);
1900
+ if (typeof document !== "undefined") {
1901
+ const c = document.createElement("canvas");
1902
+ c.width = w;
1903
+ c.height = h;
1904
+ return c;
1905
+ }
1906
+ return void 0;
1907
+ };
1908
+ var toBlob = (canvas, type, quality) => "convertToBlob" in canvas ? canvas.convertToBlob({ type, quality }) : new Promise((resolve) => canvas.toBlob(resolve, type, quality));
1909
+ var downscaleImage = async (file, opts = {}) => {
1910
+ const maxDimension = opts.maxDimension ?? 1568;
1911
+ const maxPixels = opts.maxPixels ?? 115e4;
1912
+ if (typeof createImageBitmap !== "function" || !file.type.startsWith("image/") || file.type === "image/gif" || file.type === "image/svg+xml") {
1913
+ return file;
1914
+ }
1915
+ let bitmap;
1916
+ try {
1917
+ bitmap = await createImageBitmap(file);
1918
+ } catch {
1919
+ return file;
1920
+ }
1921
+ const { width, height } = bitmap;
1922
+ const scale = Math.min(
1923
+ 1,
1924
+ maxDimension / Math.max(width, height),
1925
+ Math.sqrt(maxPixels / Math.max(1, width * height))
1926
+ );
1927
+ if (scale >= 1) {
1928
+ bitmap.close();
1929
+ return file;
1930
+ }
1931
+ const w = Math.max(1, Math.round(width * scale));
1932
+ const h = Math.max(1, Math.round(height * scale));
1933
+ const canvas = canvasOf(w, h);
1934
+ const ctx = canvas?.getContext("2d");
1935
+ if (!canvas || !ctx) {
1936
+ bitmap.close();
1937
+ return file;
1938
+ }
1939
+ ctx.drawImage(bitmap, 0, 0, w, h);
1940
+ bitmap.close();
1941
+ const type = file.type === "image/png" || file.type === "image/webp" ? file.type : "image/jpeg";
1942
+ const out = await toBlob(canvas, type, opts.quality ?? 0.9);
1943
+ return out && out.size < file.size ? out : file;
1944
+ };
1945
+
1946
+ // src/context.tsx
1947
+ import { createContext as createContext2, useContext as useContext2 } from "react";
1948
+ import { jsx as jsx2 } from "react/jsx-runtime";
1949
+ var AgentContext = createContext2(null);
1950
+ var AgentProvider = ({ config, children, ...options }) => {
1951
+ const agent = useAgent(config, options);
1952
+ return /* @__PURE__ */ jsx2(AgentContext.Provider, { value: agent, children });
1953
+ };
1954
+ var useAgentContext = () => {
1955
+ const ctx = useContext2(AgentContext);
1956
+ if (!ctx) throw new Error("useAgentContext must be used within an <AgentProvider>");
1957
+ return ctx;
1958
+ };
1959
+ var useOptionalAgentContext = () => useContext2(AgentContext);
1960
+
1961
+ // src/components/AgentChat.tsx
1962
+ import { useEffect as useEffect9, useRef as useRef9, useState as useState11 } from "react";
1963
+
1964
+ // src/components/AgentComposer.tsx
1965
+ import { useEffect as useEffect7, useLayoutEffect, useMemo as useMemo5, useRef as useRef7, useState as useState9 } from "react";
1966
+
724
1967
  // src/components/icons.tsx
725
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1968
+ import { jsx as jsx3, jsxs } from "react/jsx-runtime";
726
1969
  var base = (size = 16) => ({
727
1970
  width: size,
728
1971
  height: size,
@@ -735,113 +1978,870 @@ var base = (size = 16) => ({
735
1978
  "aria-hidden": true
736
1979
  });
737
1980
  var SendIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
738
- /* @__PURE__ */ jsx2("path", { d: "M22 2 11 13" }),
739
- /* @__PURE__ */ jsx2("path", { d: "M22 2 15 22l-4-9-9-4Z" })
1981
+ /* @__PURE__ */ jsx3("path", { d: "M22 2 11 13" }),
1982
+ /* @__PURE__ */ jsx3("path", { d: "M22 2 15 22l-4-9-9-4Z" })
740
1983
  ] });
741
- var StopIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2" }) });
742
- var SpinnerIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className: ["awr-spin", className].filter(Boolean).join(" "), children: /* @__PURE__ */ jsx2("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }) });
743
- var CheckIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M20 6 9 17l-5-5" }) });
1984
+ var StopIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2" }) });
1985
+ var SpinnerIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className: ["awr-spin", className].filter(Boolean).join(" "), children: /* @__PURE__ */ jsx3("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }) });
1986
+ var CheckIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("path", { d: "M20 6 9 17l-5-5" }) });
744
1987
  var AlertIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
745
- /* @__PURE__ */ jsx2("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" }),
746
- /* @__PURE__ */ jsx2("path", { d: "M12 9v4" }),
747
- /* @__PURE__ */ jsx2("path", { d: "M12 17h.01" })
1988
+ /* @__PURE__ */ jsx3("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" }),
1989
+ /* @__PURE__ */ jsx3("path", { d: "M12 9v4" }),
1990
+ /* @__PURE__ */ jsx3("path", { d: "M12 17h.01" })
1991
+ ] });
1992
+ var ToolIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("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" }) });
1993
+ var ShieldIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("path", { d: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" }) });
1994
+ var BrainIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
1995
+ /* @__PURE__ */ jsx3("path", { d: "M9 3a3 3 0 0 0-3 3 3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 6 1V4a3 3 0 0 0-3-1Z" }),
1996
+ /* @__PURE__ */ jsx3("path", { d: "M15 3a3 3 0 0 1 3 3 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-6 1" })
1997
+ ] });
1998
+ var BotIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
1999
+ /* @__PURE__ */ jsx3("rect", { x: "4", y: "8", width: "16", height: "12", rx: "3" }),
2000
+ /* @__PURE__ */ jsx3("path", { d: "M12 8V4" }),
2001
+ /* @__PURE__ */ jsx3("path", { d: "M9 14h.01M15 14h.01" })
2002
+ ] });
2003
+ var PlusIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("path", { d: "M12 5v14M5 12h14" }) });
2004
+ var SlashIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
2005
+ /* @__PURE__ */ jsx3("rect", { x: "3", y: "3", width: "18", height: "18", rx: "3" }),
2006
+ /* @__PURE__ */ jsx3("path", { d: "m15 7-6 10" })
748
2007
  ] });
749
- var ToolIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("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" }) });
2008
+ var ClockIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
2009
+ /* @__PURE__ */ jsx3("circle", { cx: "12", cy: "12", r: "9" }),
2010
+ /* @__PURE__ */ jsx3("path", { d: "M12 7v5l3 2" })
2011
+ ] });
2012
+ var MicIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
2013
+ /* @__PURE__ */ jsx3("rect", { x: "9", y: "3", width: "6", height: "11", rx: "3" }),
2014
+ /* @__PURE__ */ jsx3("path", { d: "M5 11a7 7 0 0 0 14 0M12 18v3" })
2015
+ ] });
2016
+ var BoltIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("path", { d: "M13 2 4 14h7l-1 8 9-12h-7Z" }) });
2017
+ var EyeIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
2018
+ /* @__PURE__ */ jsx3("path", { d: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" }),
2019
+ /* @__PURE__ */ jsx3("circle", { cx: "12", cy: "12", r: "3" })
2020
+ ] });
2021
+ var XIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("path", { d: "M18 6 6 18M6 6l12 12" }) });
2022
+ var FileIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
2023
+ /* @__PURE__ */ jsx3("path", { d: "M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z" }),
2024
+ /* @__PURE__ */ jsx3("path", { d: "M14 3v6h6" })
2025
+ ] });
2026
+ var HistoryIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(size), className, children: [
2027
+ /* @__PURE__ */ jsx3("path", { d: "M3 12a9 9 0 1 0 3-6.7L3 8" }),
2028
+ /* @__PURE__ */ jsx3("path", { d: "M3 3v5h5M12 7v5l3 2" })
2029
+ ] });
2030
+ var DownloadIcon = ({ size, className }) => /* @__PURE__ */ jsx3("svg", { ...base(size), className, children: /* @__PURE__ */ jsx3("path", { d: "M12 3v12m-5-5 5 5 5-5M5 21h14" }) });
750
2031
 
751
- // src/components/Composer.tsx
752
- import { useState as useState5 } from "react";
753
- import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
754
- var Composer = ({
755
- onSubmit,
756
- busy = false,
757
- onStop,
2032
+ // src/components/AgentComposer.tsx
2033
+ import { Fragment, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
2034
+ var thinkingDefaults = (l) => [
2035
+ { id: "off", label: l.thinkingLevels.off },
2036
+ { id: "low", label: l.thinkingLevels.low },
2037
+ { id: "medium", label: l.thinkingLevels.medium },
2038
+ { id: "high", label: l.thinkingLevels.high }
2039
+ ];
2040
+ var MODES = ["autopilot", "ask-writes", "ask-all", "read-only"];
2041
+ var ModeIcon = ({ mode }) => mode === "autopilot" ? /* @__PURE__ */ jsx4(BoltIcon, { size: 14 }) : mode === "read-only" ? /* @__PURE__ */ jsx4(EyeIcon, { size: 14 }) : /* @__PURE__ */ jsx4(ShieldIcon, { size: 14 });
2042
+ var attachSeq = 0;
2043
+ var useIsoLayoutEffect = typeof window === "undefined" ? useEffect7 : useLayoutEffect;
2044
+ var useMenuPlacement = (open, anchor, align) => {
2045
+ const [style, setStyle] = useState9();
2046
+ useIsoLayoutEffect(() => {
2047
+ if (!open) return;
2048
+ const place = () => {
2049
+ const el = anchor.current;
2050
+ if (!el) return;
2051
+ const r = el.getBoundingClientRect();
2052
+ const vw = window.innerWidth;
2053
+ const vh = window.innerHeight;
2054
+ const above = r.top - 8;
2055
+ const below = vh - r.bottom - 8;
2056
+ const up = above >= 240 || above >= below;
2057
+ const s = {
2058
+ maxHeight: Math.max(120, (up ? above : below) - 6),
2059
+ top: up ? "auto" : r.bottom + 6,
2060
+ bottom: up ? vh - r.top + 6 : "auto",
2061
+ maxWidth: vw - 16
2062
+ };
2063
+ if (align === "stretch") {
2064
+ s.left = Math.max(8, r.left);
2065
+ s.width = Math.min(r.width, vw - 16);
2066
+ } else if (align === "right") {
2067
+ s.left = "auto";
2068
+ s.right = Math.max(8, vw - r.right);
2069
+ } else {
2070
+ s.left = Math.max(8, Math.min(r.left, vw - 248));
2071
+ }
2072
+ setStyle(s);
2073
+ };
2074
+ place();
2075
+ window.addEventListener("resize", place);
2076
+ window.addEventListener("scroll", place, true);
2077
+ return () => {
2078
+ window.removeEventListener("resize", place);
2079
+ window.removeEventListener("scroll", place, true);
2080
+ };
2081
+ }, [open, anchor, align]);
2082
+ return open ? style : void 0;
2083
+ };
2084
+ var readDataUrl2 = (file) => new Promise((resolve, reject) => {
2085
+ const r = new FileReader();
2086
+ r.onload = () => resolve(String(r.result));
2087
+ r.onerror = () => reject(r.error ?? new Error("could not read the file"));
2088
+ r.readAsDataURL(file);
2089
+ });
2090
+ var safeName = (name) => name.replace(/[^\w.-]+/g, "_").slice(0, 80) || "file";
2091
+ var AgentComposer = ({
2092
+ controller: agent,
2093
+ placeholder,
2094
+ model,
2095
+ thinking,
2096
+ labels: labelsOverride,
2097
+ commands = [],
2098
+ builtinCommands = true,
2099
+ skillCommands = true,
2100
+ attachments = true,
2101
+ convertFile,
2102
+ convert = "when-needed",
2103
+ files: vfs,
2104
+ dropZone = "self",
2105
+ speech = true,
2106
+ showTimer = true,
2107
+ showAgents = true,
2108
+ showApprovalMode = true,
2109
+ showNotices = true,
2110
+ compactWidth = 460,
2111
+ toolbarExtra,
2112
+ toolbarEnd,
2113
+ renderAttachment,
758
2114
  disabled = false,
759
- placeholder = "Ask the agent to do something\u2026",
760
2115
  className
761
2116
  }) => {
762
- const [text, setText] = useState5("");
2117
+ const L = useLabels(labelsOverride);
2118
+ const MODE_CHIP = L.modes;
2119
+ const DEFAULT_THINKING = thinkingDefaults(L);
2120
+ const [text, setText] = useState9("");
2121
+ const [pending, setPending] = useState9([]);
2122
+ const [menu, setMenu] = useState9(void 0);
2123
+ const [active, setActive] = useState9(0);
2124
+ const [dismissed, setDismissed] = useState9(() => /* @__PURE__ */ new Set());
2125
+ const [attachError, setAttachError] = useState9();
2126
+ const [dragging, setDragging] = useState9(false);
2127
+ const rootRef = useRef7(null);
2128
+ const modelRef = useRef7(null);
2129
+ const modeRef = useRef7(null);
2130
+ const [dropRect, setDropRect] = useState9();
2131
+ const [compactBar, setCompactBar] = useState9(false);
2132
+ useEffect7(() => {
2133
+ const el = rootRef.current;
2134
+ if (!el || typeof ResizeObserver === "undefined") return;
2135
+ const ro = new ResizeObserver(
2136
+ () => setCompactBar(el.getBoundingClientRect().width < compactWidth)
2137
+ );
2138
+ ro.observe(el);
2139
+ return () => ro.disconnect();
2140
+ }, [compactWidth]);
2141
+ const fileRef = useRef7(null);
2142
+ const inputRef = useRef7(null);
2143
+ const busy = agent.isRunning;
2144
+ const ready = agent.isReady && !disabled;
2145
+ const caps = agent.agent?.capabilities;
2146
+ const stt = useSpeechToText({
2147
+ lang: typeof speech === "object" ? speech.lang : void 0,
2148
+ onFinal: (heard) => setText((t) => t.trim() ? `${t.trimEnd()} ${heard}` : heard)
2149
+ });
2150
+ const showMic = speech !== false && stt.supported;
2151
+ const [startedAt, setStartedAt] = useState9();
2152
+ const [now, setNow] = useState9(() => Date.now());
2153
+ const [lastElapsed, setLastElapsed] = useState9();
2154
+ useEffect7(() => {
2155
+ if (!busy) {
2156
+ if (startedAt !== void 0) setLastElapsed(Date.now() - startedAt);
2157
+ setStartedAt(void 0);
2158
+ return;
2159
+ }
2160
+ const t0 = Date.now();
2161
+ setStartedAt(t0);
2162
+ setNow(t0);
2163
+ const id = setInterval(() => setNow(Date.now()), 1e3);
2164
+ return () => clearInterval(id);
2165
+ }, [busy]);
2166
+ const elapsed = startedAt !== void 0 ? now - startedAt : lastElapsed;
2167
+ const allCommands = useMemo5(() => {
2168
+ const out = [];
2169
+ if (builtinCommands) {
2170
+ out.push(
2171
+ {
2172
+ name: "compact",
2173
+ description: L.commandDescriptions.compact,
2174
+ group: L.commandGroups.commands,
2175
+ run: () => void agent.compact()
2176
+ },
2177
+ {
2178
+ name: "new",
2179
+ description: L.commandDescriptions.new,
2180
+ group: L.commandGroups.commands,
2181
+ run: agent.reset
2182
+ },
2183
+ {
2184
+ name: "stop",
2185
+ description: L.commandDescriptions.stop,
2186
+ group: L.commandGroups.commands,
2187
+ run: agent.stop
2188
+ },
2189
+ {
2190
+ name: "autopilot",
2191
+ description: L.commandDescriptions.autopilot,
2192
+ group: L.commandGroups.consent,
2193
+ run: () => agent.setApprovalMode("autopilot")
2194
+ },
2195
+ {
2196
+ name: "ask",
2197
+ description: L.commandDescriptions.ask,
2198
+ group: L.commandGroups.consent,
2199
+ run: () => agent.setApprovalMode("ask-writes")
2200
+ },
2201
+ {
2202
+ name: "ask-all",
2203
+ description: L.commandDescriptions.askAll,
2204
+ group: L.commandGroups.consent,
2205
+ run: () => agent.setApprovalMode("ask-all")
2206
+ },
2207
+ {
2208
+ name: "read-only",
2209
+ description: L.commandDescriptions.readOnly,
2210
+ group: L.commandGroups.consent,
2211
+ run: () => agent.setApprovalMode("read-only")
2212
+ }
2213
+ );
2214
+ if (thinking) {
2215
+ const levels = (thinking.options ?? DEFAULT_THINKING).map((o) => o.id);
2216
+ out.push({
2217
+ name: "think",
2218
+ description: L.commandDescriptions.think(levels.join(" | ")),
2219
+ group: L.commandGroups.commands,
2220
+ run: (args) => {
2221
+ const level = args.trim().toLowerCase();
2222
+ if (levels.includes(level)) thinking.onChange(level);
2223
+ }
2224
+ });
2225
+ }
2226
+ }
2227
+ if (skillCommands) {
2228
+ for (const s of agent.agent?.skills ?? []) {
2229
+ out.push({
2230
+ name: s.name,
2231
+ description: s.description,
2232
+ group: L.commandGroups.skills,
2233
+ kind: "prefix",
2234
+ transform: (args) => `Use the "${s.name}" skill. ${args}`.trim()
2235
+ });
2236
+ }
2237
+ }
2238
+ return [...out, ...commands];
2239
+ }, [agent, builtinCommands, skillCommands, commands, thinking, L]);
2240
+ const slash = parseSlash(text);
2241
+ const matches = slash && !/\s/.test(text.trimStart()) ? filterCommands(allCommands, slash.name) : [];
2242
+ const palette = menu === "commands" && !slash ? allCommands : matches;
2243
+ const paletteOpen = palette.length > 0 && (menu === "commands" || matches.length > 0);
2244
+ const commandsStyle = useMenuPlacement(paletteOpen, rootRef, "stretch");
2245
+ const modelStyle = useMenuPlacement(menu === "model", modelRef, "left");
2246
+ const modeStyle = useMenuPlacement(menu === "mode", modeRef, "right");
2247
+ useEffect7(() => setActive(0), [text, menu]);
2248
+ useEffect7(() => {
2249
+ if (!menu) return;
2250
+ const onDown = (e) => {
2251
+ if (!rootRef.current?.contains(e.target)) setMenu(void 0);
2252
+ };
2253
+ document.addEventListener("mousedown", onDown);
2254
+ return () => document.removeEventListener("mousedown", onDown);
2255
+ }, [menu]);
2256
+ const pick = (cmd) => {
2257
+ setMenu(void 0);
2258
+ if (cmd.kind === "prefix") {
2259
+ setText(`/${cmd.name} `);
2260
+ inputRef.current?.focus();
2261
+ return;
2262
+ }
2263
+ const args = parseSlash(text)?.args ?? "";
2264
+ setText("");
2265
+ void cmd.run?.(args);
2266
+ };
2267
+ const attachCfg = typeof attachments === "object" ? attachments : {};
2268
+ const maxBytes = attachCfg.maxBytes ?? 20 * 1024 * 1024;
2269
+ const imageMax = attachCfg.imageMaxDimension ?? 1568;
2270
+ const addFiles = async (list) => {
2271
+ const added = [];
2272
+ let problem;
2273
+ for (const f of list) {
2274
+ const mediaType = f.type || "application/octet-stream";
2275
+ const name = f.name || `pasted-${Date.now()}.${mediaType.split("/")[1] ?? "bin"}`;
2276
+ const kind = attachmentKindOf(mediaType, name);
2277
+ if (f.size > maxBytes) {
2278
+ problem = L.tooLarge(name, Math.round(maxBytes / 1024 / 1024));
2279
+ continue;
2280
+ }
2281
+ try {
2282
+ const id = `att-${attachSeq += 1}`;
2283
+ if (kind === "text") {
2284
+ const content = await f.text();
2285
+ if (content.includes("\0")) {
2286
+ problem = L.binaryText(name);
2287
+ continue;
2288
+ }
2289
+ added.push({ id, name, kind, mediaType, text: content, bytes: f.size });
2290
+ continue;
2291
+ }
2292
+ const refusal = attachmentRefusal(kind, caps);
2293
+ const wantConvert = convertFile && (refusal || kind === "pdf" && convert === "always");
2294
+ if (wantConvert && convertFile) {
2295
+ const converted = await convertFile(f);
2296
+ if (converted) {
2297
+ added.push({
2298
+ id,
2299
+ name: converted.name ?? `${name}.md`,
2300
+ kind: "text",
2301
+ mediaType: "text/markdown",
2302
+ text: converted.text,
2303
+ bytes: converted.text.length,
2304
+ note: `converted from ${name}`
2305
+ });
2306
+ continue;
2307
+ }
2308
+ }
2309
+ if (refusal) {
2310
+ problem = refusal;
2311
+ continue;
2312
+ }
2313
+ const blob = kind === "image" && imageMax !== false ? await downscaleImage(f, {
2314
+ maxDimension: imageMax,
2315
+ maxPixels: attachCfg.imageMaxPixels
2316
+ }) : f;
2317
+ added.push({
2318
+ id,
2319
+ name,
2320
+ kind,
2321
+ mediaType: blob.type || mediaType,
2322
+ dataUrl: await readDataUrl2(blob),
2323
+ bytes: blob.size,
2324
+ ...blob !== f ? { note: `downscaled from ${L.bytes(f.size)}` } : {}
2325
+ });
2326
+ } catch (err) {
2327
+ problem = `${name}: ${err instanceof Error ? err.message : String(err)}`;
2328
+ }
2329
+ }
2330
+ setAttachError(problem);
2331
+ if (added.length) setPending((cur) => [...cur, ...added]);
2332
+ if (fileRef.current) fileRef.current.value = "";
2333
+ };
2334
+ const onPaste = (e) => {
2335
+ if (attachments === false) return;
2336
+ const pasted = Array.from(e.clipboardData?.files ?? []);
2337
+ if (pasted.length === 0) return;
2338
+ e.preventDefault();
2339
+ void addFiles(pasted);
2340
+ };
2341
+ const addFilesRef = useRef7(addFiles);
2342
+ addFilesRef.current = addFiles;
2343
+ useEffect7(() => {
2344
+ if (attachments === false) return;
2345
+ const target = dropZone === "window" ? globalThis.window : dropZone === "self" ? rootRef.current : dropZone.current;
2346
+ if (!target) return;
2347
+ let depth = 0;
2348
+ const hasFiles = (e) => Array.from(e.dataTransfer?.types ?? []).includes("Files");
2349
+ const onEnter = (e) => {
2350
+ if (!hasFiles(e)) return;
2351
+ depth += 1;
2352
+ if (target === globalThis.window) setDropRect({ inset: 0 });
2353
+ else {
2354
+ const r = target.getBoundingClientRect();
2355
+ setDropRect({ left: r.left, top: r.top, width: r.width, height: r.height });
2356
+ }
2357
+ setDragging(true);
2358
+ };
2359
+ const onOver = (e) => {
2360
+ if (hasFiles(e)) e.preventDefault();
2361
+ };
2362
+ const onLeave = () => {
2363
+ depth = Math.max(0, depth - 1);
2364
+ if (depth === 0) setDragging(false);
2365
+ };
2366
+ const onDropFiles = (e) => {
2367
+ const dropped = e.dataTransfer?.files;
2368
+ depth = 0;
2369
+ setDragging(false);
2370
+ if (!dropped?.length) return;
2371
+ e.preventDefault();
2372
+ void addFilesRef.current(Array.from(dropped));
2373
+ };
2374
+ target.addEventListener("dragenter", onEnter);
2375
+ target.addEventListener("dragover", onOver);
2376
+ target.addEventListener("dragleave", onLeave);
2377
+ target.addEventListener("drop", onDropFiles);
2378
+ return () => {
2379
+ target.removeEventListener("dragenter", onEnter);
2380
+ target.removeEventListener("dragover", onOver);
2381
+ target.removeEventListener("dragleave", onLeave);
2382
+ target.removeEventListener("drop", onDropFiles);
2383
+ };
2384
+ }, [attachments, dropZone]);
763
2385
  const submit = () => {
764
- const value = text.trim();
765
- if (!value || busy || disabled) return;
2386
+ const raw = text.trim();
2387
+ if (busy || !ready) return;
2388
+ const parsed = parseSlash(raw);
2389
+ if (parsed) {
2390
+ const cmd = allCommands.find((c) => c.name === parsed.name);
2391
+ if (cmd?.kind !== "prefix") {
2392
+ if (cmd) {
2393
+ setText("");
2394
+ void cmd.run?.(parsed.args);
2395
+ }
2396
+ return;
2397
+ }
2398
+ if (!parsed.args && pending.length === 0) return;
2399
+ void send(cmd.transform ? cmd.transform(parsed.args) : parsed.args, raw);
2400
+ return;
2401
+ }
2402
+ if (!raw && pending.length === 0) return;
2403
+ void send(raw, raw);
2404
+ };
2405
+ const send = async (goal, shown) => {
2406
+ if (stt.listening) stt.stop();
2407
+ const items = pending;
766
2408
  setText("");
767
- onSubmit(value);
2409
+ setPending([]);
2410
+ if (vfs) {
2411
+ for (const a of items) {
2412
+ const path = `/attachments/${safeName(a.name)}`;
2413
+ try {
2414
+ if (a.dataUrl) await vfs.writeDataUrl(path, a.dataUrl);
2415
+ else if (a.text !== void 0) await vfs.write(path, a.text, { mimeType: a.mediaType });
2416
+ a.path = path;
2417
+ } catch {
2418
+ }
2419
+ }
2420
+ }
2421
+ const toModel = (a) => ({
2422
+ data: a.dataUrl,
2423
+ mediaType: a.mediaType,
2424
+ name: a.name
2425
+ });
2426
+ const shownAttachments = items.map((a) => ({
2427
+ name: a.name,
2428
+ mediaType: a.mediaType,
2429
+ size: a.bytes,
2430
+ ...a.kind === "image" && a.dataUrl ? { dataUrl: a.dataUrl } : {},
2431
+ ...a.path ? { path: a.path } : {}
2432
+ }));
2433
+ const full = withAttachments(goal || L.seeAttachments, items);
2434
+ const label = shown || (items.length ? L.attachmentsOnly : "");
2435
+ void agent.run(full, {
2436
+ ...full !== label ? { label } : {},
2437
+ images: items.filter((a) => a.kind === "image" && a.dataUrl).map(toModel),
2438
+ files: items.filter((a) => (a.kind === "pdf" || a.kind === "file") && a.dataUrl).map(toModel),
2439
+ attachments: shownAttachments
2440
+ });
768
2441
  };
769
2442
  const onKeyDown = (e) => {
2443
+ if (paletteOpen) {
2444
+ if (e.key === "ArrowDown") {
2445
+ e.preventDefault();
2446
+ setActive((i) => (i + 1) % palette.length);
2447
+ return;
2448
+ }
2449
+ if (e.key === "ArrowUp") {
2450
+ e.preventDefault();
2451
+ setActive((i) => (i - 1 + palette.length) % palette.length);
2452
+ return;
2453
+ }
2454
+ if (e.key === "Tab" || e.key === "Enter" && !e.shiftKey && matches.length > 0) {
2455
+ e.preventDefault();
2456
+ pick(palette[active] ?? palette[0]);
2457
+ return;
2458
+ }
2459
+ if (e.key === "Escape") {
2460
+ setMenu(void 0);
2461
+ setText("");
2462
+ return;
2463
+ }
2464
+ }
770
2465
  if (e.key === "Enter" && !e.shiftKey) {
771
2466
  e.preventDefault();
772
2467
  submit();
773
2468
  }
774
2469
  };
2470
+ const notices = showNotices ? [
2471
+ ...noticesOf(agent, L.notices),
2472
+ ...attachError ? [{ id: `attach:${attachError}`, tone: "warn", text: attachError }] : [],
2473
+ ...stt.error ? [
2474
+ {
2475
+ id: `stt:${stt.error}`,
2476
+ tone: "warn",
2477
+ text: `${L.microphone}: ${stt.error}`
2478
+ }
2479
+ ] : []
2480
+ ].filter((n) => !dismissed.has(n.id)) : [];
2481
+ const runningAgents = agent.subagents.filter((s) => s.status === "running");
2482
+ const thinkingOptions = thinking?.options ?? DEFAULT_THINKING;
2483
+ const thinkingLabel = thinking ? thinkingOptions.find((o) => o.id === thinking.value)?.label ?? thinking.value : void 0;
2484
+ const canSend = ready && (text.trim().length > 0 || pending.length > 0);
775
2485
  return /* @__PURE__ */ jsxs2(
776
- "form",
2486
+ "div",
777
2487
  {
778
- className: ["awr-composer", className].filter(Boolean).join(" "),
779
- onSubmit: (e) => {
780
- e.preventDefault();
781
- submit();
782
- },
2488
+ className: [
2489
+ "awr-composer2",
2490
+ dragging ? "is-dragging" : "",
2491
+ compactBar ? "awr-composer2--compact" : "",
2492
+ className
2493
+ ].filter(Boolean).join(" "),
2494
+ ref: rootRef,
783
2495
  children: [
784
- /* @__PURE__ */ jsx3(
785
- "textarea",
786
- {
787
- className: "awr-composer__input",
788
- value: text,
789
- onChange: (e) => setText(e.target.value),
790
- onKeyDown,
791
- placeholder,
792
- disabled,
793
- rows: 1
794
- }
795
- ),
796
- busy ? /* @__PURE__ */ jsx3(
797
- "button",
798
- {
799
- type: "button",
800
- className: "awr-composer__btn awr-composer__btn--stop",
801
- onClick: onStop,
802
- "aria-label": "Stop",
803
- children: /* @__PURE__ */ jsx3(StopIcon, { size: 18 })
804
- }
805
- ) : /* @__PURE__ */ jsx3(
806
- "button",
807
- {
808
- type: "submit",
809
- className: "awr-composer__btn",
810
- disabled: disabled || !text.trim(),
811
- "aria-label": "Send",
812
- children: disabled ? /* @__PURE__ */ jsx3(SpinnerIcon, { size: 18 }) : /* @__PURE__ */ jsx3(SendIcon, { size: 18 })
2496
+ dragging && /* @__PURE__ */ jsx4("div", { className: "awr-dropnote", style: dropRect, "aria-hidden": "true", children: L.dropHint }),
2497
+ notices.length > 0 && /* @__PURE__ */ jsx4("div", { className: "awr-notices", children: notices.map((n) => /* @__PURE__ */ jsxs2("div", { className: `awr-notice awr-notice--${n.tone}`, role: "status", children: [
2498
+ /* @__PURE__ */ jsx4("span", { children: n.text }),
2499
+ /* @__PURE__ */ jsx4(
2500
+ "button",
2501
+ {
2502
+ type: "button",
2503
+ className: "awr-iconbtn",
2504
+ "aria-label": L.dismiss,
2505
+ onClick: () => {
2506
+ setDismissed((d) => new Set(d).add(n.id));
2507
+ if (n.id.startsWith("attach:")) setAttachError(void 0);
2508
+ },
2509
+ children: /* @__PURE__ */ jsx4(XIcon, { size: 14 })
2510
+ }
2511
+ )
2512
+ ] }, n.id)) }),
2513
+ paletteOpen && /* @__PURE__ */ jsx4(
2514
+ "ul",
2515
+ {
2516
+ className: "awr-menu awr-menu--commands",
2517
+ style: commandsStyle,
2518
+ role: "listbox",
2519
+ "aria-label": L.commands,
2520
+ children: palette.map((c, i) => /* @__PURE__ */ jsx4("li", { children: /* @__PURE__ */ jsxs2(
2521
+ "button",
2522
+ {
2523
+ type: "button",
2524
+ role: "option",
2525
+ "aria-selected": i === active,
2526
+ className: `awr-menu__item${i === active ? " is-active" : ""}`,
2527
+ onMouseDown: (e) => e.preventDefault(),
2528
+ onClick: () => pick(c),
2529
+ children: [
2530
+ /* @__PURE__ */ jsxs2("code", { children: [
2531
+ "/",
2532
+ c.name
2533
+ ] }),
2534
+ /* @__PURE__ */ jsx4("span", { className: "awr-menu__desc", children: c.description }),
2535
+ c.group && /* @__PURE__ */ jsx4("span", { className: "awr-menu__group", children: c.group })
2536
+ ]
2537
+ }
2538
+ ) }, `${c.group}:${c.name}`))
813
2539
  }
814
- )
2540
+ ),
2541
+ pending.length > 0 && /* @__PURE__ */ jsx4("div", { className: "awr-files", children: pending.map((a) => {
2542
+ const remove = () => setPending((cur) => cur.filter((x) => x.id !== a.id));
2543
+ if (renderAttachment) return /* @__PURE__ */ jsx4("span", { children: renderAttachment(a, remove) }, a.id);
2544
+ return /* @__PURE__ */ jsxs2("span", { className: "awr-chip awr-file", title: a.note ?? a.mediaType, children: [
2545
+ a.kind === "image" && a.dataUrl ? /* @__PURE__ */ jsx4("img", { className: "awr-file__thumb", src: a.dataUrl, alt: a.name }) : /* @__PURE__ */ jsx4(FileIcon, { size: 14 }),
2546
+ /* @__PURE__ */ jsx4("span", { className: "awr-file__name", children: a.name }),
2547
+ /* @__PURE__ */ jsx4(
2548
+ "button",
2549
+ {
2550
+ type: "button",
2551
+ className: "awr-iconbtn",
2552
+ "aria-label": L.remove(a.name),
2553
+ onClick: remove,
2554
+ children: /* @__PURE__ */ jsx4(XIcon, { size: 12 })
2555
+ }
2556
+ )
2557
+ ] }, a.id);
2558
+ }) }),
2559
+ /* @__PURE__ */ jsxs2("div", { className: "awr-composer2__inputrow", children: [
2560
+ /* @__PURE__ */ jsx4(
2561
+ "textarea",
2562
+ {
2563
+ ref: inputRef,
2564
+ className: "awr-composer2__input",
2565
+ value: text,
2566
+ onChange: (e) => setText(e.target.value),
2567
+ onKeyDown,
2568
+ onPaste,
2569
+ placeholder: stt.listening ? L.listening : placeholder ?? L.placeholder,
2570
+ disabled,
2571
+ rows: 2,
2572
+ "aria-label": L.message
2573
+ }
2574
+ ),
2575
+ showMic && /* @__PURE__ */ jsx4(
2576
+ "button",
2577
+ {
2578
+ type: "button",
2579
+ className: `awr-iconbtn awr-mic${stt.listening ? " is-on" : ""}`,
2580
+ "aria-label": stt.listening ? L.stopDictation : L.dictate,
2581
+ title: stt.listening ? L.stopDictation : L.dictateTitle,
2582
+ onClick: stt.toggle,
2583
+ disabled,
2584
+ children: /* @__PURE__ */ jsx4(MicIcon, { size: 18 })
2585
+ }
2586
+ )
2587
+ ] }),
2588
+ stt.listening && stt.interim && /* @__PURE__ */ jsx4("div", { className: "awr-composer2__interim", children: stt.interim }),
2589
+ /* @__PURE__ */ jsxs2("div", { className: "awr-toolbar", children: [
2590
+ attachments !== false && /* @__PURE__ */ jsxs2(Fragment, { children: [
2591
+ /* @__PURE__ */ jsx4(
2592
+ "button",
2593
+ {
2594
+ type: "button",
2595
+ className: "awr-iconbtn",
2596
+ "aria-label": L.attach,
2597
+ title: L.attachTitle,
2598
+ onClick: () => fileRef.current?.click(),
2599
+ disabled,
2600
+ children: /* @__PURE__ */ jsx4(PlusIcon, { size: 18 })
2601
+ }
2602
+ ),
2603
+ /* @__PURE__ */ jsx4(
2604
+ "input",
2605
+ {
2606
+ ref: fileRef,
2607
+ type: "file",
2608
+ multiple: true,
2609
+ hidden: true,
2610
+ accept: attachCfg.accept,
2611
+ onChange: (e) => void addFiles(Array.from(e.target.files ?? []))
2612
+ }
2613
+ )
2614
+ ] }),
2615
+ /* @__PURE__ */ jsx4(
2616
+ "button",
2617
+ {
2618
+ type: "button",
2619
+ className: `awr-iconbtn${menu === "commands" ? " is-on" : ""}`,
2620
+ "aria-label": L.commands,
2621
+ title: L.commandsTitle,
2622
+ onClick: () => setMenu(menu === "commands" ? void 0 : "commands"),
2623
+ children: /* @__PURE__ */ jsx4(SlashIcon, { size: 18 })
2624
+ }
2625
+ ),
2626
+ toolbarExtra,
2627
+ showTimer && elapsed !== void 0 && /* @__PURE__ */ jsxs2("span", { className: "awr-tchip", title: busy ? L.timerRunning : L.timerLast, children: [
2628
+ /* @__PURE__ */ jsx4(ClockIcon, { size: 14 }),
2629
+ " ",
2630
+ formatElapsed(elapsed)
2631
+ ] }),
2632
+ showAgents && /* @__PURE__ */ jsxs2(
2633
+ "span",
2634
+ {
2635
+ className: `awr-tchip awr-agents${runningAgents.length ? " is-busy" : ""}`,
2636
+ title: agent.subagents.length ? agent.subagents.map((s) => `${s.name} (${s.status}): ${s.task}`).join("\n") : L.agentsTitle,
2637
+ children: [
2638
+ /* @__PURE__ */ jsx4("span", { className: "awr-agents__dot", "aria-hidden": "true" }),
2639
+ /* @__PURE__ */ jsx4(BotIcon, { size: 14 }),
2640
+ " ",
2641
+ compactBar ? runningAgents.length : L.agents(runningAgents.length)
2642
+ ]
2643
+ }
2644
+ ),
2645
+ (model || thinking) && /* @__PURE__ */ jsxs2("span", { className: "awr-popwrap awr-popwrap--model", ref: modelRef, children: [
2646
+ /* @__PURE__ */ jsxs2(
2647
+ "button",
2648
+ {
2649
+ type: "button",
2650
+ className: "awr-tchip awr-tchip--btn",
2651
+ onClick: () => setMenu(menu === "model" ? void 0 : "model"),
2652
+ "aria-haspopup": "menu",
2653
+ "aria-expanded": menu === "model",
2654
+ title: [model?.label, thinkingLabel].filter(Boolean).join(" \xB7 "),
2655
+ children: [
2656
+ /* @__PURE__ */ jsx4("span", { className: "awr-tchip__label", children: model?.label ?? L.model }),
2657
+ thinkingLabel && !compactBar && /* @__PURE__ */ jsx4("span", { className: "awr-tchip__sub", children: thinkingLabel })
2658
+ ]
2659
+ }
2660
+ ),
2661
+ menu === "model" && /* @__PURE__ */ jsxs2("div", { className: "awr-menu awr-menu--pop", style: modelStyle, role: "menu", children: [
2662
+ thinking && /* @__PURE__ */ jsxs2(Fragment, { children: [
2663
+ /* @__PURE__ */ jsx4("div", { className: "awr-menu__head", children: L.thinking }),
2664
+ thinkingOptions.map((o) => /* @__PURE__ */ jsx4(
2665
+ "button",
2666
+ {
2667
+ type: "button",
2668
+ role: "menuitemradio",
2669
+ "aria-checked": thinking.value === o.id,
2670
+ className: `awr-menu__item${thinking.value === o.id ? " is-active" : ""}`,
2671
+ onClick: () => {
2672
+ thinking.onChange(o.id);
2673
+ setMenu(void 0);
2674
+ },
2675
+ children: o.label
2676
+ },
2677
+ o.id
2678
+ ))
2679
+ ] }),
2680
+ model?.options?.length ? /* @__PURE__ */ jsxs2(Fragment, { children: [
2681
+ /* @__PURE__ */ jsx4("div", { className: "awr-menu__head", children: L.model }),
2682
+ model.options.map((o) => /* @__PURE__ */ jsxs2(
2683
+ "button",
2684
+ {
2685
+ type: "button",
2686
+ role: "menuitemradio",
2687
+ "aria-checked": model.value === o.id,
2688
+ className: `awr-menu__item${model.value === o.id ? " is-active" : ""}`,
2689
+ onClick: () => {
2690
+ model.onSelect?.(o.id);
2691
+ setMenu(void 0);
2692
+ },
2693
+ children: [
2694
+ o.label,
2695
+ o.group && /* @__PURE__ */ jsx4("span", { className: "awr-menu__group", children: o.group })
2696
+ ]
2697
+ },
2698
+ o.id
2699
+ ))
2700
+ ] }) : null
2701
+ ] })
2702
+ ] }),
2703
+ /* @__PURE__ */ jsx4("span", { className: "awr-toolbar__spacer" }),
2704
+ toolbarEnd,
2705
+ showApprovalMode && /* @__PURE__ */ jsxs2("span", { className: "awr-popwrap", ref: modeRef, children: [
2706
+ /* @__PURE__ */ jsxs2(
2707
+ "button",
2708
+ {
2709
+ type: "button",
2710
+ className: `awr-tchip awr-tchip--btn awr-mode awr-mode--${agent.approvalMode}`,
2711
+ title: MODE_CHIP[agent.approvalMode].hint,
2712
+ onClick: () => setMenu(menu === "mode" ? void 0 : "mode"),
2713
+ "aria-haspopup": "menu",
2714
+ "aria-expanded": menu === "mode",
2715
+ "aria-label": `${L.toolConsent}: ${MODE_CHIP[agent.approvalMode].label}`,
2716
+ children: [
2717
+ /* @__PURE__ */ jsx4(ModeIcon, { mode: agent.approvalMode }),
2718
+ !compactBar && ` ${MODE_CHIP[agent.approvalMode].label}`
2719
+ ]
2720
+ }
2721
+ ),
2722
+ menu === "mode" && /* @__PURE__ */ jsxs2("div", { className: "awr-menu awr-menu--pop", style: modeStyle, role: "menu", children: [
2723
+ /* @__PURE__ */ jsx4("div", { className: "awr-menu__head", children: L.toolConsent }),
2724
+ MODES.map((m) => /* @__PURE__ */ jsxs2(
2725
+ "button",
2726
+ {
2727
+ type: "button",
2728
+ role: "menuitemradio",
2729
+ "aria-checked": agent.approvalMode === m,
2730
+ className: `awr-menu__item${agent.approvalMode === m ? " is-active" : ""}`,
2731
+ onClick: () => {
2732
+ agent.setApprovalMode(m);
2733
+ setMenu(void 0);
2734
+ },
2735
+ children: [
2736
+ /* @__PURE__ */ jsx4(ModeIcon, { mode: m }),
2737
+ " ",
2738
+ MODE_CHIP[m].label,
2739
+ /* @__PURE__ */ jsx4("span", { className: "awr-menu__desc", children: MODE_CHIP[m].hint })
2740
+ ]
2741
+ },
2742
+ m
2743
+ ))
2744
+ ] })
2745
+ ] }),
2746
+ busy ? /* @__PURE__ */ jsx4(
2747
+ "button",
2748
+ {
2749
+ type: "button",
2750
+ className: "awr-sendbtn awr-sendbtn--stop",
2751
+ onClick: agent.stop,
2752
+ "aria-label": L.stop,
2753
+ children: /* @__PURE__ */ jsx4(StopIcon, { size: 16 })
2754
+ }
2755
+ ) : /* @__PURE__ */ jsx4(
2756
+ "button",
2757
+ {
2758
+ type: "button",
2759
+ className: "awr-sendbtn",
2760
+ onClick: submit,
2761
+ disabled: !canSend,
2762
+ "aria-label": L.send,
2763
+ children: agent.status === "initializing" ? /* @__PURE__ */ jsx4(SpinnerIcon, { size: 16 }) : /* @__PURE__ */ jsx4(SendIcon, { size: 16 })
2764
+ }
2765
+ )
2766
+ ] })
815
2767
  ]
816
2768
  }
817
2769
  );
818
2770
  };
819
2771
 
820
- // src/components/MessageList.tsx
821
- import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
822
- var MessageList = ({ messages, empty, className }) => {
823
- if (messages.length === 0) {
824
- return empty ? /* @__PURE__ */ jsx4("div", { className: "awr-messages__empty", children: empty }) : null;
825
- }
826
- return /* @__PURE__ */ jsx4("div", { className: ["awr-messages", className].filter(Boolean).join(" "), children: messages.map((m) => /* @__PURE__ */ jsx4("div", { className: `awr-msg awr-msg--${m.role}`, children: /* @__PURE__ */ jsxs3("div", { className: "awr-msg__bubble", children: [
827
- m.content,
828
- m.pending && !m.content && /* @__PURE__ */ jsx4(SpinnerIcon, { size: 14, className: "awr-msg__pending" })
829
- ] }) }, m.id)) });
2772
+ // src/components/ChatHistoryList.tsx
2773
+ import { Fragment as Fragment2 } from "react";
2774
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
2775
+ var defaultTime = (ms) => {
2776
+ const d = new Date(ms);
2777
+ const today = (/* @__PURE__ */ new Date()).toDateString() === d.toDateString();
2778
+ return today ? d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : d.toLocaleDateString();
830
2779
  };
831
-
832
- // src/components/ModelLoadBar.tsx
833
- import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
834
- var ModelLoadBar = ({ load, className }) => {
835
- const pct = Math.round(Math.max(0, Math.min(1, load.progress)) * 100);
836
- return /* @__PURE__ */ jsxs4("div", { className: ["awr-modelload", className].filter(Boolean).join(" "), children: [
837
- /* @__PURE__ */ jsxs4("div", { className: "awr-modelload__head", children: [
838
- /* @__PURE__ */ jsx5("span", { className: "awr-modelload__text", children: load.text || "Loading model\u2026" }),
839
- /* @__PURE__ */ jsxs4("span", { className: "awr-modelload__pct", children: [
840
- pct,
841
- "%"
842
- ] })
2780
+ var ChatHistoryList = ({
2781
+ history,
2782
+ title,
2783
+ disabled,
2784
+ renderChat,
2785
+ formatTime = defaultTime,
2786
+ labels,
2787
+ className
2788
+ }) => {
2789
+ const L = useLabels(labels);
2790
+ return /* @__PURE__ */ jsxs3("div", { className: ["awr-history", className].filter(Boolean).join(" "), children: [
2791
+ /* @__PURE__ */ jsxs3("div", { className: "awr-panel__head", children: [
2792
+ /* @__PURE__ */ jsx5("span", { className: "awr-panel__title", children: title ?? L.history }),
2793
+ /* @__PURE__ */ jsxs3(
2794
+ "button",
2795
+ {
2796
+ type: "button",
2797
+ className: "awr-btn awr-btn--ghost awr-history__new",
2798
+ onClick: history.newChat,
2799
+ disabled,
2800
+ children: [
2801
+ /* @__PURE__ */ jsx5(PlusIcon, { size: 14 }),
2802
+ " ",
2803
+ L.newChat
2804
+ ]
2805
+ }
2806
+ )
843
2807
  ] }),
844
- /* @__PURE__ */ jsx5("div", { className: "awr-modelload__track", role: "progressbar", "aria-valuenow": pct, children: /* @__PURE__ */ jsx5("div", { className: "awr-modelload__fill", style: { width: `${pct}%` } }) })
2808
+ !history.loading && history.chats.length === 0 && /* @__PURE__ */ jsx5("div", { className: "awr-panel__empty", children: L.historyEmpty }),
2809
+ /* @__PURE__ */ jsx5("ul", { className: "awr-history__list", children: history.chats.map((c) => {
2810
+ const active = c.id === history.currentId;
2811
+ const row = /* @__PURE__ */ jsxs3("li", { className: `awr-history__item${active ? " is-active" : ""}`, children: [
2812
+ /* @__PURE__ */ jsxs3(
2813
+ "button",
2814
+ {
2815
+ type: "button",
2816
+ className: "awr-history__open",
2817
+ onClick: () => void history.select(c.id),
2818
+ disabled: disabled || active,
2819
+ "aria-current": active ? "true" : void 0,
2820
+ children: [
2821
+ /* @__PURE__ */ jsx5("span", { className: "awr-history__title", children: c.title }),
2822
+ /* @__PURE__ */ jsxs3("span", { className: "awr-history__meta", children: [
2823
+ formatTime(c.updatedAt),
2824
+ " \xB7 ",
2825
+ L.messagesCount(c.messageCount)
2826
+ ] })
2827
+ ]
2828
+ }
2829
+ ),
2830
+ /* @__PURE__ */ jsx5(
2831
+ "button",
2832
+ {
2833
+ type: "button",
2834
+ className: "awr-iconbtn",
2835
+ "aria-label": `${L.deleteChat}: ${c.title}`,
2836
+ title: L.deleteChat,
2837
+ onClick: () => void history.remove(c.id),
2838
+ disabled,
2839
+ children: /* @__PURE__ */ jsx5(XIcon, { size: 14 })
2840
+ }
2841
+ )
2842
+ ] }, c.id);
2843
+ return renderChat ? /* @__PURE__ */ jsx5(Fragment2, { children: renderChat(c, active, row) }, c.id) : row;
2844
+ }) })
845
2845
  ] });
846
2846
  };
847
2847
 
@@ -860,79 +2860,571 @@ var previewValue = (value, max = 140) => {
860
2860
  text = text.replace(/\s+/g, " ").trim();
861
2861
  return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
862
2862
  };
2863
+ var formatTokens = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
2864
+ var formatDuration = (ms) => {
2865
+ if (ms < 1e3) return `${Math.round(ms)} ms`;
2866
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(ms < 1e4 ? 1 : 0)} s`;
2867
+ const s = Math.round(ms / 1e3);
2868
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
2869
+ };
2870
+ var isDataImage = (v) => typeof v === "string" && /^data:image\/[\w.+-]+;base64,/.test(v);
2871
+ var imagesInOutput = (output, depth = 0) => {
2872
+ if (depth > 2 || output == null) return [];
2873
+ if (isDataImage(output)) return [output];
2874
+ if (Array.isArray(output)) return output.flatMap((v) => imagesInOutput(v, depth + 1));
2875
+ if (typeof output === "object") {
2876
+ const o = output;
2877
+ if (o.type === "image" && typeof o.data === "string") {
2878
+ const mime = typeof o.mimeType === "string" ? o.mimeType : "image/png";
2879
+ return [o.data.startsWith("data:") ? o.data : `data:${mime};base64,${o.data}`];
2880
+ }
2881
+ for (const key of ["dataUrl", "url", "image"])
2882
+ if (isDataImage(o[key])) return [o[key]];
2883
+ if (depth < 2) return Object.values(o).flatMap((v) => imagesInOutput(v, depth + 1));
2884
+ }
2885
+ return [];
2886
+ };
2887
+
2888
+ // src/components/ContextMeter.tsx
2889
+ import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
2890
+ var ContextMeter = ({
2891
+ usage,
2892
+ budgetTokens,
2893
+ budget,
2894
+ compactions = [],
2895
+ onCompact,
2896
+ compacting,
2897
+ className
2898
+ }) => {
2899
+ const cached = usage.cachedInputTokens ?? 0;
2900
+ const reasoning = usage.reasoningTokens ?? 0;
2901
+ if (usage.totalTokens === 0 && !budget && compactions.length === 0 && !budgetTokens) {
2902
+ return null;
2903
+ }
2904
+ const hitRate = usage.inputTokens > 0 ? Math.round(cached / usage.inputTokens * 100) : 0;
2905
+ const fill = budgetTokens ? Math.min(1, usage.totalTokens / budgetTokens) : void 0;
2906
+ const last = compactions.at(-1);
2907
+ return /* @__PURE__ */ jsxs4("div", { className: ["awr-context", className].filter(Boolean).join(" "), children: [
2908
+ /* @__PURE__ */ jsxs4("div", { className: "awr-context__row", children: [
2909
+ /* @__PURE__ */ jsxs4("span", { title: "input tokens", children: [
2910
+ "in ",
2911
+ formatTokens(usage.inputTokens)
2912
+ ] }),
2913
+ /* @__PURE__ */ jsxs4("span", { title: "output tokens", children: [
2914
+ "out ",
2915
+ formatTokens(usage.outputTokens)
2916
+ ] }),
2917
+ reasoning > 0 && /* @__PURE__ */ jsxs4("span", { title: "thinking tokens", children: [
2918
+ "think ",
2919
+ formatTokens(reasoning)
2920
+ ] }),
2921
+ /* @__PURE__ */ jsxs4("span", { title: "input tokens served from the provider's prompt cache", children: [
2922
+ "cached ",
2923
+ formatTokens(cached),
2924
+ hitRate > 0 ? ` (${hitRate}%)` : ""
2925
+ ] }),
2926
+ onCompact && /* @__PURE__ */ jsx6(
2927
+ "button",
2928
+ {
2929
+ type: "button",
2930
+ className: "awr-btn awr-btn--ghost awr-context__compact",
2931
+ onClick: onCompact,
2932
+ disabled: compacting,
2933
+ children: compacting ? "Compacting\u2026" : "Compact"
2934
+ }
2935
+ )
2936
+ ] }),
2937
+ fill !== void 0 && /* @__PURE__ */ jsx6(
2938
+ "div",
2939
+ {
2940
+ className: `awr-context__track${fill >= 1 ? " is-full" : ""}`,
2941
+ title: `${usage.totalTokens} / ${budgetTokens} tokens`,
2942
+ children: /* @__PURE__ */ jsx6("div", { className: "awr-context__fill", style: { width: `${fill * 100}%` } })
2943
+ }
2944
+ ),
2945
+ budget && /* @__PURE__ */ jsxs4("div", { className: "awr-context__note awr-context__note--warn", children: [
2946
+ budget.kind === "tool-calls" ? "Tool-call" : `${budget.kind} token`,
2947
+ " limit reached (",
2948
+ budget.tokens,
2949
+ "/",
2950
+ budget.cap,
2951
+ ") \u2014 the agent stopped early."
2952
+ ] }),
2953
+ last && /* @__PURE__ */ jsxs4("div", { className: "awr-context__note", children: [
2954
+ "Compacted ",
2955
+ last.scope,
2956
+ ": ",
2957
+ formatTokens(last.beforeTokens),
2958
+ " \u2192",
2959
+ " ",
2960
+ formatTokens(last.afterTokens),
2961
+ " tokens"
2962
+ ] })
2963
+ ] });
2964
+ };
2965
+
2966
+ // src/components/FilesPanel.tsx
2967
+ import { Fragment as Fragment3, useEffect as useEffect8, useRef as useRef8, useState as useState10 } from "react";
2968
+ import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
2969
+ var PREVIEW_CHARS = 2e4;
2970
+ var FilesPanel = ({
2971
+ files: vfs,
2972
+ prefix = "/",
2973
+ title,
2974
+ allowUpload = true,
2975
+ allowDelete = true,
2976
+ uploadDir,
2977
+ onOpen,
2978
+ renderFile,
2979
+ labels,
2980
+ className
2981
+ }) => {
2982
+ const L = useLabels(labels);
2983
+ const fs = useVirtualFiles(vfs, prefix);
2984
+ const [preview, setPreview] = useState10();
2985
+ const inputRef = useRef8(null);
2986
+ useEffect8(() => {
2987
+ if (preview && !fs.files.some((f) => f.path === preview.path)) setPreview(void 0);
2988
+ }, [fs.files, preview]);
2989
+ const open = async (f) => {
2990
+ onOpen?.(f);
2991
+ if (preview?.path === f.path) return setPreview(void 0);
2992
+ if (f.mimeType.startsWith("image/")) {
2993
+ const src = await fs.dataUrl(f.path);
2994
+ if (src) setPreview({ path: f.path, kind: "image", src });
2995
+ return;
2996
+ }
2997
+ const text = await fs.text(f.path);
2998
+ if (text !== void 0) setPreview({ path: f.path, kind: "text", text });
2999
+ else setPreview(void 0);
3000
+ };
3001
+ const download = async (f) => {
3002
+ const href = await fs.dataUrl(f.path);
3003
+ if (!href) return;
3004
+ const a = document.createElement("a");
3005
+ a.href = href;
3006
+ a.download = f.path.split("/").pop() || "file";
3007
+ a.click();
3008
+ };
3009
+ return /* @__PURE__ */ jsxs5("div", { className: ["awr-filespanel", className].filter(Boolean).join(" "), children: [
3010
+ /* @__PURE__ */ jsxs5("div", { className: "awr-panel__head", children: [
3011
+ /* @__PURE__ */ jsx7("span", { className: "awr-panel__title", children: title ?? L.files }),
3012
+ allowUpload && /* @__PURE__ */ jsxs5(Fragment4, { children: [
3013
+ /* @__PURE__ */ jsx7(
3014
+ "button",
3015
+ {
3016
+ type: "button",
3017
+ className: "awr-iconbtn",
3018
+ "aria-label": L.upload,
3019
+ title: L.upload,
3020
+ onClick: () => inputRef.current?.click(),
3021
+ children: /* @__PURE__ */ jsx7(PlusIcon, { size: 16 })
3022
+ }
3023
+ ),
3024
+ /* @__PURE__ */ jsx7(
3025
+ "input",
3026
+ {
3027
+ ref: inputRef,
3028
+ type: "file",
3029
+ multiple: true,
3030
+ hidden: true,
3031
+ onChange: async (e) => {
3032
+ for (const f of Array.from(e.target.files ?? [])) await fs.upload(f, uploadDir);
3033
+ e.target.value = "";
3034
+ }
3035
+ }
3036
+ )
3037
+ ] })
3038
+ ] }),
3039
+ fs.error && /* @__PURE__ */ jsx7("div", { className: "awr-notice awr-notice--warn", children: fs.error }),
3040
+ !fs.loading && fs.files.length === 0 && /* @__PURE__ */ jsx7("div", { className: "awr-panel__empty", children: L.filesEmpty }),
3041
+ /* @__PURE__ */ jsx7("ul", { className: "awr-filelist", children: fs.files.map((f) => {
3042
+ const row = /* @__PURE__ */ jsxs5(
3043
+ "li",
3044
+ {
3045
+ className: `awr-filelist__item${preview?.path === f.path ? " is-active" : ""}`,
3046
+ children: [
3047
+ /* @__PURE__ */ jsxs5(
3048
+ "button",
3049
+ {
3050
+ type: "button",
3051
+ className: "awr-filelist__open",
3052
+ onClick: () => void open(f),
3053
+ title: `${L.preview}: ${f.path}`,
3054
+ children: [
3055
+ /* @__PURE__ */ jsx7(FileIcon, { size: 14 }),
3056
+ /* @__PURE__ */ jsx7("span", { className: "awr-filelist__path", children: f.path }),
3057
+ /* @__PURE__ */ jsx7("span", { className: "awr-filelist__size", children: L.bytes(f.size) })
3058
+ ]
3059
+ }
3060
+ ),
3061
+ /* @__PURE__ */ jsx7(
3062
+ "button",
3063
+ {
3064
+ type: "button",
3065
+ className: "awr-iconbtn",
3066
+ "aria-label": `${L.download} ${f.path}`,
3067
+ title: L.download,
3068
+ onClick: () => void download(f),
3069
+ children: /* @__PURE__ */ jsx7(DownloadIcon, { size: 14 })
3070
+ }
3071
+ ),
3072
+ allowDelete && /* @__PURE__ */ jsx7(
3073
+ "button",
3074
+ {
3075
+ type: "button",
3076
+ className: "awr-iconbtn",
3077
+ "aria-label": `${L.delete} ${f.path}`,
3078
+ title: L.delete,
3079
+ onClick: () => void fs.remove(f.path),
3080
+ children: /* @__PURE__ */ jsx7(XIcon, { size: 14 })
3081
+ }
3082
+ )
3083
+ ]
3084
+ },
3085
+ f.path
3086
+ );
3087
+ return renderFile ? /* @__PURE__ */ jsx7(Fragment3, { children: renderFile(f, row) }, f.path) : row;
3088
+ }) }),
3089
+ preview && /* @__PURE__ */ jsx7("div", { className: "awr-filepreview", children: preview.kind === "image" ? /* @__PURE__ */ jsx7("img", { src: preview.src, alt: preview.path }) : /* @__PURE__ */ jsx7("pre", { children: preview.text.length > PREVIEW_CHARS ? `${preview.text.slice(0, PREVIEW_CHARS)}
3090
+ \u2026` : preview.text }) })
3091
+ ] });
3092
+ };
863
3093
 
864
3094
  // src/components/StepList.tsx
865
- import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
866
- var ToolCallRow = ({ call }) => {
3095
+ import { Fragment as Fragment5 } from "react";
3096
+ import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
3097
+ var ToolCallRow = ({ call, showUsage = true, labels }) => {
3098
+ const L = useLabels(labels);
867
3099
  const state = call.status === "calling" ? "calling" : call.ok === false ? "failed" : "ok";
868
- return /* @__PURE__ */ jsxs5("li", { className: `awr-tool awr-tool--${state}`, children: [
869
- /* @__PURE__ */ jsx6(ToolIcon, { size: 13, className: "awr-tool__icon" }),
870
- /* @__PURE__ */ jsx6("code", { className: "awr-tool__name", children: call.name }),
871
- previewValue(call.input) && /* @__PURE__ */ jsx6("span", { className: "awr-tool__args", children: previewValue(call.input) }),
872
- call.status === "calling" && /* @__PURE__ */ jsx6(SpinnerIcon, { size: 12, className: "awr-tool__spin" }),
873
- call.status === "done" && call.ok === false && /* @__PURE__ */ jsx6("span", { className: "awr-tool__badge", children: "failed" })
3100
+ const images = call.ok === false ? [] : imagesInOutput(call.output).slice(0, 4);
3101
+ const cost = [
3102
+ call.inputTokens ? `\u2248${formatTokens(call.inputTokens)} in` : "",
3103
+ call.outputTokens ? `\u2248${formatTokens(call.outputTokens)} out` : "",
3104
+ call.durationMs !== void 0 ? formatDuration(call.durationMs) : ""
3105
+ ].filter(Boolean).join(" \xB7 ");
3106
+ return /* @__PURE__ */ jsxs6("li", { className: `awr-tool awr-tool--${state}`, children: [
3107
+ /* @__PURE__ */ jsxs6("div", { className: "awr-tool__row", children: [
3108
+ /* @__PURE__ */ jsx8(ToolIcon, { size: 13, className: "awr-tool__icon" }),
3109
+ /* @__PURE__ */ jsx8("code", { className: "awr-tool__name", children: call.name }),
3110
+ previewValue(call.input) && /* @__PURE__ */ jsx8("span", { className: "awr-tool__args", children: previewValue(call.input) }),
3111
+ call.status === "calling" && /* @__PURE__ */ jsx8(SpinnerIcon, { size: 12, className: "awr-tool__spin" }),
3112
+ call.status === "done" && call.ok === false && /* @__PURE__ */ jsx8("span", { className: "awr-tool__badge", children: L.failed }),
3113
+ showUsage && cost && /* @__PURE__ */ jsx8("span", { className: "awr-tool__cost", title: L.toolCostTitle, children: cost })
3114
+ ] }),
3115
+ images.length > 0 && /* @__PURE__ */ jsx8("div", { className: "awr-tool__images", children: images.map((src, i) => /* @__PURE__ */ jsx8("a", { href: src, target: "_blank", rel: "noreferrer", children: /* @__PURE__ */ jsx8("img", { className: "awr-thumb", src, alt: `${call.name} result ${i + 1}` }) }, i)) })
874
3116
  ] });
875
3117
  };
876
- var StepItem = ({ step }) => /* @__PURE__ */ jsxs5("li", { className: `awr-step awr-step--${step.blocked ? "blocked" : step.status}`, children: [
877
- /* @__PURE__ */ jsxs5("div", { className: "awr-step__head", children: [
878
- /* @__PURE__ */ jsx6("span", { className: "awr-step__marker", children: step.status === "running" ? /* @__PURE__ */ jsx6(SpinnerIcon, { size: 14 }) : step.blocked ? /* @__PURE__ */ jsx6(AlertIcon, { size: 14 }) : /* @__PURE__ */ jsx6(CheckIcon, { size: 14 }) }),
879
- /* @__PURE__ */ jsxs5("span", { className: "awr-step__index", children: [
3118
+ var SubagentRow = ({
3119
+ sub,
3120
+ labels
3121
+ }) => {
3122
+ const L = useLabels(labels);
3123
+ return /* @__PURE__ */ jsxs6("li", { className: `awr-subagent awr-subagent--${sub.status}`, children: [
3124
+ /* @__PURE__ */ jsxs6("div", { className: "awr-subagent__head", children: [
3125
+ /* @__PURE__ */ jsx8(BotIcon, { size: 13, className: "awr-subagent__icon" }),
3126
+ /* @__PURE__ */ jsx8("span", { className: "awr-subagent__name", children: sub.name }),
3127
+ /* @__PURE__ */ jsx8("span", { className: "awr-subagent__task", title: sub.task, children: previewValue(sub.task, 90) }),
3128
+ sub.status === "running" && /* @__PURE__ */ jsx8(SpinnerIcon, { size: 12, className: "awr-tool__spin" })
3129
+ ] }),
3130
+ /* @__PURE__ */ jsx8("div", { className: "awr-subagent__activity", children: sub.status === "error" ? sub.error : sub.status === "done" ? previewValue(sub.text, 160) : `${sub.activity}${sub.toolCalls ? ` \xB7 ${L.toolCalls(sub.toolCalls)}` : ""}` })
3131
+ ] });
3132
+ };
3133
+ var decisionLabel = (a, L) => a.status === "pending" ? L.consentWaiting : a.status === "approved" ? L.consentAllowed : L.consentDenied(a.reason);
3134
+ var StepItem = ({
3135
+ step,
3136
+ subagents,
3137
+ approvals,
3138
+ showToolCalls,
3139
+ showUsage,
3140
+ showThoughts,
3141
+ renderToolCall,
3142
+ L
3143
+ }) => /* @__PURE__ */ jsxs6("li", { className: `awr-step awr-step--${step.blocked ? "blocked" : step.status}`, children: [
3144
+ /* @__PURE__ */ jsxs6("div", { className: "awr-step__head", children: [
3145
+ /* @__PURE__ */ jsx8("span", { className: "awr-step__marker", children: step.status === "running" ? /* @__PURE__ */ jsx8(SpinnerIcon, { size: 14 }) : step.blocked ? /* @__PURE__ */ jsx8(AlertIcon, { size: 14 }) : /* @__PURE__ */ jsx8(CheckIcon, { size: 14 }) }),
3146
+ /* @__PURE__ */ jsxs6("span", { className: "awr-step__index", children: [
880
3147
  step.index,
881
3148
  "/",
882
3149
  step.total
883
3150
  ] }),
884
- /* @__PURE__ */ jsx6("span", { className: "awr-step__desc", children: step.step.description })
3151
+ /* @__PURE__ */ jsx8("span", { className: "awr-step__desc", children: step.step.description })
885
3152
  ] }),
886
- step.text.trim() && /* @__PURE__ */ jsx6("p", { className: "awr-step__text", children: step.text.trim() }),
887
- step.toolCalls.length > 0 && /* @__PURE__ */ jsx6("ul", { className: "awr-step__tools", children: step.toolCalls.map((call, i) => /* @__PURE__ */ jsx6(ToolCallRow, { call }, i)) }),
888
- step.blocked && step.summary && /* @__PURE__ */ jsx6("p", { className: "awr-step__blocked", children: step.summary })
3153
+ showThoughts && step.reasoning.trim() && /* @__PURE__ */ jsxs6("details", { className: "awr-thought", open: step.status === "running" && !step.text, children: [
3154
+ /* @__PURE__ */ jsxs6("summary", { children: [
3155
+ /* @__PURE__ */ jsx8(BrainIcon, { size: 13 }),
3156
+ " ",
3157
+ L.stepThoughts
3158
+ ] }),
3159
+ /* @__PURE__ */ jsx8("p", { className: "awr-thought__text", children: step.reasoning.trim() })
3160
+ ] }),
3161
+ step.text.trim() && /* @__PURE__ */ jsx8("p", { className: "awr-step__text", children: step.text.trim() }),
3162
+ showToolCalls && step.toolCalls.length > 0 && /* @__PURE__ */ jsx8("ul", { className: "awr-step__tools", children: step.toolCalls.map((call, i) => {
3163
+ const row = /* @__PURE__ */ jsx8(ToolCallRow, { call, showUsage }, i);
3164
+ return renderToolCall ? /* @__PURE__ */ jsx8(Fragment5, { children: renderToolCall(call, row) }, i) : row;
3165
+ }) }),
3166
+ approvals.length > 0 && /* @__PURE__ */ jsx8("ul", { className: "awr-step__tools", children: approvals.map((a) => /* @__PURE__ */ jsxs6("li", { className: `awr-tool awr-tool__row awr-tool--approval-${a.status}`, children: [
3167
+ /* @__PURE__ */ jsx8(ShieldIcon, { size: 13, className: "awr-tool__icon" }),
3168
+ /* @__PURE__ */ jsx8("code", { className: "awr-tool__name", children: a.name }),
3169
+ /* @__PURE__ */ jsx8("span", { className: "awr-tool__args", children: decisionLabel(a, L) })
3170
+ ] }, a.id)) }),
3171
+ subagents.length > 0 && /* @__PURE__ */ jsx8("ul", { className: "awr-subagents", children: subagents.map((sub) => /* @__PURE__ */ jsx8(SubagentRow, { sub }, sub.id)) }),
3172
+ step.blocked && step.summary && /* @__PURE__ */ jsx8("p", { className: "awr-step__blocked", children: step.summary })
889
3173
  ] });
890
- var StepList = ({ steps, className }) => {
3174
+ var StepList = ({
3175
+ steps,
3176
+ subagents = [],
3177
+ approvals = [],
3178
+ showToolCalls = true,
3179
+ showUsage = true,
3180
+ showThoughts = true,
3181
+ renderToolCall,
3182
+ labels,
3183
+ className
3184
+ }) => {
3185
+ const L = useLabels(labels);
891
3186
  if (steps.length === 0) return null;
892
- return /* @__PURE__ */ jsx6("ol", { className: ["awr-steps", className].filter(Boolean).join(" "), children: steps.map((step) => /* @__PURE__ */ jsx6(StepItem, { step }, step.id)) });
3187
+ return /* @__PURE__ */ jsx8("ol", { className: ["awr-steps", className].filter(Boolean).join(" "), children: steps.map((step) => /* @__PURE__ */ jsx8(
3188
+ StepItem,
3189
+ {
3190
+ step,
3191
+ subagents: subagents.filter((s) => s.stepId === step.id),
3192
+ approvals: approvals.filter((a) => a.stepId === step.id && a.status !== "pending"),
3193
+ showToolCalls,
3194
+ showUsage,
3195
+ showThoughts,
3196
+ renderToolCall,
3197
+ L
3198
+ },
3199
+ step.id
3200
+ )) });
3201
+ };
3202
+
3203
+ // src/components/MessageList.tsx
3204
+ import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
3205
+ var usageLine = (usage, durationMs) => {
3206
+ const parts = [];
3207
+ if (usage && usage.totalTokens > 0) {
3208
+ parts.push(`in ${formatTokens(usage.inputTokens)}`, `out ${formatTokens(usage.outputTokens)}`);
3209
+ if (usage.reasoningTokens) parts.push(`think ${formatTokens(usage.reasoningTokens)}`);
3210
+ if (usage.cachedInputTokens) parts.push(`cached ${formatTokens(usage.cachedInputTokens)}`);
3211
+ }
3212
+ if (durationMs !== void 0) parts.push(formatDuration(durationMs));
3213
+ return parts.join(" \xB7 ");
3214
+ };
3215
+ var AttachmentView = ({ attachment: a }) => a.dataUrl && a.mediaType.startsWith("image/") ? /* @__PURE__ */ jsx9("a", { href: a.dataUrl, target: "_blank", rel: "noreferrer", title: a.path ?? a.name, children: /* @__PURE__ */ jsx9("img", { className: "awr-thumb awr-thumb--msg", src: a.dataUrl, alt: a.name }) }) : /* @__PURE__ */ jsxs7("span", { className: "awr-chip awr-file", title: a.path ?? a.mediaType, children: [
3216
+ /* @__PURE__ */ jsx9(FileIcon, { size: 13 }),
3217
+ " ",
3218
+ a.name
3219
+ ] });
3220
+ var toolCallCount = (m) => (m.steps ?? []).reduce((n, s) => n + s.toolCalls.length, 0);
3221
+ var activitySummary = (m, showToolCalls, L) => {
3222
+ const steps = m.steps ?? [];
3223
+ const parts = [L.steps(steps.length)];
3224
+ if (showToolCalls) parts.push(L.toolCalls(toolCallCount(m)));
3225
+ if (m.subagents?.length) parts.push(L.subagents(m.subagents.length));
3226
+ if (m.skills?.length) parts.push(L.skillsUsed(m.skills.join(", ")));
3227
+ return parts.join(" \xB7 ");
3228
+ };
3229
+ var MessageList = ({
3230
+ messages,
3231
+ empty,
3232
+ showActivity = true,
3233
+ showToolCalls = true,
3234
+ showUsage = true,
3235
+ showThoughts = true,
3236
+ activityOpen = false,
3237
+ liveExtra,
3238
+ renderContent,
3239
+ renderMessage,
3240
+ renderAttachment,
3241
+ renderToolCall,
3242
+ labels,
3243
+ className
3244
+ }) => {
3245
+ const L = useLabels(labels);
3246
+ if (messages.length === 0) {
3247
+ return empty ? /* @__PURE__ */ jsx9("div", { className: "awr-messages__empty", children: empty }) : null;
3248
+ }
3249
+ return /* @__PURE__ */ jsx9("div", { className: ["awr-messages", className].filter(Boolean).join(" "), children: messages.map((m) => {
3250
+ const steps = m.steps ?? [];
3251
+ const hasActivity = showActivity && (steps.length > 0 || (m.subagents?.length ?? 0) > 0 || m.pending && !!liveExtra);
3252
+ const usage = showUsage ? usageLine(m.usage, m.durationMs) : "";
3253
+ const node = /* @__PURE__ */ jsx9(
3254
+ "div",
3255
+ {
3256
+ className: `awr-msg awr-msg--${m.role}${m.error ? " awr-msg--error" : ""}${m.pending ? " is-pending" : ""}`,
3257
+ children: /* @__PURE__ */ jsxs7("div", { className: "awr-msg__col", children: [
3258
+ m.role === "assistant" && hasActivity && /* @__PURE__ */ jsxs7("details", { className: "awr-activity", open: m.pending || activityOpen, children: [
3259
+ /* @__PURE__ */ jsx9("summary", { className: "awr-activity__summary", children: activitySummary(m, showToolCalls, L) }),
3260
+ m.pending && liveExtra,
3261
+ /* @__PURE__ */ jsx9(
3262
+ StepList,
3263
+ {
3264
+ steps,
3265
+ subagents: m.subagents,
3266
+ approvals: m.approvals,
3267
+ showToolCalls,
3268
+ showUsage,
3269
+ showThoughts,
3270
+ renderToolCall,
3271
+ labels
3272
+ }
3273
+ ),
3274
+ showThoughts && m.reasoning?.trim() && /* @__PURE__ */ jsxs7("details", { className: "awr-thought", children: [
3275
+ /* @__PURE__ */ jsxs7("summary", { children: [
3276
+ /* @__PURE__ */ jsx9(BrainIcon, { size: 13 }),
3277
+ " ",
3278
+ L.answerThoughts
3279
+ ] }),
3280
+ /* @__PURE__ */ jsx9("p", { className: "awr-thought__text", children: m.reasoning.trim() })
3281
+ ] })
3282
+ ] }),
3283
+ (m.content || m.pending || !m.attachments?.length) && /* @__PURE__ */ jsxs7("div", { className: "awr-msg__bubble", children: [
3284
+ m.content ? renderContent ? renderContent(m) : m.content : null,
3285
+ m.pending && !m.content && /* @__PURE__ */ jsx9(SpinnerIcon, { size: 14, className: "awr-msg__pending" })
3286
+ ] }),
3287
+ m.attachments?.length ? /* @__PURE__ */ jsx9("div", { className: "awr-msg__attachments", "aria-label": L.attachments, children: m.attachments.map((a, i) => /* @__PURE__ */ jsx9("span", { className: "awr-msg__attachment", children: renderAttachment ? renderAttachment(a, m) : /* @__PURE__ */ jsx9(AttachmentView, { attachment: a }) }, i)) }) : null,
3288
+ m.role === "assistant" && usage && !m.pending && /* @__PURE__ */ jsx9("div", { className: "awr-msg__usage", title: L.usageTitle, children: usage })
3289
+ ] })
3290
+ },
3291
+ m.id
3292
+ );
3293
+ return renderMessage ? /* @__PURE__ */ jsx9("div", { children: renderMessage(m, node) }, m.id) : node;
3294
+ }) });
3295
+ };
3296
+
3297
+ // src/components/ModelLoadBar.tsx
3298
+ import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
3299
+ var ModelLoadBar = ({ load, className }) => {
3300
+ const pct = Math.round(Math.max(0, Math.min(1, load.progress)) * 100);
3301
+ return /* @__PURE__ */ jsxs8("div", { className: ["awr-modelload", className].filter(Boolean).join(" "), children: [
3302
+ /* @__PURE__ */ jsxs8("div", { className: "awr-modelload__head", children: [
3303
+ /* @__PURE__ */ jsx10("span", { className: "awr-modelload__text", children: load.text || "Loading model\u2026" }),
3304
+ /* @__PURE__ */ jsxs8("span", { className: "awr-modelload__pct", children: [
3305
+ pct,
3306
+ "%"
3307
+ ] })
3308
+ ] }),
3309
+ /* @__PURE__ */ jsx10("div", { className: "awr-modelload__track", role: "progressbar", "aria-valuenow": pct, children: /* @__PURE__ */ jsx10("div", { className: "awr-modelload__fill", style: { width: `${pct}%` } }) })
3310
+ ] });
3311
+ };
3312
+
3313
+ // src/components/ToolApprovalPrompt.tsx
3314
+ import { jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
3315
+ var ToolApprovalPrompt = ({
3316
+ approvals,
3317
+ onApprove,
3318
+ onDeny,
3319
+ allowRemember = true,
3320
+ renderApproval,
3321
+ labels,
3322
+ className
3323
+ }) => {
3324
+ const L = useLabels(labels);
3325
+ if (approvals.length === 0) return null;
3326
+ return /* @__PURE__ */ jsx11("div", { className: ["awr-approvals", className].filter(Boolean).join(" "), role: "alert", children: approvals.map((a) => {
3327
+ const card = /* @__PURE__ */ jsxs9("div", { className: "awr-approval", children: [
3328
+ /* @__PURE__ */ jsxs9("div", { className: "awr-approval__head", children: [
3329
+ /* @__PURE__ */ jsx11(ShieldIcon, { size: 14, className: "awr-approval__icon" }),
3330
+ /* @__PURE__ */ jsxs9("span", { children: [
3331
+ L.approvalLead,
3332
+ " ",
3333
+ /* @__PURE__ */ jsx11("code", { className: "awr-tool__name", children: a.name }),
3334
+ a.readOnly ? ` (${L.readOnlyTool})` : ""
3335
+ ] })
3336
+ ] }),
3337
+ previewValue(a.input, 300) && /* @__PURE__ */ jsx11("pre", { className: "awr-approval__input", children: previewValue(a.input, 300) }),
3338
+ /* @__PURE__ */ jsxs9("div", { className: "awr-approval__actions", children: [
3339
+ /* @__PURE__ */ jsx11(
3340
+ "button",
3341
+ {
3342
+ type: "button",
3343
+ className: "awr-btn awr-btn--primary",
3344
+ onClick: () => onApprove(a.id),
3345
+ children: L.approve
3346
+ }
3347
+ ),
3348
+ allowRemember && /* @__PURE__ */ jsx11(
3349
+ "button",
3350
+ {
3351
+ type: "button",
3352
+ className: "awr-btn",
3353
+ onClick: () => onApprove(a.id, { remember: true }),
3354
+ children: L.alwaysAllow
3355
+ }
3356
+ ),
3357
+ /* @__PURE__ */ jsx11(
3358
+ "button",
3359
+ {
3360
+ type: "button",
3361
+ className: "awr-btn awr-btn--danger",
3362
+ onClick: () => onDeny(a.id, L.declinedReason),
3363
+ children: L.deny
3364
+ }
3365
+ )
3366
+ ] })
3367
+ ] }, a.id);
3368
+ return renderApproval ? /* @__PURE__ */ jsx11("div", { children: renderApproval(a, card) }, a.id) : card;
3369
+ }) });
893
3370
  };
894
3371
 
895
3372
  // src/components/UsageBadge.tsx
896
- import { jsxs as jsxs6 } from "react/jsx-runtime";
897
- var fmt = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
898
- var UsageBadge = ({ usage, className }) => {
3373
+ import { jsxs as jsxs10 } from "react/jsx-runtime";
3374
+ var UsageBadge = ({ usage, compact = false, className }) => {
899
3375
  if (usage.totalTokens === 0) return null;
900
- return /* @__PURE__ */ jsxs6(
901
- "span",
902
- {
903
- className: ["awr-usage", className].filter(Boolean).join(" "),
904
- title: `${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`,
905
- children: [
906
- fmt(usage.inputTokens),
907
- "\u2191 ",
908
- fmt(usage.outputTokens),
909
- "\u2193"
910
- ]
911
- }
912
- );
3376
+ const reasoning = usage.reasoningTokens ?? 0;
3377
+ const cached = usage.cachedInputTokens ?? 0;
3378
+ const title = [
3379
+ `${usage.inputTokens} in + ${usage.outputTokens} out = ${usage.totalTokens} tokens`,
3380
+ reasoning ? `${reasoning} thinking` : "",
3381
+ cached ? `${cached} input tokens from the prompt cache` : ""
3382
+ ].filter(Boolean).join(" \xB7 ");
3383
+ return /* @__PURE__ */ jsxs10("span", { className: ["awr-usage", className].filter(Boolean).join(" "), title, children: [
3384
+ formatTokens(usage.inputTokens),
3385
+ "\u2191 ",
3386
+ formatTokens(usage.outputTokens),
3387
+ "\u2193",
3388
+ !compact && reasoning > 0 && ` \xB7 ${formatTokens(reasoning)} think`,
3389
+ !compact && cached > 0 && ` \xB7 ${formatTokens(cached)} cached`
3390
+ ] });
913
3391
  };
914
3392
 
915
3393
  // src/components/AgentChat.tsx
916
- import { jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
917
- var statusLabel = (status) => {
918
- switch (status) {
919
- case "initializing":
920
- return "Loading model\u2026";
921
- case "running":
922
- return "Working\u2026";
923
- case "error":
924
- return "Failed to start";
925
- default:
926
- return "Ready";
927
- }
928
- };
929
- var AgentChat = ({
3394
+ import { Fragment as Fragment6, jsx as jsx12, jsxs as jsxs11 } from "react/jsx-runtime";
3395
+ var isHistoryHook = (h) => typeof h === "object" && h !== null && "select" in h && "chats" in h;
3396
+ var cx = (...names) => names.filter(Boolean).join(" ");
3397
+ var AgentChat = (props) => /* @__PURE__ */ jsx12(AgentLabelsProvider, { labels: props.labels ?? NO_LABELS, children: /* @__PURE__ */ jsx12(AgentChatInner, { ...props }) });
3398
+ var NO_LABELS = {};
3399
+ var AgentChatInner = ({
930
3400
  controller,
931
3401
  title,
3402
+ emptyState,
932
3403
  placeholder,
933
3404
  showActivity = true,
3405
+ showToolCalls = true,
934
3406
  showUsage = true,
935
- emptyState = "Ask the agent to do something.",
3407
+ showThoughts = true,
3408
+ showTotalUsage = true,
3409
+ showStatus = true,
3410
+ showApprovalMode = true,
3411
+ showContext = false,
3412
+ activityOpen = false,
3413
+ history,
3414
+ defaultHistoryOpen,
3415
+ files,
3416
+ defaultFilesOpen = false,
3417
+ narrowWidth = 760,
3418
+ composer,
3419
+ renderContent,
3420
+ renderMessage,
3421
+ renderAttachment,
3422
+ renderToolCall,
3423
+ renderApproval,
3424
+ slots = {},
3425
+ components = {},
3426
+ theme = "auto",
3427
+ classNames = {},
936
3428
  className,
937
3429
  style
938
3430
  }) => {
@@ -943,72 +3435,354 @@ var AgentChat = ({
943
3435
  "<AgentChat> needs a `controller` prop from useAgent(), or an enclosing <AgentProvider>."
944
3436
  );
945
3437
  }
946
- const bodyRef = useRef4(null);
947
- useEffect3(() => {
3438
+ const L = useLabels();
3439
+ const external = isHistoryHook(history) ? history : void 0;
3440
+ const [ownStore] = useState11(
3441
+ () => history instanceof ChatHistoryStore ? history : new ChatHistoryStore()
3442
+ );
3443
+ const own = useChatHistory(agent, {
3444
+ store: ownStore,
3445
+ enabled: Boolean(history) && !external
3446
+ });
3447
+ const chats = history ? external ?? own : void 0;
3448
+ const rootRef = useRef9(null);
3449
+ const [narrow, setNarrow] = useState11(void 0);
3450
+ useEffect9(() => {
3451
+ const el = rootRef.current;
3452
+ if (!el || typeof ResizeObserver === "undefined") return setNarrow(false);
3453
+ const measure = () => setNarrow(el.getBoundingClientRect().width < narrowWidth);
3454
+ measure();
3455
+ const ro = new ResizeObserver(measure);
3456
+ ro.observe(el);
3457
+ return () => ro.disconnect();
3458
+ }, [narrowWidth]);
3459
+ const [historyChoice, setHistoryOpen] = useState11(defaultHistoryOpen);
3460
+ const historyOpen = historyChoice ?? narrow === false;
3461
+ const [filesOpen, setFilesOpen] = useState11(defaultFilesOpen);
3462
+ const toggleHistory = () => {
3463
+ setHistoryOpen(!historyOpen);
3464
+ if (narrow && !historyOpen) setFilesOpen(false);
3465
+ };
3466
+ const toggleFiles = () => {
3467
+ setFilesOpen((o) => !o);
3468
+ if (narrow && !filesOpen) setHistoryOpen(false);
3469
+ };
3470
+ const bodyRef = useRef9(null);
3471
+ const stickRef = useRef9(true);
3472
+ useEffect9(() => {
948
3473
  const el = bodyRef.current;
949
- if (el) el.scrollTop = el.scrollHeight;
950
- }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad]);
3474
+ if (el && stickRef.current) el.scrollTop = el.scrollHeight;
3475
+ }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad, agent.pendingApprovals]);
3476
+ const [compacting, setCompacting] = useState11(false);
3477
+ const compact = () => {
3478
+ setCompacting(true);
3479
+ void agent.compact().finally(() => setCompacting(false));
3480
+ };
3481
+ const Composer2 = components.Composer ?? AgentComposer;
3482
+ const Messages = components.MessageList ?? MessageList;
3483
+ const HistoryList = components.HistoryList ?? ChatHistoryList;
3484
+ const Files = components.FilesPanel ?? FilesPanel;
3485
+ const Approvals = components.ApprovalPrompt ?? ToolApprovalPrompt;
3486
+ const loading = agent.modelLoad && agent.modelLoad.progress < 1;
951
3487
  const showReplan = agent.replan && agent.replan.mode !== "continue";
952
- const loading = agent.modelLoad && agent.modelLoad.progress < 1 && agent.isRunning === false;
953
- return /* @__PURE__ */ jsxs7("div", { className: ["awr-chat", className].filter(Boolean).join(" "), style, children: [
954
- title && /* @__PURE__ */ jsx7("div", { className: "awr-chat__title", children: title }),
955
- /* @__PURE__ */ jsxs7("div", { className: "awr-chat__body", ref: bodyRef, children: [
956
- /* @__PURE__ */ jsx7(MessageList, { messages: agent.messages, empty: emptyState }),
957
- showActivity && (agent.steps.length > 0 || agent.planThought) && /* @__PURE__ */ jsxs7("div", { className: "awr-activity", children: [
958
- agent.planThought.trim() && /* @__PURE__ */ jsxs7("details", { className: "awr-activity__plan", children: [
959
- /* @__PURE__ */ jsx7("summary", { children: "Plan" }),
960
- /* @__PURE__ */ jsx7("p", { className: "awr-activity__thought", children: agent.planThought })
961
- ] }),
962
- /* @__PURE__ */ jsx7(StepList, { steps: agent.steps }),
963
- showReplan && /* @__PURE__ */ jsxs7("div", { className: "awr-activity__replan", children: [
964
- "Replanned (",
965
- agent.replan.mode,
966
- "): ",
967
- agent.replan.reason
968
- ] })
969
- ] }),
970
- agent.modelLoad && (loading || agent.isRunning) && agent.modelLoad.progress < 1 && /* @__PURE__ */ jsx7(ModelLoadBar, { load: agent.modelLoad })
3488
+ const liveExtra = agent.planThought.trim() || showReplan ? /* @__PURE__ */ jsxs11(Fragment6, { children: [
3489
+ agent.planThought.trim() && /* @__PURE__ */ jsxs11("details", { className: "awr-activity__plan", children: [
3490
+ /* @__PURE__ */ jsx12("summary", { children: L.planned }),
3491
+ /* @__PURE__ */ jsx12("p", { className: "awr-activity__thought", children: agent.planThought })
971
3492
  ] }),
972
- agent.error && agent.status === "error" && /* @__PURE__ */ jsxs7("div", { className: "awr-chat__error", children: [
973
- /* @__PURE__ */ jsx7(AlertIcon, { size: 14 }),
974
- " ",
975
- agent.error
3493
+ showReplan && /* @__PURE__ */ jsx12("div", { className: "awr-activity__replan", children: L.replanned(agent.replan.mode, agent.replan.reason) })
3494
+ ] }) : void 0;
3495
+ const header = slots.header === false ? null : slots.header !== void 0 ? slots.header : /* @__PURE__ */ jsxs11("div", { className: cx("awr-chat__header", classNames.header), children: [
3496
+ chats && /* @__PURE__ */ jsx12(
3497
+ "button",
3498
+ {
3499
+ type: "button",
3500
+ className: cx("awr-iconbtn", historyOpen && "is-on"),
3501
+ "aria-label": L.showHistory,
3502
+ title: L.showHistory,
3503
+ "aria-pressed": historyOpen,
3504
+ onClick: toggleHistory,
3505
+ children: /* @__PURE__ */ jsx12(HistoryIcon, { size: 16 })
3506
+ }
3507
+ ),
3508
+ slots.headerStart,
3509
+ /* @__PURE__ */ jsx12("div", { className: "awr-chat__title", children: title }),
3510
+ showStatus && /* @__PURE__ */ jsxs11("span", { className: `awr-status awr-status--${agent.status}`, title: L.status[agent.status], children: [
3511
+ /* @__PURE__ */ jsx12("span", { className: "awr-status__dot" }),
3512
+ /* @__PURE__ */ jsx12("span", { className: "awr-status__text", children: L.status[agent.status] })
976
3513
  ] }),
977
- /* @__PURE__ */ jsxs7("div", { className: "awr-chat__footer", children: [
978
- /* @__PURE__ */ jsxs7("div", { className: "awr-chat__meta", children: [
979
- /* @__PURE__ */ jsxs7("span", { className: `awr-status awr-status--${agent.status}`, children: [
980
- /* @__PURE__ */ jsx7("span", { className: "awr-status__dot" }),
981
- statusLabel(agent.status)
982
- ] }),
983
- showUsage && /* @__PURE__ */ jsx7(UsageBadge, { usage: agent.usage })
984
- ] }),
985
- /* @__PURE__ */ jsx7(
986
- Composer,
987
- {
988
- onSubmit: (text) => void agent.run(text),
989
- busy: agent.isRunning,
990
- onStop: agent.stop,
991
- disabled: !agent.isReady && !agent.isRunning,
992
- placeholder
993
- }
994
- )
995
- ] })
3514
+ showTotalUsage && /* @__PURE__ */ jsx12("span", { title: L.totalUsage, children: /* @__PURE__ */ jsx12(UsageBadge, { usage: agent.totalUsage, compact: narrow !== false }) }),
3515
+ files && /* @__PURE__ */ jsx12(
3516
+ "button",
3517
+ {
3518
+ type: "button",
3519
+ className: cx("awr-iconbtn", filesOpen && "is-on"),
3520
+ "aria-label": L.showFiles,
3521
+ title: L.showFiles,
3522
+ "aria-pressed": filesOpen,
3523
+ onClick: toggleFiles,
3524
+ children: /* @__PURE__ */ jsx12(FileIcon, { size: 16 })
3525
+ }
3526
+ ),
3527
+ slots.headerEnd
996
3528
  ] });
3529
+ return /* @__PURE__ */ jsxs11(
3530
+ "div",
3531
+ {
3532
+ ref: rootRef,
3533
+ className: cx("awr-chat", narrow && "awr-chat--narrow", className, classNames.root),
3534
+ style,
3535
+ "data-awr-theme": theme === "auto" ? void 0 : theme,
3536
+ children: [
3537
+ chats && historyOpen && /* @__PURE__ */ jsxs11("aside", { className: cx("awr-chat__sidebar", classNames.sidebar), children: [
3538
+ /* @__PURE__ */ jsx12(
3539
+ HistoryList,
3540
+ {
3541
+ history: {
3542
+ ...chats,
3543
+ // Picking a chat on a narrow panel closes the overlay.
3544
+ select: async (id) => {
3545
+ await chats.select(id);
3546
+ if (narrow) setHistoryOpen(false);
3547
+ },
3548
+ newChat: () => {
3549
+ chats.newChat();
3550
+ if (narrow) setHistoryOpen(false);
3551
+ }
3552
+ },
3553
+ disabled: agent.isRunning
3554
+ }
3555
+ ),
3556
+ slots.sidebar,
3557
+ /* @__PURE__ */ jsx12(
3558
+ "button",
3559
+ {
3560
+ type: "button",
3561
+ className: "awr-iconbtn awr-chat__closeside",
3562
+ "aria-label": L.close,
3563
+ onClick: () => setHistoryOpen(false),
3564
+ children: "\xD7"
3565
+ }
3566
+ )
3567
+ ] }),
3568
+ /* @__PURE__ */ jsxs11("div", { className: cx("awr-chat__main", classNames.main), children: [
3569
+ header,
3570
+ /* @__PURE__ */ jsxs11(
3571
+ "div",
3572
+ {
3573
+ className: cx("awr-chat__body", classNames.body),
3574
+ ref: bodyRef,
3575
+ onScroll: (e) => {
3576
+ const el = e.currentTarget;
3577
+ stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
3578
+ },
3579
+ children: [
3580
+ slots.beforeMessages,
3581
+ /* @__PURE__ */ jsx12(
3582
+ Messages,
3583
+ {
3584
+ messages: agent.messages,
3585
+ empty: emptyState ?? L.emptyState,
3586
+ showActivity,
3587
+ showToolCalls,
3588
+ showUsage,
3589
+ showThoughts,
3590
+ activityOpen,
3591
+ liveExtra,
3592
+ renderContent,
3593
+ renderMessage,
3594
+ renderAttachment,
3595
+ renderToolCall
3596
+ }
3597
+ ),
3598
+ /* @__PURE__ */ jsx12(
3599
+ Approvals,
3600
+ {
3601
+ approvals: agent.pendingApprovals,
3602
+ onApprove: agent.approve,
3603
+ onDeny: agent.deny,
3604
+ renderApproval
3605
+ }
3606
+ ),
3607
+ agent.modelLoad && loading && /* @__PURE__ */ jsx12(ModelLoadBar, { load: agent.modelLoad }),
3608
+ slots.afterMessages
3609
+ ]
3610
+ }
3611
+ ),
3612
+ /* @__PURE__ */ jsxs11("div", { className: cx("awr-chat__footer", classNames.footer), children: [
3613
+ slots.footerStart,
3614
+ showContext !== false && /* @__PURE__ */ jsx12(
3615
+ ContextMeter,
3616
+ {
3617
+ usage: agent.usage,
3618
+ budgetTokens: typeof showContext === "number" ? showContext : void 0,
3619
+ budget: agent.budget,
3620
+ compactions: agent.compactions,
3621
+ onCompact: agent.isRunning ? void 0 : compact,
3622
+ compacting
3623
+ }
3624
+ ),
3625
+ composer === false ? agent.error && agent.status === "error" && /* @__PURE__ */ jsxs11("div", { className: "awr-chat__error", children: [
3626
+ /* @__PURE__ */ jsx12(AlertIcon, { size: 14 }),
3627
+ " ",
3628
+ agent.error
3629
+ ] }) : /* @__PURE__ */ jsx12(
3630
+ Composer2,
3631
+ {
3632
+ controller: agent,
3633
+ showApprovalMode,
3634
+ files,
3635
+ dropZone: rootRef,
3636
+ ...placeholder ? { placeholder } : {},
3637
+ ...composer
3638
+ }
3639
+ )
3640
+ ] })
3641
+ ] }),
3642
+ files && filesOpen && /* @__PURE__ */ jsxs11("aside", { className: cx("awr-chat__files", classNames.files), children: [
3643
+ /* @__PURE__ */ jsx12(Files, { files }),
3644
+ /* @__PURE__ */ jsx12(
3645
+ "button",
3646
+ {
3647
+ type: "button",
3648
+ className: "awr-iconbtn awr-chat__closeside",
3649
+ "aria-label": L.close,
3650
+ onClick: () => setFilesOpen(false),
3651
+ children: "\xD7"
3652
+ }
3653
+ )
3654
+ ] })
3655
+ ]
3656
+ }
3657
+ );
3658
+ };
3659
+
3660
+ // src/components/Composer.tsx
3661
+ import { useState as useState12 } from "react";
3662
+ import { jsx as jsx13, jsxs as jsxs12 } from "react/jsx-runtime";
3663
+ var Composer = ({
3664
+ onSubmit,
3665
+ busy = false,
3666
+ onStop,
3667
+ disabled = false,
3668
+ placeholder = "Ask the agent to do something\u2026",
3669
+ className
3670
+ }) => {
3671
+ const [text, setText] = useState12("");
3672
+ const submit = () => {
3673
+ const value = text.trim();
3674
+ if (!value || busy || disabled) return;
3675
+ setText("");
3676
+ onSubmit(value);
3677
+ };
3678
+ const onKeyDown = (e) => {
3679
+ if (e.key === "Enter" && !e.shiftKey) {
3680
+ e.preventDefault();
3681
+ submit();
3682
+ }
3683
+ };
3684
+ return /* @__PURE__ */ jsxs12(
3685
+ "form",
3686
+ {
3687
+ className: ["awr-composer", className].filter(Boolean).join(" "),
3688
+ onSubmit: (e) => {
3689
+ e.preventDefault();
3690
+ submit();
3691
+ },
3692
+ children: [
3693
+ /* @__PURE__ */ jsx13(
3694
+ "textarea",
3695
+ {
3696
+ className: "awr-composer__input",
3697
+ value: text,
3698
+ onChange: (e) => setText(e.target.value),
3699
+ onKeyDown,
3700
+ placeholder,
3701
+ disabled,
3702
+ rows: 1
3703
+ }
3704
+ ),
3705
+ busy ? /* @__PURE__ */ jsx13(
3706
+ "button",
3707
+ {
3708
+ type: "button",
3709
+ className: "awr-composer__btn awr-composer__btn--stop",
3710
+ onClick: onStop,
3711
+ "aria-label": "Stop",
3712
+ children: /* @__PURE__ */ jsx13(StopIcon, { size: 18 })
3713
+ }
3714
+ ) : /* @__PURE__ */ jsx13(
3715
+ "button",
3716
+ {
3717
+ type: "submit",
3718
+ className: "awr-composer__btn",
3719
+ disabled: disabled || !text.trim(),
3720
+ "aria-label": "Send",
3721
+ children: disabled ? /* @__PURE__ */ jsx13(SpinnerIcon, { size: 18 }) : /* @__PURE__ */ jsx13(SendIcon, { size: 18 })
3722
+ }
3723
+ )
3724
+ ]
3725
+ }
3726
+ );
997
3727
  };
998
3728
 
999
3729
  // src/components/PlanView.tsx
1000
- import { jsx as jsx8, jsxs as jsxs8 } from "react/jsx-runtime";
3730
+ import { jsx as jsx14, jsxs as jsxs13 } from "react/jsx-runtime";
1001
3731
  var PlanView = ({ plan, showThought = true, className }) => {
1002
3732
  if (!plan.steps.length && !plan.thought) return null;
1003
- return /* @__PURE__ */ jsxs8("div", { className: ["awr-plan", className].filter(Boolean).join(" "), children: [
1004
- showThought && plan.thought.trim() && /* @__PURE__ */ jsx8("p", { className: "awr-plan__thought", children: plan.thought }),
1005
- plan.steps.length > 0 && /* @__PURE__ */ jsx8("ol", { className: "awr-plan__steps", children: plan.steps.map((step) => /* @__PURE__ */ jsx8("li", { className: "awr-plan__step", children: step.description }, step.id)) })
3733
+ return /* @__PURE__ */ jsxs13("div", { className: ["awr-plan", className].filter(Boolean).join(" "), children: [
3734
+ showThought && plan.thought.trim() && /* @__PURE__ */ jsx14("p", { className: "awr-plan__thought", children: plan.thought }),
3735
+ plan.steps.length > 0 && /* @__PURE__ */ jsx14("ol", { className: "awr-plan__steps", children: plan.steps.map((step) => /* @__PURE__ */ jsx14("li", { className: "awr-plan__step", children: step.description }, step.id)) })
1006
3736
  ] });
1007
3737
  };
1008
3738
 
3739
+ // src/components/ApprovalModeSwitch.tsx
3740
+ import { jsx as jsx15 } from "react/jsx-runtime";
3741
+ var DEFAULT_LABELS = {
3742
+ autopilot: "Autopilot",
3743
+ "ask-writes": "Ask before changes",
3744
+ "ask-all": "Ask always",
3745
+ "read-only": "Read-only"
3746
+ };
3747
+ var HINTS = {
3748
+ autopilot: "Run every tool without asking",
3749
+ "ask-writes": "Run read-only tools freely; ask before anything that may change state",
3750
+ "ask-all": "Ask before every tool call",
3751
+ "read-only": "Run read-only tools; refuse everything else without asking"
3752
+ };
3753
+ var ApprovalModeSwitch = ({
3754
+ mode,
3755
+ onChange,
3756
+ modes = ["autopilot", "ask-writes", "ask-all", "read-only"],
3757
+ labels,
3758
+ disabled,
3759
+ className
3760
+ }) => /* @__PURE__ */ jsx15(
3761
+ "div",
3762
+ {
3763
+ className: ["awr-modeswitch", className].filter(Boolean).join(" "),
3764
+ role: "radiogroup",
3765
+ "aria-label": "Tool consent",
3766
+ children: modes.map((m) => /* @__PURE__ */ jsx15(
3767
+ "button",
3768
+ {
3769
+ type: "button",
3770
+ role: "radio",
3771
+ "aria-checked": mode === m,
3772
+ title: HINTS[m],
3773
+ className: `awr-modeswitch__opt${mode === m ? " is-active" : ""}`,
3774
+ onClick: () => onChange(m),
3775
+ disabled,
3776
+ children: labels?.[m] ?? DEFAULT_LABELS[m]
3777
+ },
3778
+ m
3779
+ ))
3780
+ }
3781
+ );
3782
+
1009
3783
  // src/components/ApiKeyForm.tsx
1010
- import { useEffect as useEffect4, useState as useState6 } from "react";
1011
- import { jsx as jsx9, jsxs as jsxs9 } from "react/jsx-runtime";
3784
+ import { useEffect as useEffect10, useState as useState13 } from "react";
3785
+ import { jsx as jsx16, jsxs as jsxs14 } from "react/jsx-runtime";
1012
3786
  var ApiKeyForm = ({
1013
3787
  credentials,
1014
3788
  credentialRef,
@@ -1017,10 +3791,10 @@ var ApiKeyForm = ({
1017
3791
  onChange,
1018
3792
  className
1019
3793
  }) => {
1020
- const [value, setValue] = useState6("");
1021
- const [present, setPresent] = useState6(false);
1022
- const [busy, setBusy] = useState6(false);
1023
- useEffect4(() => {
3794
+ const [value, setValue] = useState13("");
3795
+ const [present, setPresent] = useState13(false);
3796
+ const [busy, setBusy] = useState13(false);
3797
+ useEffect10(() => {
1024
3798
  let active = true;
1025
3799
  credentials.hasKey(credentialRef).then((has) => {
1026
3800
  if (active) setPresent(has);
@@ -1052,16 +3826,16 @@ var ApiKeyForm = ({
1052
3826
  setBusy(false);
1053
3827
  }
1054
3828
  };
1055
- return /* @__PURE__ */ jsxs9("div", { className: ["awr-keyform", className].filter(Boolean).join(" "), children: [
1056
- /* @__PURE__ */ jsxs9("label", { className: "awr-keyform__label", children: [
3829
+ return /* @__PURE__ */ jsxs14("div", { className: ["awr-keyform", className].filter(Boolean).join(" "), children: [
3830
+ /* @__PURE__ */ jsxs14("label", { className: "awr-keyform__label", children: [
1057
3831
  label,
1058
- present && /* @__PURE__ */ jsxs9("span", { className: "awr-keyform__saved", children: [
1059
- /* @__PURE__ */ jsx9(CheckIcon, { size: 12 }),
3832
+ present && /* @__PURE__ */ jsxs14("span", { className: "awr-keyform__saved", children: [
3833
+ /* @__PURE__ */ jsx16(CheckIcon, { size: 12 }),
1060
3834
  " stored, encrypted"
1061
3835
  ] })
1062
3836
  ] }),
1063
- /* @__PURE__ */ jsxs9("div", { className: "awr-keyform__row", children: [
1064
- /* @__PURE__ */ jsx9(
3837
+ /* @__PURE__ */ jsxs14("div", { className: "awr-keyform__row", children: [
3838
+ /* @__PURE__ */ jsx16(
1065
3839
  "input",
1066
3840
  {
1067
3841
  className: "awr-keyform__input",
@@ -1079,7 +3853,7 @@ var ApiKeyForm = ({
1079
3853
  disabled: busy
1080
3854
  }
1081
3855
  ),
1082
- /* @__PURE__ */ jsx9(
3856
+ /* @__PURE__ */ jsx16(
1083
3857
  "button",
1084
3858
  {
1085
3859
  type: "button",
@@ -1089,7 +3863,7 @@ var ApiKeyForm = ({
1089
3863
  children: "Save"
1090
3864
  }
1091
3865
  ),
1092
- present && /* @__PURE__ */ jsx9(
3866
+ present && /* @__PURE__ */ jsx16(
1093
3867
  "button",
1094
3868
  {
1095
3869
  type: "button",
@@ -1107,43 +3881,100 @@ var ApiKeyForm = ({
1107
3881
  import {
1108
3882
  createAgent as createAgent2,
1109
3883
  defineTool,
3884
+ defineSkill,
3885
+ parseSkillMarkdown,
3886
+ loadSkillFromUrl,
3887
+ createSubagentTool,
3888
+ serveSubagentWorker,
3889
+ markReadOnly,
1110
3890
  createWebLLMModel as createWebLLMModel2,
1111
3891
  preloadWebLLMModel as preloadWebLLMModel2,
1112
3892
  unloadWebLLMModel,
1113
3893
  isWebGPUAvailable as isWebGPUAvailable2,
1114
3894
  VaultCredentialStore as VaultCredentialStore2,
1115
- MemoryCredentialStore
3895
+ MemoryCredentialStore,
3896
+ MemoryStore,
3897
+ IndexedDBStore,
3898
+ VirtualFileSystem,
3899
+ createFileTools,
3900
+ AttachmentsNotSupportedError,
3901
+ ImagesNotSupportedError,
3902
+ supportsImages,
3903
+ supportsPdf
1116
3904
  } from "@dudko.dev/agent-web";
1117
3905
  export {
1118
3906
  AgentChat,
3907
+ AgentComposer,
3908
+ AgentLabelsProvider,
1119
3909
  AgentProvider,
1120
3910
  ApiKeyForm,
3911
+ ApprovalModeSwitch,
3912
+ AttachmentView,
3913
+ AttachmentsNotSupportedError,
3914
+ ChatHistoryList,
3915
+ ChatHistoryStore,
1121
3916
  Composer,
3917
+ ContextMeter,
3918
+ FilesPanel,
3919
+ ImagesNotSupportedError,
3920
+ IndexedDBStore,
1122
3921
  MemoryCredentialStore,
3922
+ MemoryStore,
1123
3923
  MessageList,
1124
3924
  ModelLoadBar,
1125
3925
  PlanView,
1126
3926
  StepList,
3927
+ SubagentRow,
3928
+ ToolApprovalPrompt,
3929
+ ToolCallRow,
1127
3930
  UsageBadge,
1128
3931
  VaultCredentialStore2 as VaultCredentialStore,
3932
+ VirtualFileSystem,
1129
3933
  agentStateReducer,
3934
+ attachmentKindOf,
3935
+ attachmentRefusal,
3936
+ chatTitle,
1130
3937
  claimOAuthCallback,
1131
3938
  createAgent2 as createAgent,
3939
+ createFileTools,
1132
3940
  createInitialAgentState,
3941
+ createSubagentTool,
1133
3942
  createWebLLMModel2 as createWebLLMModel,
3943
+ defaultLabels,
3944
+ defineSkill,
1134
3945
  defineTool,
1135
3946
  describeMcpResult,
3947
+ downscaleImage,
3948
+ filterCommands,
3949
+ formatElapsed,
1136
3950
  isUnauthorizedError,
1137
3951
  isWebGPUAvailable2 as isWebGPUAvailable,
3952
+ loadSkillFromUrl,
3953
+ markReadOnly,
3954
+ mergeLabels,
3955
+ newChatId,
3956
+ noticesOf,
3957
+ parseSkillMarkdown,
3958
+ parseSlash,
1138
3959
  preloadWebLLMModel2 as preloadWebLLMModel,
1139
3960
  readCallbackParams,
3961
+ serveSubagentWorker,
1140
3962
  stripOAuthParams,
3963
+ supportsImages,
3964
+ supportsPdf,
1141
3965
  unloadWebLLMModel,
3966
+ usageLine,
1142
3967
  useAgent,
1143
3968
  useAgentContext,
3969
+ useChatHistory,
1144
3970
  useCredentials,
3971
+ useLabels,
1145
3972
  useMcp,
3973
+ useMcpServers,
1146
3974
  useOptionalAgentContext,
1147
- useWebLLMModel
3975
+ useSpeechToText,
3976
+ useVirtualFiles,
3977
+ useWebLLMModel,
3978
+ withAttachments
1148
3979
  };
1149
3980
  //# sourceMappingURL=index.js.map