@daex-dev/chat-ui 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4791 @@
1
+ import { createContext, memo, useState, useMemo, useCallback, useEffect, useRef, useId, useContext, useLayoutEffect, Fragment as Fragment$1 } from 'react';
2
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
+
4
+ // src/AdeChat.tsx
5
+
6
+ // src/composer/composerState.ts
7
+ function resolveComposerAction(input) {
8
+ const text = input.draft.trim();
9
+ const running = input.status === "running";
10
+ if (input.disabled) return { kind: "blocked", reason: "disabled" };
11
+ if (!input.ready) return { kind: "blocked", reason: "no_thread" };
12
+ if (!text.length && !input.hasAttachments) return { kind: "blocked", reason: "empty" };
13
+ if (running) {
14
+ if (input.allowSteer === false) return { kind: "blocked", reason: "steer_unsupported" };
15
+ return { kind: "steer", text };
16
+ }
17
+ return { kind: "send", text };
18
+ }
19
+ function resolveComposerState(input) {
20
+ const action = resolveComposerAction(input);
21
+ const running = input.status === "running";
22
+ return {
23
+ action,
24
+ canSubmit: action.kind !== "blocked",
25
+ canInterrupt: running && !input.disabled && input.ready,
26
+ running,
27
+ submitLabel: running ? "Steer" : "Send"
28
+ };
29
+ }
30
+ function blockedHint(reason) {
31
+ switch (reason) {
32
+ case "empty":
33
+ return null;
34
+ case "disabled":
35
+ return null;
36
+ case "no_thread":
37
+ return "Connecting\u2026";
38
+ case "steer_unsupported":
39
+ return "Stop the current response before sending another message.";
40
+ }
41
+ }
42
+ function resolveKeyIntent(input) {
43
+ if (input.isComposing) return "none";
44
+ if (input.key === "Escape") {
45
+ return input.running ? "interrupt" : "none";
46
+ }
47
+ if (input.key !== "Enter") return "none";
48
+ if (input.shiftKey) return "newline";
49
+ const commandModified = input.metaKey || input.ctrlKey;
50
+ const shouldSubmit = input.sendOnEnter ? !commandModified : commandModified;
51
+ return shouldSubmit ? "submit" : "newline";
52
+ }
53
+ function mergeAttachments(current, incoming = []) {
54
+ const merged = [];
55
+ const indexById = /* @__PURE__ */ new Map();
56
+ for (const attachment of [...current, ...incoming]) {
57
+ const existing = indexById.get(attachment.id);
58
+ if (existing === void 0) {
59
+ indexById.set(attachment.id, merged.length);
60
+ merged.push(attachment);
61
+ } else {
62
+ merged[existing] = attachment;
63
+ }
64
+ }
65
+ return merged;
66
+ }
67
+ function Composer({
68
+ onSend,
69
+ onSteer,
70
+ onInterrupt,
71
+ status = "idle",
72
+ ready = true,
73
+ disabled = false,
74
+ value,
75
+ onValueChange,
76
+ placeholder = "Send a message\u2026",
77
+ sendOnEnter = true,
78
+ autoFocus = false,
79
+ maxRows = 12,
80
+ onRequestAttachment,
81
+ attachments,
82
+ onAttachmentsChange,
83
+ modelRail,
84
+ actions,
85
+ error,
86
+ slashCommands,
87
+ slashCommandsLoading = false,
88
+ slashCommandsError = null,
89
+ onRetrySlashCommands,
90
+ className
91
+ }) {
92
+ const [internalDraft, setInternalDraft] = useState("");
93
+ const [internalAttachments, setInternalAttachments] = useState([]);
94
+ const [submitError, setSubmitError] = useState(null);
95
+ const inputRef = useRef(null);
96
+ const [cursorPosition, setCursorPosition] = useState(null);
97
+ const [selectedSlashIndex, setSelectedSlashIndex] = useState(0);
98
+ const [dismissedSlashQuery, setDismissedSlashQuery] = useState(null);
99
+ const slashMenuId = `adechat-slash-${useId()}`;
100
+ const draft = value ?? internalDraft;
101
+ const staged = useMemo(
102
+ () => mergeAttachments(attachments ?? internalAttachments),
103
+ [attachments, internalAttachments]
104
+ );
105
+ const stagedRef = useRef(staged);
106
+ stagedRef.current = staged;
107
+ const setDraft = useCallback(
108
+ (next) => {
109
+ if (value === void 0) setInternalDraft(next);
110
+ onValueChange?.(next);
111
+ },
112
+ [onValueChange, value]
113
+ );
114
+ const controlled = attachments !== void 0;
115
+ const setStaged = useCallback(
116
+ (next) => {
117
+ stagedRef.current = next;
118
+ if (!controlled) setInternalAttachments(next);
119
+ onAttachmentsChange?.(next);
120
+ },
121
+ [controlled, onAttachmentsChange]
122
+ );
123
+ const state = resolveComposerState({
124
+ draft,
125
+ status,
126
+ ready,
127
+ disabled,
128
+ allowSteer: Boolean(onSteer),
129
+ hasAttachments: staged.length > 0
130
+ });
131
+ const slashMatch = useMemo(() => {
132
+ const cursor = cursorPosition ?? draft.length;
133
+ const before = draft.slice(0, cursor);
134
+ const match = /^\/([^\s/]*)$/.exec(before);
135
+ return match ? { start: 0, query: match[1] ?? "" } : null;
136
+ }, [cursorPosition, draft]);
137
+ const slashSuggestions = useMemo(() => {
138
+ if (!slashMatch || !slashCommands) return [];
139
+ const query = slashMatch.query.toLocaleLowerCase();
140
+ return slashCommands.filter((command) => command.name.replace(/^\//, "").toLocaleLowerCase().startsWith(query)).slice(0, 10);
141
+ }, [slashCommands, slashMatch]);
142
+ const slashMenuOpen = Boolean(
143
+ slashMatch && dismissedSlashQuery !== slashMatch.query && (slashCommands !== void 0 || slashCommandsLoading || slashCommandsError)
144
+ );
145
+ useEffect(() => setSelectedSlashIndex(0), [slashMatch?.query]);
146
+ const selectSlashCommand = useCallback((command) => {
147
+ if (!slashMatch) return;
148
+ const cursor = inputRef.current?.selectionStart ?? draft.length;
149
+ const before = draft.slice(0, slashMatch.start);
150
+ const after = draft.slice(cursor);
151
+ const name = command.name.replace(/^\//, "");
152
+ const next = `${before}/${name} ${after}`;
153
+ const nextCursor = before.length + name.length + 2;
154
+ setDraft(next);
155
+ setCursorPosition(nextCursor);
156
+ setDismissedSlashQuery(null);
157
+ requestAnimationFrame(() => {
158
+ const input = inputRef.current;
159
+ input?.focus();
160
+ input?.setSelectionRange(nextCursor, nextCursor);
161
+ });
162
+ }, [draft, setDraft, slashMatch]);
163
+ useEffect(() => {
164
+ const node = inputRef.current;
165
+ if (!node) return;
166
+ node.style.height = "auto";
167
+ const lineHeight = Number.parseFloat(getComputedStyle(node).lineHeight) || 20;
168
+ node.style.height = `${Math.min(node.scrollHeight, lineHeight * maxRows)}px`;
169
+ }, [draft, maxRows]);
170
+ const submit = useCallback(async () => {
171
+ const action = state.action;
172
+ if (action.kind === "blocked") return;
173
+ const input = {
174
+ text: action.text,
175
+ ...staged.length ? { attachments: staged } : {}
176
+ };
177
+ setDraft("");
178
+ setStaged([]);
179
+ setSubmitError(null);
180
+ const restore = () => {
181
+ setDraft(action.text);
182
+ setStaged(mergeAttachments(staged, stagedRef.current));
183
+ };
184
+ try {
185
+ if (action.kind === "steer" && onSteer) await onSteer(input);
186
+ else if (await onSend(input) === false) restore();
187
+ } catch (cause) {
188
+ restore();
189
+ setSubmitError(cause instanceof Error ? cause.message : String(cause));
190
+ }
191
+ }, [onSend, onSteer, setDraft, setStaged, staged, state.action]);
192
+ const interrupt = useCallback(async () => {
193
+ if (!onInterrupt || !state.canInterrupt) return;
194
+ await onInterrupt();
195
+ }, [onInterrupt, state.canInterrupt]);
196
+ const handleKeyDown = useCallback(
197
+ (event) => {
198
+ if (slashMenuOpen) {
199
+ if (event.key === "ArrowDown" && slashSuggestions.length > 0) {
200
+ event.preventDefault();
201
+ setSelectedSlashIndex((current) => (current + 1) % slashSuggestions.length);
202
+ return;
203
+ }
204
+ if (event.key === "ArrowUp" && slashSuggestions.length > 0) {
205
+ event.preventDefault();
206
+ setSelectedSlashIndex((current) => (current - 1 + slashSuggestions.length) % slashSuggestions.length);
207
+ return;
208
+ }
209
+ if ((event.key === "Enter" || event.key === "Tab") && slashSuggestions.length > 0) {
210
+ event.preventDefault();
211
+ selectSlashCommand(slashSuggestions[selectedSlashIndex] ?? slashSuggestions[0]);
212
+ return;
213
+ }
214
+ if (event.key === "Escape") {
215
+ event.preventDefault();
216
+ setDismissedSlashQuery(slashMatch?.query ?? "");
217
+ return;
218
+ }
219
+ }
220
+ const intent = resolveKeyIntent({
221
+ key: event.key,
222
+ shiftKey: event.shiftKey,
223
+ metaKey: event.metaKey,
224
+ ctrlKey: event.ctrlKey,
225
+ // React's synthetic event exposes composition state on the native event.
226
+ isComposing: event.nativeEvent.isComposing === true,
227
+ sendOnEnter,
228
+ running: state.running,
229
+ hasDraft: draft.trim().length > 0
230
+ });
231
+ if (intent === "submit") {
232
+ event.preventDefault();
233
+ void submit();
234
+ return;
235
+ }
236
+ if (intent === "interrupt" && onInterrupt) {
237
+ event.preventDefault();
238
+ void interrupt();
239
+ }
240
+ },
241
+ [draft, interrupt, onInterrupt, sendOnEnter, slashMatch, slashMenuOpen, slashSuggestions, selectedSlashIndex, selectSlashCommand, state.running, submit]
242
+ );
243
+ const attach = useCallback(async () => {
244
+ if (!onRequestAttachment) return;
245
+ const next = await onRequestAttachment();
246
+ if (!next || next.length === 0) return;
247
+ setStaged(mergeAttachments(stagedRef.current, next));
248
+ }, [onRequestAttachment, setStaged]);
249
+ const remove = useCallback(
250
+ (id) => setStaged(stagedRef.current.filter((item) => item.id !== id)),
251
+ [setStaged]
252
+ );
253
+ const hint = state.action.kind === "blocked" ? blockedHint(state.action.reason) : null;
254
+ const shownError = error ?? submitError;
255
+ return /* @__PURE__ */ jsxs("div", { className: ["adechat-composer", className].filter(Boolean).join(" "), children: [
256
+ /* @__PURE__ */ jsxs("div", { className: "adechat-composer-surface", children: [
257
+ staged.length ? /* @__PURE__ */ jsx("div", { className: "adechat-attachments", children: staged.map((attachment) => /* @__PURE__ */ jsxs(
258
+ "button",
259
+ {
260
+ type: "button",
261
+ className: "adechat-attachment",
262
+ onClick: () => remove(attachment.id),
263
+ "aria-label": `Remove ${attachment.name}`,
264
+ children: [
265
+ attachment.name,
266
+ " \xD7"
267
+ ]
268
+ },
269
+ attachment.id
270
+ )) }) : null,
271
+ slashMenuOpen ? /* @__PURE__ */ jsxs("div", { className: "adechat-slash-menu", id: slashMenuId, role: "listbox", "aria-label": "Slash commands", children: [
272
+ slashCommandsLoading && slashCommands === null ? /* @__PURE__ */ jsx("p", { className: "adechat-slash-state", children: "Loading commands\u2026" }) : null,
273
+ slashCommandsError ? /* @__PURE__ */ jsxs("div", { className: "adechat-slash-error", role: "alert", children: [
274
+ /* @__PURE__ */ jsx("span", { children: "Couldn\u2019t load slash commands." }),
275
+ onRetrySlashCommands ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", onClick: () => void onRetrySlashCommands(), disabled: slashCommandsLoading, children: "Retry" }) : null
276
+ ] }) : null,
277
+ slashSuggestions.map((command, index) => {
278
+ const name = command.name.replace(/^\//, "");
279
+ const optionId = `${slashMenuId}-${index}`;
280
+ return /* @__PURE__ */ jsxs(
281
+ "button",
282
+ {
283
+ type: "button",
284
+ role: "option",
285
+ id: optionId,
286
+ "aria-selected": index === selectedSlashIndex,
287
+ className: "adechat-slash-option",
288
+ onMouseDown: (event) => event.preventDefault(),
289
+ onClick: () => selectSlashCommand(command),
290
+ children: [
291
+ /* @__PURE__ */ jsxs("span", { children: [
292
+ "/",
293
+ name
294
+ ] }),
295
+ command.argumentHint ? /* @__PURE__ */ jsx("small", { children: command.argumentHint }) : null,
296
+ command.description ? /* @__PURE__ */ jsx("span", { className: "adechat-slash-description", children: command.description }) : null
297
+ ]
298
+ },
299
+ `${command.name}-${index}`
300
+ );
301
+ }),
302
+ !slashCommandsLoading && !slashCommandsError && slashCommands !== null && slashSuggestions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "adechat-slash-state", children: "No matching commands." }) : null
303
+ ] }) : null,
304
+ /* @__PURE__ */ jsx(
305
+ "textarea",
306
+ {
307
+ ref: inputRef,
308
+ className: "adechat-composer-input",
309
+ rows: 1,
310
+ value: draft,
311
+ placeholder,
312
+ disabled,
313
+ autoFocus,
314
+ onChange: (event) => {
315
+ setDraft(event.target.value);
316
+ setCursorPosition(event.currentTarget.selectionStart);
317
+ setDismissedSlashQuery(null);
318
+ },
319
+ onKeyDown: handleKeyDown,
320
+ onClick: (event) => setCursorPosition(event.currentTarget.selectionStart),
321
+ onKeyUp: (event) => setCursorPosition(event.currentTarget.selectionStart),
322
+ "aria-label": "Message",
323
+ ...slashMenuOpen ? {
324
+ "aria-autocomplete": "list",
325
+ "aria-controls": slashMenuId,
326
+ "aria-expanded": true,
327
+ ...slashSuggestions[selectedSlashIndex] ? { "aria-activedescendant": `${slashMenuId}-${selectedSlashIndex}` } : {}
328
+ } : {}
329
+ }
330
+ ),
331
+ /* @__PURE__ */ jsxs("div", { className: "adechat-composer-actions", children: [
332
+ onRequestAttachment ? /* @__PURE__ */ jsx(
333
+ "button",
334
+ {
335
+ type: "button",
336
+ className: "adechat-button adechat-button-icon",
337
+ onClick: () => void attach(),
338
+ disabled,
339
+ "aria-label": "Add attachment",
340
+ children: "+"
341
+ }
342
+ ) : null,
343
+ modelRail ? /* @__PURE__ */ jsx("div", { className: "adechat-composer-rail", children: modelRail }) : null,
344
+ actions,
345
+ /* @__PURE__ */ jsx("div", { className: "adechat-composer-spacer" }),
346
+ hint ? /* @__PURE__ */ jsx("span", { className: "adechat-composer-hint", children: hint }) : null,
347
+ state.canInterrupt && onInterrupt ? /* @__PURE__ */ jsx(
348
+ "button",
349
+ {
350
+ type: "button",
351
+ className: "adechat-button",
352
+ "data-variant": "danger",
353
+ onClick: () => void interrupt(),
354
+ children: "Stop"
355
+ }
356
+ ) : null,
357
+ /* @__PURE__ */ jsx(
358
+ "button",
359
+ {
360
+ type: "button",
361
+ className: "adechat-button",
362
+ "data-variant": "primary",
363
+ onClick: () => void submit(),
364
+ disabled: !state.canSubmit,
365
+ children: state.submitLabel
366
+ }
367
+ )
368
+ ] })
369
+ ] }),
370
+ shownError ? /* @__PURE__ */ jsx("div", { className: "adechat-composer-error", children: shownError }) : null
371
+ ] });
372
+ }
373
+ function QueueStrip({ queue, refreshKey }) {
374
+ const [items, setItems] = useState([]);
375
+ const [loading, setLoading] = useState(false);
376
+ const [loaded, setLoaded] = useState(false);
377
+ const [error, setError] = useState(null);
378
+ const [busyId, setBusyId] = useState(null);
379
+ const [editingId, setEditingId] = useState(null);
380
+ const [editText, setEditText] = useState("");
381
+ const refresh = useCallback(async () => {
382
+ if (typeof queue?.list !== "function") return;
383
+ setLoading(true);
384
+ try {
385
+ setItems([...await queue.list()]);
386
+ setError(null);
387
+ setLoaded(true);
388
+ } catch (cause) {
389
+ setError(cause instanceof Error ? cause.message : String(cause));
390
+ setLoaded(false);
391
+ } finally {
392
+ setLoading(false);
393
+ }
394
+ }, [queue]);
395
+ useEffect(() => {
396
+ void refresh();
397
+ }, [refresh, refreshKey]);
398
+ const act = async (id, action) => {
399
+ if (!action) return;
400
+ setBusyId(id);
401
+ setError(null);
402
+ try {
403
+ await action();
404
+ if (editingId === id) setEditingId(null);
405
+ await refresh();
406
+ } catch (cause) {
407
+ setError(cause instanceof Error ? cause.message : String(cause));
408
+ } finally {
409
+ setBusyId(null);
410
+ }
411
+ };
412
+ if (typeof queue?.list !== "function") return null;
413
+ return /* @__PURE__ */ jsxs("section", { className: "adechat-queue", "aria-label": "Queued messages", children: [
414
+ loading && !loaded ? /* @__PURE__ */ jsx("p", { className: "adechat-queue-state", children: "Loading queued messages\u2026" }) : null,
415
+ error ? /* @__PURE__ */ jsxs("div", { className: "adechat-queue-error", role: "alert", children: [
416
+ /* @__PURE__ */ jsxs("span", { children: [
417
+ "Couldn\u2019t load or update the queue: ",
418
+ error
419
+ ] }),
420
+ /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", onClick: () => void refresh(), disabled: loading, children: "Retry" })
421
+ ] }) : null,
422
+ loaded && items.length > 0 ? /* @__PURE__ */ jsx("ol", { className: "adechat-queue-list", children: items.map((item, index) => {
423
+ const busy = busyId === item.id;
424
+ const editing = editingId === item.id;
425
+ const canMove = typeof queue.move === "function" && !item.dispatched;
426
+ return /* @__PURE__ */ jsxs("li", { className: "adechat-queue-item", children: [
427
+ editing ? /* @__PURE__ */ jsxs(
428
+ "form",
429
+ {
430
+ className: "adechat-queue-edit",
431
+ onSubmit: (event) => {
432
+ event.preventDefault();
433
+ void act(item.id, queue.edit ? () => queue.edit(item.id, editText) : void 0);
434
+ },
435
+ children: [
436
+ /* @__PURE__ */ jsx("input", { "aria-label": "Edit queued message", value: editText, onChange: (event) => setEditText(event.target.value), disabled: busy }),
437
+ /* @__PURE__ */ jsx("button", { type: "submit", className: "adechat-button", disabled: busy || !queue.edit, children: "Save" }),
438
+ /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", onClick: () => setEditingId(null), disabled: busy, children: "Cancel edit" })
439
+ ]
440
+ }
441
+ ) : /* @__PURE__ */ jsx("span", { className: "adechat-queue-text", children: item.text || "Attachment message" }),
442
+ !editing ? /* @__PURE__ */ jsxs("div", { className: "adechat-queue-actions", children: [
443
+ canMove ? /* @__PURE__ */ jsxs(Fragment, { children: [
444
+ /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", "aria-label": `Move message ${index + 1} up`, disabled: busy || index === 0, onClick: () => void act(item.id, () => queue.move(item.id, index - 1)), children: "\u2191" }),
445
+ /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", "aria-label": `Move message ${index + 1} down`, disabled: busy || index === items.length - 1, onClick: () => void act(item.id, () => queue.move(item.id, index + 1)), children: "\u2193" })
446
+ ] }) : null,
447
+ !item.dispatched && queue.edit ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", disabled: busy, onClick: () => {
448
+ setEditingId(item.id);
449
+ setEditText(item.text);
450
+ }, children: "Edit" }) : null,
451
+ !item.dispatched && queue.dispatch ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", disabled: busy, onClick: () => void act(item.id, () => queue.dispatch(item.id)), children: "Send now" }) : null,
452
+ item.dispatched && queue.cancelDispatched ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", disabled: busy, onClick: () => void act(item.id, () => queue.cancelDispatched(item.id)), children: "Cancel send" }) : null,
453
+ queue.cancel ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", disabled: busy, onClick: () => void act(item.id, () => queue.cancel(item.id)), children: "Cancel" }) : null
454
+ ] }) : null
455
+ ] }, item.id);
456
+ }) }) : null
457
+ ] });
458
+ }
459
+
460
+ // src/models/modelSelection.ts
461
+ function readThreadModelSelection(value) {
462
+ if (!value || typeof value !== "object") return null;
463
+ const record2 = value;
464
+ if (typeof record2.modelId !== "string" || !record2.modelId) return null;
465
+ const info = { modelId: record2.modelId };
466
+ if (typeof record2.displayName === "string" || record2.displayName === null) {
467
+ info.displayName = record2.displayName;
468
+ }
469
+ if (typeof record2.provider === "string" && record2.provider) info.provider = record2.provider;
470
+ return info;
471
+ }
472
+
473
+ // src/activity/toolIdentity.ts
474
+ function parseToolIdentity(name) {
475
+ const trimmed = typeof name === "string" ? name.trim() : "";
476
+ if (trimmed.startsWith("mcp__")) {
477
+ const rest = trimmed.slice("mcp__".length);
478
+ const split2 = rest.indexOf("__");
479
+ if (split2 > 0 && split2 + 2 < rest.length) {
480
+ return { server: rest.slice(0, split2), tool: rest.slice(split2 + 2) };
481
+ }
482
+ return { server: null, tool: trimmed };
483
+ }
484
+ if (trimmed.startsWith("mcp:")) {
485
+ const rest = trimmed.slice("mcp:".length);
486
+ const split2 = rest.indexOf(":");
487
+ if (split2 > 0 && split2 + 1 < rest.length) {
488
+ return { server: rest.slice(0, split2), tool: rest.slice(split2 + 1) };
489
+ }
490
+ return { server: null, tool: trimmed };
491
+ }
492
+ const split = trimmed.indexOf(":");
493
+ if (split > 0 && split + 1 < trimmed.length) {
494
+ return { server: trimmed.slice(0, split), tool: trimmed.slice(split + 1) };
495
+ }
496
+ return { server: null, tool: trimmed };
497
+ }
498
+
499
+ // src/transcript/transcriptRows.ts
500
+ function readRecord(value) {
501
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
502
+ }
503
+ function readPendingInputOptions(value) {
504
+ if (!Array.isArray(value)) return void 0;
505
+ return value.flatMap((entry) => {
506
+ const record2 = readRecord(entry);
507
+ if (typeof record2?.label !== "string" || typeof record2.value !== "string") return [];
508
+ return [{
509
+ label: record2.label,
510
+ value: record2.value,
511
+ ...typeof record2.description === "string" ? { description: record2.description } : {},
512
+ ...record2.recommended === true ? { recommended: true } : {},
513
+ ...typeof record2.preview === "string" ? { preview: record2.preview } : {},
514
+ ...record2.previewFormat === "markdown" || record2.previewFormat === "html" ? { previewFormat: record2.previewFormat } : {}
515
+ }];
516
+ });
517
+ }
518
+ function readPendingInputQuestions(value) {
519
+ if (!Array.isArray(value)) return void 0;
520
+ return value.flatMap((entry) => {
521
+ const record2 = readRecord(entry);
522
+ if (typeof record2?.id !== "string" || typeof record2.question !== "string") return [];
523
+ const options = readPendingInputOptions(record2.options);
524
+ return [{
525
+ id: record2.id,
526
+ question: record2.question,
527
+ ...typeof record2.header === "string" ? { header: record2.header } : {},
528
+ ...options ? { options } : {},
529
+ ...record2.multiSelect === true ? { multiSelect: true } : {},
530
+ ...typeof record2.allowsFreeform === "boolean" ? { allowsFreeform: record2.allowsFreeform } : {},
531
+ ...record2.isSecret === true ? { isSecret: true } : {},
532
+ ...typeof record2.defaultAssumption === "string" || record2.defaultAssumption === null ? { defaultAssumption: record2.defaultAssumption } : {},
533
+ ...typeof record2.impact === "string" || record2.impact === null ? { impact: record2.impact } : {}
534
+ }];
535
+ });
536
+ }
537
+ function approvalRequestKind(event) {
538
+ if (typeof event.requestKind === "string" && event.requestKind) return event.requestKind;
539
+ const kind = readRecord(readRecord(event.detail)?.request)?.kind;
540
+ return typeof kind === "string" && kind ? kind : void 0;
541
+ }
542
+ function pendingInputFields(event) {
543
+ const envelope = readRecord(event);
544
+ const detail = readRecord(envelope?.detail);
545
+ const request = readRecord(detail?.request) ?? readRecord(detail?.pendingInput) ?? detail;
546
+ const value = (key) => envelope?.[key] ?? request?.[key] ?? detail?.[key];
547
+ const fields = {};
548
+ const requestId = value("requestId");
549
+ const title = value("title");
550
+ const source = value("source");
551
+ const questions = readPendingInputQuestions(value("questions"));
552
+ const options = readPendingInputOptions(value("options"));
553
+ const providerMetadata = readRecord(value("providerMetadata"));
554
+ if (typeof requestId === "string" && requestId) fields.requestId = requestId;
555
+ if (typeof title === "string" || title === null) fields.title = title;
556
+ if (typeof source === "string") fields.source = source;
557
+ if (questions) fields.questions = questions;
558
+ if (options) fields.options = options;
559
+ if (typeof value("allowsFreeform") === "boolean") fields.allowsFreeform = value("allowsFreeform");
560
+ if (typeof value("canProceedWithoutAnswer") === "boolean") fields.canProceedWithoutAnswer = value("canProceedWithoutAnswer");
561
+ if (providerMetadata) fields.providerMetadata = providerMetadata;
562
+ return fields;
563
+ }
564
+ function eventHasPayload(value) {
565
+ if (value == null) return false;
566
+ if (typeof value === "string") return value.trim().length > 0;
567
+ if (typeof value === "number" || typeof value === "boolean") return true;
568
+ if (Array.isArray(value)) return value.length > 0;
569
+ if (typeof value === "object") return Object.keys(value).length > 0;
570
+ return false;
571
+ }
572
+ function formatStructuredValue(value) {
573
+ if (typeof value === "string") return value;
574
+ try {
575
+ return JSON.stringify(value, null, 2);
576
+ } catch {
577
+ return String(value);
578
+ }
579
+ }
580
+ function mergeStreamingText(existing, incoming) {
581
+ if (!existing.length) return incoming;
582
+ if (!incoming.length) return existing;
583
+ if (incoming.startsWith(existing)) return incoming;
584
+ return `${existing}${incoming}`;
585
+ }
586
+ function buildRenderKey(envelope, sequence) {
587
+ return `${envelope.sessionId}:${sequence}:${envelope.timestamp}`;
588
+ }
589
+ function buildTextRenderKey(event, envelope, sequence) {
590
+ const messageId = event.messageId?.trim();
591
+ if (messageId) return `${envelope.sessionId}:text:${messageId}:${sequence}`;
592
+ return buildRenderKey(envelope, sequence);
593
+ }
594
+ function getTextIdentity(event) {
595
+ const messageId = event.messageId?.trim();
596
+ return messageId?.length ? messageId : null;
597
+ }
598
+ function turnAndItemMatch(a, b) {
599
+ const aTurnId = a.turnId ?? null;
600
+ const bTurnId = b.turnId ?? null;
601
+ if (!aTurnId || !bTurnId || aTurnId !== bTurnId) return false;
602
+ const aItemId = a.itemId ?? null;
603
+ const bItemId = b.itemId ?? null;
604
+ return !aItemId || !bItemId || aItemId === bItemId;
605
+ }
606
+ function shouldMergeTextRows(previous, next) {
607
+ const previousIdentity = getTextIdentity(previous);
608
+ const nextIdentity = getTextIdentity(next);
609
+ if (previousIdentity || nextIdentity) {
610
+ if (previousIdentity && nextIdentity) return previousIdentity === nextIdentity;
611
+ return turnAndItemMatch(previous, next);
612
+ }
613
+ if (turnAndItemMatch(previous, next)) return true;
614
+ return !previous.turnId && !next.turnId && !previous.itemId && !next.itemId;
615
+ }
616
+ function buildCollapseKey(prefix, event, suffix) {
617
+ const parts = [prefix];
618
+ if (event.turnId) parts.push(event.turnId);
619
+ const stableItemId = event.logicalItemId ?? event.itemId;
620
+ if (stableItemId) parts.push(stableItemId);
621
+ return parts.join("::");
622
+ }
623
+ function isGenericToolIdentifier(value) {
624
+ const normalized = value?.trim().toLowerCase() ?? "";
625
+ return !normalized.length || normalized === "other" || normalized === "tool";
626
+ }
627
+ function readToolTitle(value) {
628
+ const record2 = readRecord(value);
629
+ if (!record2) return null;
630
+ const title = typeof record2.title === "string" ? record2.title.trim() : "";
631
+ return title.length ? title : null;
632
+ }
633
+ function resolveToolName(tool, payload) {
634
+ const titleFallback = readToolTitle(payload);
635
+ return isGenericToolIdentifier(tool) && titleFallback ? titleFallback : tool;
636
+ }
637
+ function toolIdentityOf(tool, mcp) {
638
+ const server = typeof mcp?.server === "string" ? mcp.server.trim() : "";
639
+ const name = typeof mcp?.tool === "string" ? mcp.tool.trim() : "";
640
+ if (server && name) return { server, tool: name };
641
+ return parseToolIdentity(tool);
642
+ }
643
+ function readResourceLinks(value) {
644
+ if (!Array.isArray(value)) return void 0;
645
+ const links = [];
646
+ for (const entry of value) {
647
+ const record2 = readRecord(entry);
648
+ const uri = typeof record2?.uri === "string" ? record2.uri.trim() : "";
649
+ if (!record2 || !uri) continue;
650
+ const link = { uri };
651
+ if (typeof record2.name === "string" && record2.name) link.name = record2.name;
652
+ if (typeof record2.title === "string" && record2.title) link.title = record2.title;
653
+ if (typeof record2.mimeType === "string" && record2.mimeType) link.mimeType = record2.mimeType;
654
+ links.push(link);
655
+ }
656
+ return links.length ? links : void 0;
657
+ }
658
+ var RENDERED_TYPES = /* @__PURE__ */ new Set([
659
+ "user_message",
660
+ "text",
661
+ "reasoning",
662
+ "tool_call",
663
+ "tool_result",
664
+ "error",
665
+ "status",
666
+ "approval_request",
667
+ "pending_input_resolved"
668
+ ]);
669
+ var APPROVAL_RESOLUTION_STATE = {
670
+ accepted: "accepted",
671
+ declined: "rejected",
672
+ cancelled: "cancelled"
673
+ };
674
+ function readTurnId(event) {
675
+ const value = event.turnId;
676
+ return typeof value === "string" && value ? value : null;
677
+ }
678
+ function turnEndingOf(event) {
679
+ if (!event) return null;
680
+ if (event.type === "done") return { turnId: readTurnId(event) };
681
+ if (event.type === "status") {
682
+ const turnStatus = event.turnStatus;
683
+ if (turnStatus === "completed" || turnStatus === "failed" || turnStatus === "interrupted") {
684
+ return { turnId: readTurnId(event) };
685
+ }
686
+ }
687
+ return null;
688
+ }
689
+ function resolveRestoredApprovalState(input) {
690
+ const held = input.orphanResolutions.get(input.itemId) ?? (input.logicalItemId ? input.orphanResolutions.get(input.logicalItemId) : void 0);
691
+ return held ?? "pending";
692
+ }
693
+ function isRenderedEvent(event) {
694
+ return event ? RENDERED_TYPES.has(event.type) : false;
695
+ }
696
+ var RowCollapser = class {
697
+ raw = [];
698
+ /** collapseKey -> index in `raw`, so a result can find its call. */
699
+ toolRowIndex = /* @__PURE__ */ new Map();
700
+ /** itemId AND logicalItemId -> index, so a resolution can find its request. */
701
+ approvalRowIndex = /* @__PURE__ */ new Map();
702
+ /**
703
+ * Resolutions that arrived before the request they settle.
704
+ *
705
+ * The engine emits the request first and `mergeHistoryWithBuffer` sorts by
706
+ * `sequence`, so this needs a runtime that renumbers — but when it happens,
707
+ * dropping the resolution left a live card with working buttons on a request
708
+ * that is already settled. Held here and applied when the request lands.
709
+ */
710
+ orphanResolutions = /* @__PURE__ */ new Map();
711
+ /**
712
+ * Item ids of rows built from `restore()` rather than from an envelope.
713
+ *
714
+ * A turn ending never expires these (see `resolveRestoredApprovalState`).
715
+ * A single-pass collapse got that for free by restoring after the walk; an
716
+ * incremental one restores first and then keeps walking, so it has to say so.
717
+ */
718
+ restoredIds = /* @__PURE__ */ new Set();
719
+ /** Envelopes consumed so far: the positional fallback for `sequence`. */
720
+ position = 0;
721
+ /** Lowest `raw` index changed since the last `takeDirty()`. */
722
+ dirtyFrom = Number.POSITIVE_INFINITY;
723
+ mark(index) {
724
+ if (index < this.dirtyFrom) this.dirtyFrom = index;
725
+ }
726
+ set(index, row) {
727
+ this.raw[index] = row;
728
+ this.mark(index);
729
+ }
730
+ push(row) {
731
+ const index = this.raw.length;
732
+ this.raw.push(row);
733
+ this.mark(index);
734
+ return index;
735
+ }
736
+ /** The lowest changed index, and reset. Infinity when nothing changed. */
737
+ takeDirty() {
738
+ const dirty = this.dirtyFrom;
739
+ this.dirtyFrom = Number.POSITIVE_INFINITY;
740
+ return dirty;
741
+ }
742
+ /**
743
+ * Mark every still-pending approval of a finished turn `expired`.
744
+ *
745
+ * A turn ending settles its approvals whether or not anyone answered them: the
746
+ * provider is gone and a button press would now throw. An ending that names no
747
+ * turn expires every pending row, because there is nothing left running that
748
+ * could still be waiting on one.
749
+ */
750
+ expirePendingApprovals(turnId) {
751
+ this.raw.forEach((row, index) => {
752
+ const event = row.event;
753
+ if (event.type !== "approval" || event.state !== "pending") return;
754
+ if (this.restoredIds.has(event.id)) return;
755
+ if (turnId !== null && event.turnId !== null && event.turnId !== turnId) return;
756
+ this.set(index, { ...row, event: { ...event, state: "expired" } });
757
+ });
758
+ }
759
+ append(envelopes) {
760
+ for (const envelope of envelopes) {
761
+ this.step(envelope, this.position);
762
+ this.position += 1;
763
+ }
764
+ }
765
+ step(envelope, position) {
766
+ const rows = this.raw;
767
+ const event = envelope.event;
768
+ if (this.approvalRowIndex.size > 0) {
769
+ const ending = turnEndingOf(event);
770
+ if (ending) this.expirePendingApprovals(ending.turnId);
771
+ }
772
+ if (!isRenderedEvent(event)) return;
773
+ const sequence = envelope.sequence ?? position;
774
+ if (event.type === "approval_request") {
775
+ const row = {
776
+ type: "approval",
777
+ id: event.itemId,
778
+ kind: event.kind,
779
+ description: event.description,
780
+ turnId: event.turnId ?? null,
781
+ state: "pending"
782
+ };
783
+ const requestKind = approvalRequestKind(event);
784
+ if (requestKind !== void 0) row.requestKind = requestKind;
785
+ if (event.detail !== void 0) row.detail = event.detail;
786
+ Object.assign(row, pendingInputFields(event));
787
+ const held = this.orphanResolutions.get(event.itemId) ?? (event.logicalItemId ? this.orphanResolutions.get(event.logicalItemId) : void 0);
788
+ if (held) {
789
+ row.state = held;
790
+ this.orphanResolutions.delete(event.itemId);
791
+ if (event.logicalItemId) this.orphanResolutions.delete(event.logicalItemId);
792
+ }
793
+ const existing = this.approvalRowIndex.get(event.itemId);
794
+ if (existing !== void 0 && rows[existing]) {
795
+ const previous = rows[existing].event;
796
+ const state = previous.type === "approval" ? previous.state : "pending";
797
+ this.restoredIds.delete(event.itemId);
798
+ this.set(existing, {
799
+ ...rows[existing],
800
+ timestamp: envelope.timestamp,
801
+ event: { ...row, state }
802
+ });
803
+ return;
804
+ }
805
+ this.approvalRowIndex.set(event.itemId, rows.length);
806
+ if (event.logicalItemId) this.approvalRowIndex.set(event.logicalItemId, rows.length);
807
+ this.push({ key: `approval:${event.itemId}`, timestamp: envelope.timestamp, event: row });
808
+ return;
809
+ }
810
+ if (event.type === "pending_input_resolved") {
811
+ const index = this.approvalRowIndex.get(event.itemId) ?? (event.logicalItemId ? this.approvalRowIndex.get(event.logicalItemId) : void 0);
812
+ const row = index !== void 0 ? rows[index] : void 0;
813
+ const state = APPROVAL_RESOLUTION_STATE[event.resolution];
814
+ if (!state) return;
815
+ if (index === void 0 || !row || row.event.type !== "approval") {
816
+ this.orphanResolutions.set(event.itemId, state);
817
+ if (event.logicalItemId) this.orphanResolutions.set(event.logicalItemId, state);
818
+ return;
819
+ }
820
+ this.set(index, { ...row, timestamp: envelope.timestamp, event: { ...row.event, state } });
821
+ return;
822
+ }
823
+ if (event.type === "text") {
824
+ const lastIndex = rows.length - 1;
825
+ const previous = rows[lastIndex];
826
+ if (previous && previous.event.type === "text" && shouldMergeTextRows(previous.event, event)) {
827
+ this.set(lastIndex, {
828
+ key: previous.key,
829
+ timestamp: envelope.timestamp,
830
+ event: {
831
+ ...previous.event,
832
+ text: mergeStreamingText(previous.event.text, event.text)
833
+ }
834
+ });
835
+ return;
836
+ }
837
+ this.push({
838
+ key: buildTextRenderKey(event, envelope, sequence),
839
+ timestamp: envelope.timestamp,
840
+ event
841
+ });
842
+ return;
843
+ }
844
+ if (event.type === "tool_call") {
845
+ const collapseKey = buildCollapseKey("tool", event);
846
+ const chip = {
847
+ type: "tool_chip",
848
+ id: collapseKey,
849
+ tool: resolveToolName(event.tool, event.args),
850
+ identity: toolIdentityOf(event.tool, event.mcp),
851
+ args: event.args,
852
+ status: "running",
853
+ turnId: event.turnId ?? null
854
+ };
855
+ const existing = this.toolRowIndex.get(collapseKey);
856
+ if (existing !== void 0 && rows[existing]) {
857
+ this.set(existing, { ...rows[existing], timestamp: envelope.timestamp, event: chip });
858
+ return;
859
+ }
860
+ this.toolRowIndex.set(collapseKey, rows.length);
861
+ this.push({ key: collapseKey, timestamp: envelope.timestamp, event: chip });
862
+ return;
863
+ }
864
+ if (event.type === "tool_result") {
865
+ const collapseKey = buildCollapseKey("tool", event);
866
+ const index = this.toolRowIndex.get(collapseKey);
867
+ const previousChip = index !== void 0 && rows[index]?.event.type === "tool_chip" ? rows[index].event : null;
868
+ const tool = resolveToolName(event.tool, event.result) || previousChip?.tool || event.tool;
869
+ const chip = {
870
+ type: "tool_chip",
871
+ id: collapseKey,
872
+ tool,
873
+ identity: event.mcp || !previousChip ? toolIdentityOf(event.tool || tool, event.mcp) : previousChip.identity,
874
+ args: previousChip?.args,
875
+ result: event.result,
876
+ status: event.status ?? "completed",
877
+ turnId: event.turnId ?? previousChip?.turnId ?? null
878
+ };
879
+ const resourceLinks = readResourceLinks(event.resourceLinks) ?? previousChip?.resourceLinks;
880
+ if (resourceLinks) chip.resourceLinks = resourceLinks;
881
+ if (index !== void 0 && rows[index]) {
882
+ this.set(index, { ...rows[index], timestamp: envelope.timestamp, event: chip });
883
+ return;
884
+ }
885
+ this.toolRowIndex.set(collapseKey, rows.length);
886
+ this.push({ key: collapseKey, timestamp: envelope.timestamp, event: chip });
887
+ return;
888
+ }
889
+ this.push({
890
+ key: buildRenderKey(envelope, sequence),
891
+ timestamp: envelope.timestamp,
892
+ event
893
+ });
894
+ }
895
+ /**
896
+ * Put a restored approval row where its timestamp says it belongs.
897
+ *
898
+ * Appending it instead pinned it below every message that streamed in later,
899
+ * for the life of the mount: a card answered ten messages ago still read as
900
+ * the newest thing in the transcript. Only the restored rows move; the
901
+ * envelope rows keep the order `sortEnvelopes` gave them, which is by
902
+ * `sequence` and not by clock. Every stored index at or past the insertion
903
+ * point shifts by one, because later envelopes still look rows up by index.
904
+ */
905
+ insertByTimestamp(row) {
906
+ const index = this.raw.findIndex((existing) => existing.timestamp > row.timestamp);
907
+ if (index === -1) return this.push(row);
908
+ this.raw.splice(index, 0, row);
909
+ for (const map of [this.toolRowIndex, this.approvalRowIndex]) {
910
+ for (const [key, value] of map) if (value >= index) map.set(key, value + 1);
911
+ }
912
+ this.mark(index);
913
+ return index;
914
+ }
915
+ /**
916
+ * Rows built directly from the request shape — no envelope is fabricated for
917
+ * them. An envelope needs a `sessionId` and a `sequence`, and a caller that
918
+ * has neither can only invent them; an invented sequence then collides with
919
+ * the first real envelopes that arrive.
920
+ */
921
+ restore(pendingApprovals, restoredAt) {
922
+ const at = restoredAt ?? this.raw[this.raw.length - 1]?.timestamp ?? (/* @__PURE__ */ new Date(0)).toISOString();
923
+ for (const request of pendingApprovals) {
924
+ if (!request.itemId) continue;
925
+ if (this.approvalRowIndex.has(request.itemId)) continue;
926
+ if (request.logicalItemId && this.approvalRowIndex.has(request.logicalItemId)) continue;
927
+ const row = {
928
+ type: "approval",
929
+ id: request.itemId,
930
+ kind: request.kind,
931
+ description: request.description,
932
+ turnId: request.turnId ?? null,
933
+ state: resolveRestoredApprovalState({
934
+ itemId: request.itemId,
935
+ ...request.logicalItemId ? { logicalItemId: request.logicalItemId } : {},
936
+ orphanResolutions: this.orphanResolutions
937
+ })
938
+ };
939
+ if (request.requestKind !== void 0) row.requestKind = request.requestKind;
940
+ if (request.detail !== void 0) row.detail = request.detail;
941
+ if (request.requestId !== void 0) row.requestId = request.requestId;
942
+ if (request.title !== void 0) row.title = request.title;
943
+ if (request.source !== void 0) row.source = request.source;
944
+ if (request.questions !== void 0) row.questions = request.questions;
945
+ if (request.options !== void 0) row.options = request.options;
946
+ if (request.allowsFreeform !== void 0) row.allowsFreeform = request.allowsFreeform;
947
+ if (request.canProceedWithoutAnswer !== void 0) row.canProceedWithoutAnswer = request.canProceedWithoutAnswer;
948
+ if (request.providerMetadata !== void 0) row.providerMetadata = request.providerMetadata;
949
+ this.restoredIds.add(request.itemId);
950
+ const index = this.insertByTimestamp({
951
+ key: `approval:${request.itemId}`,
952
+ timestamp: at,
953
+ event: row
954
+ });
955
+ this.approvalRowIndex.set(request.itemId, index);
956
+ if (request.logicalItemId) this.approvalRowIndex.set(request.logicalItemId, index);
957
+ }
958
+ }
959
+ };
960
+ function collapseTranscriptEvents(envelopes, pendingApprovals = [], restoredAt) {
961
+ const collapser = new RowCollapser();
962
+ collapser.append(envelopes);
963
+ collapser.restore(pendingApprovals, restoredAt);
964
+ return collapser.raw.slice();
965
+ }
966
+ function sameStatusRow(a, b) {
967
+ return a.turnStatus === b.turnStatus && (a.turnId ?? null) === (b.turnId ?? null) && (a.message ?? "") === (b.message ?? "");
968
+ }
969
+ function mergeReasoningFragment(existing, incoming) {
970
+ if (!existing.length) return incoming;
971
+ if (!incoming.length) return existing;
972
+ if (existing === incoming) return existing;
973
+ if (incoming.startsWith(existing)) return incoming;
974
+ if (existing.startsWith(incoming)) return existing;
975
+ if (incoming.trim().length > 0 && existing.trimEnd().endsWith(incoming.trim())) return existing;
976
+ return `${existing}${incoming}`;
977
+ }
978
+ function mergeReasoningTextFragments(texts) {
979
+ const fragments = [];
980
+ for (const raw of texts) {
981
+ const text = raw.trim();
982
+ if (!text.length) continue;
983
+ if (fragments.includes(text)) continue;
984
+ const contained = fragments.map((fragment, index) => text.includes(fragment) ? index : -1).filter((index) => index >= 0);
985
+ if (contained.length) {
986
+ const firstIndex = contained[0];
987
+ fragments[firstIndex] = text;
988
+ for (const index of contained.slice(1).sort((left, right) => right - left)) {
989
+ fragments.splice(index, 1);
990
+ }
991
+ continue;
992
+ }
993
+ if (fragments.some((fragment) => fragment.includes(text))) continue;
994
+ fragments.push(text);
995
+ }
996
+ return fragments.join("\n\n---\n\n");
997
+ }
998
+ function groupInto(rows, from, grouped, starts) {
999
+ let index = from;
1000
+ while (index < rows.length) {
1001
+ const row = rows[index];
1002
+ if (row.event.type === "reasoning") {
1003
+ const head = row.event;
1004
+ const blocks = [];
1005
+ let currentItemKey = `${head.itemId ?? ""}\0${head.summaryIndex ?? ""}`;
1006
+ let currentText = head.text ?? "";
1007
+ let cursor = index + 1;
1008
+ const flushBlock = () => {
1009
+ if (currentText.length) blocks.push(currentText);
1010
+ };
1011
+ while (cursor < rows.length) {
1012
+ const candidate = rows[cursor];
1013
+ if (candidate.event.type !== "reasoning") break;
1014
+ if ((candidate.event.turnId ?? null) !== (head.turnId ?? null)) break;
1015
+ const nextItemKey = `${candidate.event.itemId ?? ""}\0${candidate.event.summaryIndex ?? ""}`;
1016
+ if (nextItemKey === currentItemKey) {
1017
+ currentText = mergeReasoningFragment(currentText, candidate.event.text ?? "");
1018
+ } else {
1019
+ flushBlock();
1020
+ currentText = candidate.event.text ?? "";
1021
+ currentItemKey = nextItemKey;
1022
+ }
1023
+ cursor += 1;
1024
+ }
1025
+ if (cursor > index + 1) {
1026
+ flushBlock();
1027
+ grouped.push({
1028
+ key: `reasoning-group:${row.key}`,
1029
+ timestamp: rows[cursor - 1].timestamp,
1030
+ event: { ...head, text: mergeReasoningTextFragments(blocks) }
1031
+ });
1032
+ starts.push(index);
1033
+ index = cursor;
1034
+ continue;
1035
+ }
1036
+ }
1037
+ if (row.event.type === "status") {
1038
+ const previous = grouped[grouped.length - 1];
1039
+ if (previous && previous.event.type === "status" && sameStatusRow(previous.event, row.event)) {
1040
+ grouped[grouped.length - 1] = row;
1041
+ index += 1;
1042
+ continue;
1043
+ }
1044
+ }
1045
+ grouped.push(row);
1046
+ starts.push(index);
1047
+ index += 1;
1048
+ }
1049
+ }
1050
+ function groupTranscriptRows(rows) {
1051
+ const grouped = [];
1052
+ groupInto(rows, 0, grouped, []);
1053
+ return grouped;
1054
+ }
1055
+ function buildTranscriptRows(envelopes, pendingApprovals = [], restoredAt) {
1056
+ return groupTranscriptRows(collapseTranscriptEvents(envelopes, pendingApprovals, restoredAt));
1057
+ }
1058
+ var TranscriptRowBuilder = class {
1059
+ collapser = new RowCollapser();
1060
+ grouped = [];
1061
+ starts = [];
1062
+ snapshot = [];
1063
+ /** The grouped rows, as a stable array until the next change. */
1064
+ get rows() {
1065
+ return this.snapshot;
1066
+ }
1067
+ /** Fold envelopes onto the end. Returns `rows`. */
1068
+ append(envelopes) {
1069
+ this.collapser.append(envelopes);
1070
+ return this.flush();
1071
+ }
1072
+ /**
1073
+ * Add the approvals the runtime is still blocked on (see
1074
+ * `collapseTranscriptEvents`). Call once, after the history append.
1075
+ */
1076
+ restore(pendingApprovals, restoredAt) {
1077
+ this.collapser.restore(pendingApprovals, restoredAt);
1078
+ return this.flush();
1079
+ }
1080
+ flush() {
1081
+ const dirty = this.collapser.takeDirty();
1082
+ if (!Number.isFinite(dirty)) return this.snapshot;
1083
+ let group = this.starts.length - 1;
1084
+ while (group >= 0 && this.starts[group] > dirty) group -= 1;
1085
+ const resumeGroup = Math.max(0, group);
1086
+ const resumeRaw = this.starts[resumeGroup] ?? 0;
1087
+ this.grouped.length = resumeGroup;
1088
+ this.starts.length = resumeGroup;
1089
+ groupInto(this.collapser.raw, resumeRaw, this.grouped, this.starts);
1090
+ this.snapshot = this.grouped.slice();
1091
+ return this.snapshot;
1092
+ }
1093
+ };
1094
+ var AdeChatContext = createContext({ client: null });
1095
+ function DaexChatProvider({ client, labels, children }) {
1096
+ const value = useMemo(
1097
+ () => labels ? { client, labels } : { client },
1098
+ [client, labels]
1099
+ );
1100
+ return /* @__PURE__ */ jsx(AdeChatContext.Provider, { value, children });
1101
+ }
1102
+ function useDaexChatContext() {
1103
+ return useContext(AdeChatContext);
1104
+ }
1105
+ function useDaexChatClient(explicit) {
1106
+ const { client } = useDaexChatContext();
1107
+ const resolved = explicit ?? client;
1108
+ if (!resolved) {
1109
+ throw new Error(
1110
+ "@daex-dev/chat-ui: no DaexChatClient. Pass `client` or wrap the tree in <DaexChatProvider>."
1111
+ );
1112
+ }
1113
+ return resolved;
1114
+ }
1115
+ function useDaexProviders(explicitClient) {
1116
+ const client = useDaexChatClient(explicitClient);
1117
+ const [statuses, setStatuses] = useState([]);
1118
+ const [models, setModels] = useState([]);
1119
+ const [loading, setLoading] = useState(true);
1120
+ const [error, setError] = useState(null);
1121
+ const [nonce, setNonce] = useState(0);
1122
+ const refresh = useCallback(() => setNonce((value) => value + 1), []);
1123
+ useEffect(() => {
1124
+ let cancelled = false;
1125
+ setLoading(true);
1126
+ Promise.all([client.providers.status(), client.models.list()]).then(([nextStatuses, nextModels]) => {
1127
+ if (cancelled) return;
1128
+ setStatuses(nextStatuses);
1129
+ setModels(nextModels);
1130
+ setError(null);
1131
+ }).catch((cause) => {
1132
+ if (cancelled) return;
1133
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
1134
+ }).finally(() => {
1135
+ if (!cancelled) setLoading(false);
1136
+ });
1137
+ return () => {
1138
+ cancelled = true;
1139
+ };
1140
+ }, [client, nonce]);
1141
+ useEffect(() => {
1142
+ return client.providers.onChange((next) => {
1143
+ setStatuses(next);
1144
+ client.models.list().then(setModels).catch(() => {
1145
+ });
1146
+ });
1147
+ }, [client]);
1148
+ return { statuses, models, loading, error, refresh };
1149
+ }
1150
+ var IDLE_STATUS = { state: "idle" };
1151
+ var DEFAULT_HISTORY_PAGE_SIZE = 200;
1152
+ function oldestSequence(envelopes) {
1153
+ let oldest = null;
1154
+ for (const envelope of envelopes) {
1155
+ if (typeof envelope.sequence === "number" && (oldest === null || envelope.sequence < oldest)) {
1156
+ oldest = envelope.sequence;
1157
+ }
1158
+ }
1159
+ return oldest;
1160
+ }
1161
+ function cursorFrom(page) {
1162
+ if (!page.hasMore) return null;
1163
+ const before = typeof page.nextBeforeSequence === "number" ? page.nextBeforeSequence : oldestSequence(page.events);
1164
+ return before === null ? null : { beforeSequence: before };
1165
+ }
1166
+ function useDaexThread(key, options) {
1167
+ const client = useDaexChatClient(options?.client);
1168
+ const [thread, setThread] = useState(null);
1169
+ const [rows, setRows] = useState([]);
1170
+ const envelopesRef = useRef([]);
1171
+ const builderRef = useRef(new TranscriptRowBuilder());
1172
+ const [olderCursor, setOlderCursor] = useState(null);
1173
+ const [loadingOlder, setLoadingOlder] = useState(false);
1174
+ const [model, setModelInfo] = useState(null);
1175
+ const openEpochRef = useRef(0);
1176
+ const restoredRef = useRef({
1177
+ restored: [],
1178
+ at: null
1179
+ });
1180
+ const loadingOlderRef = useRef(false);
1181
+ const [status, setStatus] = useState(IDLE_STATUS);
1182
+ const [usage, setUsage] = useState(null);
1183
+ const [slashCommands, setSlashCommands] = useState(void 0);
1184
+ const [slashCommandsLoading, setSlashCommandsLoading] = useState(false);
1185
+ const [slashCommandsError, setSlashCommandsError] = useState(null);
1186
+ const [error, setError] = useState(null);
1187
+ const [reopenEpoch, setReopenEpoch] = useState(0);
1188
+ const keepRowsOnReopenRef = useRef(false);
1189
+ const reopenKeepingRows = useCallback(() => {
1190
+ keepRowsOnReopenRef.current = true;
1191
+ setReopenEpoch((value) => value + 1);
1192
+ }, []);
1193
+ const modelId = options?.modelId;
1194
+ const providerId = options?.providerId;
1195
+ const resume = options?.resume;
1196
+ const enabled = options?.enabled ?? true;
1197
+ const pageSizeRef = useRef(DEFAULT_HISTORY_PAGE_SIZE);
1198
+ pageSizeRef.current = options?.historyPageSize && options.historyPageSize > 0 ? Math.floor(options.historyPageSize) : DEFAULT_HISTORY_PAGE_SIZE;
1199
+ const requestedModelIdRef = useRef(modelId);
1200
+ requestedModelIdRef.current = modelId;
1201
+ const boundModelIdRef = useRef(void 0);
1202
+ const rebuildRows = useCallback(
1203
+ (restored, at) => {
1204
+ const builder = new TranscriptRowBuilder();
1205
+ builder.append(envelopesRef.current);
1206
+ builder.restore(restored, at ?? void 0);
1207
+ builderRef.current = builder;
1208
+ setRows(builder.rows);
1209
+ },
1210
+ []
1211
+ );
1212
+ useEffect(() => {
1213
+ if (typeof client.on !== "function") return;
1214
+ return client.on("restart", (payload) => {
1215
+ if (payload.ok) reopenKeepingRows();
1216
+ });
1217
+ }, [client, reopenKeepingRows]);
1218
+ useEffect(() => {
1219
+ let cancelled = false;
1220
+ const disposers = [];
1221
+ const epoch = ++openEpochRef.current;
1222
+ const keepRows = keepRowsOnReopenRef.current;
1223
+ keepRowsOnReopenRef.current = false;
1224
+ setThread(null);
1225
+ if (!keepRows) {
1226
+ envelopesRef.current = [];
1227
+ builderRef.current = new TranscriptRowBuilder();
1228
+ setRows([]);
1229
+ }
1230
+ setOlderCursor(null);
1231
+ setLoadingOlder(false);
1232
+ loadingOlderRef.current = false;
1233
+ setModelInfo(null);
1234
+ restoredRef.current = { restored: [], at: null };
1235
+ setStatus(IDLE_STATUS);
1236
+ setUsage(null);
1237
+ setSlashCommands(void 0);
1238
+ setSlashCommandsLoading(false);
1239
+ setSlashCommandsError(null);
1240
+ if (!enabled) return;
1241
+ const openOptions = {};
1242
+ const openModelId = requestedModelIdRef.current;
1243
+ boundModelIdRef.current = openModelId;
1244
+ if (openModelId !== void 0) openOptions.modelId = openModelId;
1245
+ if (providerId !== void 0) openOptions.providerId = providerId;
1246
+ if (resume !== void 0) openOptions.resume = resume;
1247
+ client.threads.open(key, openOptions).then(async (opened) => {
1248
+ if (cancelled) return;
1249
+ const live = [];
1250
+ let historyApplied = false;
1251
+ let pendingLive = [];
1252
+ let flushScheduled = false;
1253
+ const flushLive = () => {
1254
+ flushScheduled = false;
1255
+ if (cancelled || pendingLive.length === 0) return;
1256
+ const batch = pendingLive;
1257
+ pendingLive = [];
1258
+ envelopesRef.current.push(...batch);
1259
+ setRows(builderRef.current.append(batch));
1260
+ };
1261
+ disposers.push(
1262
+ opened.on("event", (envelope) => {
1263
+ if (isHistoryInvalidation(envelope)) {
1264
+ reopenKeepingRows();
1265
+ return;
1266
+ }
1267
+ if (!historyApplied) {
1268
+ live.push(envelope);
1269
+ return;
1270
+ }
1271
+ pendingLive.push(envelope);
1272
+ if (!flushScheduled) {
1273
+ flushScheduled = true;
1274
+ queueMicrotask(flushLive);
1275
+ }
1276
+ })
1277
+ );
1278
+ disposers.push(opened.on("status", (next) => setStatus(next)));
1279
+ disposers.push(opened.on("usage", (next) => setUsage(next)));
1280
+ if (typeof opened.slashCommands === "function") {
1281
+ setSlashCommands(null);
1282
+ setSlashCommandsLoading(true);
1283
+ void opened.slashCommands().then((commands) => {
1284
+ if (!cancelled && epoch === openEpochRef.current) {
1285
+ setSlashCommands(commands ?? []);
1286
+ setSlashCommandsError(null);
1287
+ }
1288
+ }).catch((cause) => {
1289
+ if (!cancelled && epoch === openEpochRef.current) {
1290
+ setSlashCommands(null);
1291
+ setSlashCommandsError(cause instanceof Error ? cause.message : String(cause));
1292
+ }
1293
+ }).finally(() => {
1294
+ if (!cancelled && epoch === openEpochRef.current) setSlashCommandsLoading(false);
1295
+ });
1296
+ }
1297
+ let history;
1298
+ let cursor = null;
1299
+ if (typeof opened.historyPage === "function") {
1300
+ const page = await opened.historyPage({ limit: pageSizeRef.current }).catch(() => null);
1301
+ if (page) {
1302
+ history = page.events ?? [];
1303
+ cursor = cursorFrom(page);
1304
+ } else {
1305
+ history = await opened.history().catch(() => []);
1306
+ }
1307
+ } else {
1308
+ history = await opened.history().catch(() => []);
1309
+ }
1310
+ if (cancelled) return;
1311
+ const restored = await readPendingApprovals(opened);
1312
+ if (cancelled) return;
1313
+ const seen = new Set(history.map(envelopeIdentity));
1314
+ historyApplied = true;
1315
+ const merged = sortEnvelopes([
1316
+ ...history,
1317
+ ...live.filter((item) => !seen.has(envelopeIdentity(item)))
1318
+ ]);
1319
+ const restoredReadAt = merged[merged.length - 1]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
1320
+ if (epoch !== openEpochRef.current) return;
1321
+ envelopesRef.current = merged;
1322
+ rebuildRows(restored, restoredReadAt);
1323
+ setOlderCursor(cursor);
1324
+ restoredRef.current = { restored, at: restoredReadAt };
1325
+ setModelInfo(readThreadModelSelection(opened.model));
1326
+ setThread(opened);
1327
+ setError(null);
1328
+ }).catch((cause) => {
1329
+ if (cancelled) return;
1330
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
1331
+ });
1332
+ return () => {
1333
+ cancelled = true;
1334
+ for (const dispose of disposers) dispose();
1335
+ };
1336
+ }, [client, key, providerId, resume, enabled, rebuildRows, reopenEpoch, reopenKeepingRows]);
1337
+ const threadRef = useRef(null);
1338
+ threadRef.current = thread;
1339
+ const send = useCallback(async (input) => {
1340
+ await threadRef.current?.send(input);
1341
+ }, []);
1342
+ const steer = useCallback(async (input) => {
1343
+ await threadRef.current?.steer(input);
1344
+ }, []);
1345
+ const interrupt = useCallback(async () => {
1346
+ await threadRef.current?.interrupt();
1347
+ }, []);
1348
+ const setModel = useCallback(async (nextModelId) => {
1349
+ const target = threadRef.current;
1350
+ if (!target || !nextModelId) return;
1351
+ if (boundModelIdRef.current === nextModelId) return;
1352
+ if (typeof target.setModel !== "function") return;
1353
+ const selection = await target.setModel(nextModelId);
1354
+ boundModelIdRef.current = nextModelId;
1355
+ if (threadRef.current === target) {
1356
+ setModelInfo(target.model ?? readThreadModelSelection(selection));
1357
+ }
1358
+ }, []);
1359
+ const update = useCallback(async (patch) => {
1360
+ const target = threadRef.current;
1361
+ if (typeof target?.update !== "function") return;
1362
+ const updated = await target.update(patch);
1363
+ if (threadRef.current === target) {
1364
+ const next = target.model ?? readThreadModelSelection(updated?.model);
1365
+ if (next) setModelInfo(next);
1366
+ }
1367
+ }, []);
1368
+ const retry = useCallback(async () => {
1369
+ const target = threadRef.current;
1370
+ if (typeof target?.retry !== "function") return;
1371
+ await target.retry();
1372
+ }, []);
1373
+ const editLast = useCallback(async (input) => {
1374
+ const target = threadRef.current;
1375
+ if (typeof target?.editLast !== "function") return;
1376
+ await target.editLast(input);
1377
+ }, []);
1378
+ const loadOlder = useCallback(async () => {
1379
+ const target = threadRef.current;
1380
+ if (!target || typeof target.historyPage !== "function") return;
1381
+ if (!olderCursor || loadingOlderRef.current) return;
1382
+ const epoch = openEpochRef.current;
1383
+ loadingOlderRef.current = true;
1384
+ setLoadingOlder(true);
1385
+ try {
1386
+ const page = await target.historyPage({
1387
+ beforeSequence: olderCursor.beforeSequence,
1388
+ limit: pageSizeRef.current
1389
+ });
1390
+ if (epoch !== openEpochRef.current || threadRef.current !== target) return;
1391
+ const seen = new Set(envelopesRef.current.map(envelopeIdentity));
1392
+ const older = (page.events ?? []).filter((item) => !seen.has(envelopeIdentity(item)));
1393
+ const next = cursorFrom(page);
1394
+ setOlderCursor(older.length === 0 ? null : next);
1395
+ if (older.length === 0) return;
1396
+ envelopesRef.current = sortEnvelopes([...older, ...envelopesRef.current]);
1397
+ rebuildRows(restoredRef.current.restored, restoredRef.current.at);
1398
+ } catch {
1399
+ } finally {
1400
+ if (epoch === openEpochRef.current) {
1401
+ loadingOlderRef.current = false;
1402
+ setLoadingOlder(false);
1403
+ }
1404
+ }
1405
+ }, [olderCursor, rebuildRows]);
1406
+ const approve = useCallback(
1407
+ async (itemId, decision, responseText) => {
1408
+ const target = threadRef.current;
1409
+ if (typeof target?.approve !== "function") return;
1410
+ if (responseText === void 0) await target.approve(itemId, decision);
1411
+ else await target.approve(itemId, decision, responseText);
1412
+ },
1413
+ []
1414
+ );
1415
+ const pendingApprovals = useCallback(async () => {
1416
+ const target = threadRef.current;
1417
+ if (typeof target?.pendingApprovals !== "function") return [];
1418
+ return await target.pendingApprovals();
1419
+ }, []);
1420
+ const respond = useCallback(async (requestId, response) => {
1421
+ const target = threadRef.current;
1422
+ if (typeof target?.respond !== "function") return;
1423
+ await target.respond(requestId, response);
1424
+ }, []);
1425
+ const reloadSlashCommands = useCallback(async () => {
1426
+ const target = threadRef.current;
1427
+ if (typeof target?.slashCommands !== "function") return;
1428
+ setSlashCommandsLoading(true);
1429
+ setSlashCommandsError(null);
1430
+ try {
1431
+ setSlashCommands(await target.slashCommands());
1432
+ } catch (cause) {
1433
+ setSlashCommands(null);
1434
+ setSlashCommandsError(cause instanceof Error ? cause.message : String(cause));
1435
+ } finally {
1436
+ setSlashCommandsLoading(false);
1437
+ }
1438
+ }, []);
1439
+ return {
1440
+ thread,
1441
+ ready: thread !== null,
1442
+ rows,
1443
+ status,
1444
+ usage,
1445
+ error,
1446
+ send,
1447
+ steer,
1448
+ interrupt,
1449
+ setModel,
1450
+ update,
1451
+ retry,
1452
+ editLast,
1453
+ approve,
1454
+ pendingApprovals,
1455
+ respond,
1456
+ canRespond: typeof thread?.respond === "function",
1457
+ slashCommands,
1458
+ slashCommandsLoading,
1459
+ slashCommandsError,
1460
+ reloadSlashCommands,
1461
+ canSetModel: typeof thread?.setModel === "function",
1462
+ canApprove: typeof thread?.approve === "function",
1463
+ canUpdate: typeof thread?.update === "function",
1464
+ canRetry: typeof thread?.retry === "function" && typeof thread?.editLast === "function",
1465
+ model,
1466
+ hasOlder: olderCursor !== null,
1467
+ loadingOlder,
1468
+ loadOlder
1469
+ };
1470
+ }
1471
+ function isHistoryInvalidation(envelope) {
1472
+ const event = envelope.event;
1473
+ return event?.type === "session_meta_updated" && event.historyInvalidated === true;
1474
+ }
1475
+ function envelopeIdentity(envelope) {
1476
+ return `${envelope.sessionId}:${envelope.sequence ?? "?"}:${envelope.timestamp}:${envelope.event?.type ?? "?"}`;
1477
+ }
1478
+ function sortEnvelopes(envelopes) {
1479
+ return envelopes.map((envelope, index) => ({ envelope, index })).sort((a, b) => {
1480
+ const aSeq = typeof a.envelope.sequence === "number" ? a.envelope.sequence : null;
1481
+ const bSeq = typeof b.envelope.sequence === "number" ? b.envelope.sequence : null;
1482
+ if (aSeq !== null && bSeq === null) return -1;
1483
+ if (aSeq === null && bSeq !== null) return 1;
1484
+ if (aSeq !== null && bSeq !== null) {
1485
+ if (aSeq !== bSeq) return aSeq - bSeq;
1486
+ return a.index - b.index;
1487
+ }
1488
+ if (a.envelope.timestamp !== b.envelope.timestamp) {
1489
+ return a.envelope.timestamp < b.envelope.timestamp ? -1 : 1;
1490
+ }
1491
+ return a.index - b.index;
1492
+ }).map((entry) => entry.envelope);
1493
+ }
1494
+ async function readPendingApprovals(thread) {
1495
+ if (typeof thread.pendingApprovals !== "function") return [];
1496
+ const pending = await thread.pendingApprovals().catch(() => []);
1497
+ return pending.filter((request) => Boolean(request.itemId));
1498
+ }
1499
+ var AdeChatProvider = DaexChatProvider;
1500
+ var useAdeChatClient = useDaexChatClient;
1501
+ var useAdeChatContext = useDaexChatContext;
1502
+ var useAdeProviders = useDaexProviders;
1503
+ var useAdeThread = useDaexThread;
1504
+
1505
+ // src/models/modelSearch.ts
1506
+ function normalizeSearchQuery(input) {
1507
+ const trimmed = input.trim();
1508
+ return trimmed ? trimmed.toLowerCase() : "";
1509
+ }
1510
+ function scoreSubsequenceMatch(value, query) {
1511
+ if (!query) return 0;
1512
+ let queryIndex = 0;
1513
+ let firstMatchIndex = -1;
1514
+ let previousMatchIndex = -1;
1515
+ let gapPenalty = 0;
1516
+ for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
1517
+ if (value[valueIndex] !== query[queryIndex]) continue;
1518
+ if (firstMatchIndex === -1) firstMatchIndex = valueIndex;
1519
+ if (previousMatchIndex !== -1) gapPenalty += valueIndex - previousMatchIndex - 1;
1520
+ previousMatchIndex = valueIndex;
1521
+ queryIndex += 1;
1522
+ if (queryIndex === query.length) {
1523
+ const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
1524
+ const valueLengthPenalty = Math.min(64, value.length - query.length);
1525
+ return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + valueLengthPenalty;
1526
+ }
1527
+ }
1528
+ return null;
1529
+ }
1530
+ function lengthPenalty(value, query) {
1531
+ return Math.min(64, Math.max(0, value.length - query.length));
1532
+ }
1533
+ function findBoundaryMatchIndex(value, query, boundaryMarkers) {
1534
+ let bestIndex = null;
1535
+ for (const marker of boundaryMarkers) {
1536
+ const index = value.indexOf(`${marker}${query}`);
1537
+ if (index === -1) continue;
1538
+ const matchIndex = index + marker.length;
1539
+ if (bestIndex === null || matchIndex < bestIndex) bestIndex = matchIndex;
1540
+ }
1541
+ return bestIndex;
1542
+ }
1543
+ function scoreQueryMatch(input) {
1544
+ const { value, query } = input;
1545
+ if (!value || !query) return null;
1546
+ if (value === query) return input.exactBase;
1547
+ if (input.prefixBase !== void 0 && value.startsWith(query)) {
1548
+ return input.prefixBase + lengthPenalty(value, query);
1549
+ }
1550
+ if (input.boundaryBase !== void 0) {
1551
+ const boundaryIndex = findBoundaryMatchIndex(
1552
+ value,
1553
+ query,
1554
+ input.boundaryMarkers ?? [" ", "-", "_", "/"]
1555
+ );
1556
+ if (boundaryIndex !== null) {
1557
+ return input.boundaryBase + boundaryIndex * 2 + lengthPenalty(value, query);
1558
+ }
1559
+ }
1560
+ if (input.includesBase !== void 0) {
1561
+ const includesIndex = value.indexOf(query);
1562
+ if (includesIndex !== -1) {
1563
+ return input.includesBase + includesIndex * 2 + lengthPenalty(value, query);
1564
+ }
1565
+ }
1566
+ if (input.fuzzyBase !== void 0) {
1567
+ const fuzzyScore = scoreSubsequenceMatch(value, query);
1568
+ if (fuzzyScore !== null) return input.fuzzyBase + fuzzyScore;
1569
+ }
1570
+ return null;
1571
+ }
1572
+ function resolveProviderDisplayName(item) {
1573
+ return item.providerDisplayName ?? item.providerId;
1574
+ }
1575
+ function buildModelSearchText(item) {
1576
+ return normalizeSearchQuery(
1577
+ [item.displayName, item.shortName, item.subProvider, item.providerId, resolveProviderDisplayName(item)].concat(item.aliases ?? []).filter((value) => typeof value === "string" && value.length > 0).join(" ")
1578
+ );
1579
+ }
1580
+ function getSearchFields(item) {
1581
+ return [
1582
+ normalizeSearchQuery(item.displayName),
1583
+ ...item.shortName ? [normalizeSearchQuery(item.shortName)] : [],
1584
+ ...(item.aliases ?? []).map((alias) => normalizeSearchQuery(alias)).filter(Boolean),
1585
+ ...item.subProvider ? [normalizeSearchQuery(item.subProvider)] : [],
1586
+ normalizeSearchQuery(item.providerId),
1587
+ normalizeSearchQuery(resolveProviderDisplayName(item)),
1588
+ buildModelSearchText(item)
1589
+ ];
1590
+ }
1591
+ function scoreToken(field, token, fieldBase) {
1592
+ return scoreQueryMatch({
1593
+ value: field,
1594
+ query: token,
1595
+ exactBase: fieldBase,
1596
+ prefixBase: fieldBase + 2,
1597
+ boundaryBase: fieldBase + 4,
1598
+ includesBase: fieldBase + 6,
1599
+ ...token.length >= 3 ? { fuzzyBase: fieldBase + 100 } : {}
1600
+ });
1601
+ }
1602
+ function scoreModelSearch(item, query) {
1603
+ const tokens = normalizeSearchQuery(query).split(/\s+/u).filter((token) => token.length > 0);
1604
+ if (tokens.length === 0) return 0;
1605
+ const fields = getSearchFields(item);
1606
+ let score = 0;
1607
+ for (const token of tokens) {
1608
+ const tokenScores = fields.map((field, index) => scoreToken(field, token, index * 10)).filter((fieldScore) => fieldScore !== null);
1609
+ if (tokenScores.length === 0) return null;
1610
+ score += Math.min(...tokenScores);
1611
+ }
1612
+ return score;
1613
+ }
1614
+ function searchable(model, status) {
1615
+ return {
1616
+ displayName: model.displayName,
1617
+ ...model.shortName ? { shortName: model.shortName } : {},
1618
+ ...model.subProvider ? { subProvider: model.subProvider } : {},
1619
+ ...model.aliases ? { aliases: model.aliases } : {},
1620
+ providerId: model.providerId,
1621
+ ...status?.displayName ? { providerDisplayName: status.displayName } : {}
1622
+ };
1623
+ }
1624
+ function isProviderUsable(status) {
1625
+ return Boolean(status?.installed && status.authenticated);
1626
+ }
1627
+ function isModelSelectable(model, status) {
1628
+ if (model.available === false) return false;
1629
+ return isProviderUsable(status);
1630
+ }
1631
+ function groupModelsByProvider(input) {
1632
+ const statusById = new Map(input.statuses.map((status) => [status.id, status]));
1633
+ const query = input.query?.trim() ?? "";
1634
+ const order = [];
1635
+ for (const status of input.statuses) if (!order.includes(status.id)) order.push(status.id);
1636
+ for (const model of input.models) if (!order.includes(model.providerId)) order.push(model.providerId);
1637
+ const scored = /* @__PURE__ */ new Map();
1638
+ for (const model of input.models) {
1639
+ const status = statusById.get(model.providerId) ?? null;
1640
+ const score = query ? scoreModelSearch(searchable(model, status), query) : 0;
1641
+ if (score === null) continue;
1642
+ const bucket = scored.get(model.providerId) ?? [];
1643
+ bucket.push({ model, score });
1644
+ scored.set(model.providerId, bucket);
1645
+ }
1646
+ const groups = [];
1647
+ for (const providerId of order) {
1648
+ const bucket = scored.get(providerId);
1649
+ if (!bucket || bucket.length === 0) continue;
1650
+ const status = statusById.get(providerId) ?? null;
1651
+ const models = bucket.map((entry, index) => ({ ...entry, index })).sort((a, b) => a.score - b.score || a.index - b.index).map((entry) => entry.model);
1652
+ groups.push({
1653
+ providerId,
1654
+ providerLabel: status?.displayName ?? providerId,
1655
+ status,
1656
+ enabled: isProviderUsable(status),
1657
+ models
1658
+ });
1659
+ }
1660
+ return groups;
1661
+ }
1662
+ function statusDot(status) {
1663
+ if (!status || !status.installed) return "missing";
1664
+ return status.authenticated ? "ok" : "unauthed";
1665
+ }
1666
+ function ModelPicker(props) {
1667
+ const usesContext = props.models === void 0 || props.providers === void 0;
1668
+ return usesContext ? /* @__PURE__ */ jsx(ConnectedModelPicker, { ...props }) : /* @__PURE__ */ jsx(ModelPickerView, { ...props });
1669
+ }
1670
+ function ConnectedModelPicker(props) {
1671
+ const { statuses, models, loading, error } = useDaexProviders(props.client);
1672
+ if (error) {
1673
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-modelpicker-empty", children: [
1674
+ "Could not load models: ",
1675
+ error.message
1676
+ ] });
1677
+ }
1678
+ if (loading && models.length === 0) {
1679
+ return /* @__PURE__ */ jsx("div", { className: "adechat-modelpicker-empty", children: "Loading models\u2026" });
1680
+ }
1681
+ return /* @__PURE__ */ jsx(
1682
+ ModelPickerView,
1683
+ {
1684
+ ...props,
1685
+ models: props.models ?? models,
1686
+ providers: props.providers ?? statuses
1687
+ }
1688
+ );
1689
+ }
1690
+ function ModelPickerView({
1691
+ value,
1692
+ onChange,
1693
+ models = [],
1694
+ providers = [],
1695
+ searchable: searchable2 = true,
1696
+ renderProviderNotice,
1697
+ reasoningEffort,
1698
+ onReasoningEffortChange,
1699
+ className
1700
+ }) {
1701
+ const [query, setQuery] = useState("");
1702
+ const [selectedProvider, setSelectedProvider] = useState(null);
1703
+ const railRefs = useRef(/* @__PURE__ */ new Map());
1704
+ const groups = useMemo(
1705
+ () => groupModelsByProvider({ models, statuses: providers, query }),
1706
+ [models, providers, query]
1707
+ );
1708
+ const activeProvider = useMemo(() => {
1709
+ if (selectedProvider && groups.some((group) => group.providerId === selectedProvider)) {
1710
+ return selectedProvider;
1711
+ }
1712
+ const selectedModel2 = models.find((model) => model.id === value);
1713
+ if (selectedModel2 && groups.some((group) => group.providerId === selectedModel2.providerId)) {
1714
+ return selectedModel2.providerId;
1715
+ }
1716
+ return groups[0]?.providerId ?? null;
1717
+ }, [groups, models, selectedProvider, value]);
1718
+ useEffect(() => {
1719
+ if (selectedProvider && !groups.some((group) => group.providerId === selectedProvider)) {
1720
+ setSelectedProvider(null);
1721
+ }
1722
+ }, [groups, selectedProvider]);
1723
+ const handleRailKeyDown = useCallback(
1724
+ (event, index) => {
1725
+ if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
1726
+ event.preventDefault();
1727
+ const last = Math.max(0, groups.length - 1);
1728
+ const nextIndex = event.key === "Home" ? 0 : event.key === "End" ? last : Math.min(Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)), last);
1729
+ const next = groups[nextIndex];
1730
+ if (!next) return;
1731
+ setSelectedProvider(next.providerId);
1732
+ railRefs.current.get(next.providerId)?.focus();
1733
+ },
1734
+ [groups]
1735
+ );
1736
+ const activeGroup = groups.find((group) => group.providerId === activeProvider) ?? null;
1737
+ const selectedModel = value ? models.find((model) => model.id === value) ?? null : null;
1738
+ const efforts = selectedModel?.reasoningEfforts ?? [];
1739
+ const currentEffort = reasoningEffort ?? selectedModel?.defaultReasoningEffort ?? null;
1740
+ return /* @__PURE__ */ jsxs("div", { className: ["adechat-modelpicker", className].filter(Boolean).join(" "), children: [
1741
+ /* @__PURE__ */ jsxs("div", { className: "adechat-modelpicker-rail", role: "tablist", "aria-orientation": "vertical", children: [
1742
+ groups.map((group, index) => /* @__PURE__ */ jsxs(
1743
+ "button",
1744
+ {
1745
+ ref: (node) => {
1746
+ if (node) railRefs.current.set(group.providerId, node);
1747
+ else railRefs.current.delete(group.providerId);
1748
+ },
1749
+ type: "button",
1750
+ role: "tab",
1751
+ className: "adechat-modelpicker-railbutton",
1752
+ "aria-selected": group.providerId === activeProvider,
1753
+ tabIndex: group.providerId === activeProvider ? 0 : -1,
1754
+ onClick: () => setSelectedProvider(group.providerId),
1755
+ onKeyDown: (event) => handleRailKeyDown(event, index),
1756
+ children: [
1757
+ /* @__PURE__ */ jsx(
1758
+ "span",
1759
+ {
1760
+ className: "adechat-status-dot",
1761
+ "data-status": statusDot(group.status),
1762
+ "aria-hidden": "true"
1763
+ }
1764
+ ),
1765
+ /* @__PURE__ */ jsx("span", { className: "adechat-modelpicker-raillabel", children: group.providerLabel })
1766
+ ]
1767
+ },
1768
+ group.providerId
1769
+ )),
1770
+ groups.length === 0 ? /* @__PURE__ */ jsx("div", { className: "adechat-modelpicker-empty", children: "No providers" }) : null
1771
+ ] }),
1772
+ /* @__PURE__ */ jsxs("div", { className: "adechat-modelpicker-main", children: [
1773
+ searchable2 ? /* @__PURE__ */ jsx(
1774
+ "input",
1775
+ {
1776
+ className: "adechat-modelpicker-search",
1777
+ type: "search",
1778
+ value: query,
1779
+ placeholder: "Search models",
1780
+ onChange: (event) => setQuery(event.target.value),
1781
+ "aria-label": "Search models"
1782
+ }
1783
+ ) : null,
1784
+ /* @__PURE__ */ jsx("ul", { className: "adechat-modelpicker-list", role: "listbox", "aria-label": "Models", children: activeGroup ? /* @__PURE__ */ jsx(
1785
+ ModelGroupRows,
1786
+ {
1787
+ group: activeGroup,
1788
+ selectedId: value ?? null,
1789
+ onChange,
1790
+ ...renderProviderNotice ? { renderProviderNotice } : {}
1791
+ }
1792
+ ) : /* @__PURE__ */ jsx("li", { className: "adechat-modelpicker-empty", children: query ? `No models match \u201C${query}\u201D.` : "No models available." }) }),
1793
+ onReasoningEffortChange && selectedModel && efforts.length ? /* @__PURE__ */ jsxs(
1794
+ "div",
1795
+ {
1796
+ className: "adechat-modelpicker-effort",
1797
+ role: "radiogroup",
1798
+ "aria-label": `Reasoning effort for ${selectedModel.displayName}`,
1799
+ children: [
1800
+ /* @__PURE__ */ jsx("span", { className: "adechat-modelpicker-effortlabel", children: "Effort" }),
1801
+ efforts.map((effort) => /* @__PURE__ */ jsx(
1802
+ "button",
1803
+ {
1804
+ type: "button",
1805
+ role: "radio",
1806
+ className: "adechat-modelpicker-effortoption",
1807
+ "aria-checked": effort === currentEffort,
1808
+ onClick: () => onReasoningEffortChange(effort, selectedModel),
1809
+ children: effort
1810
+ },
1811
+ effort
1812
+ ))
1813
+ ]
1814
+ }
1815
+ ) : null
1816
+ ] })
1817
+ ] });
1818
+ }
1819
+ function ModelGroupRows({
1820
+ group,
1821
+ selectedId,
1822
+ onChange,
1823
+ renderProviderNotice
1824
+ }) {
1825
+ const notice = !group.enabled ? renderProviderNotice?.(group.status, group.providerId) : null;
1826
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1827
+ /* @__PURE__ */ jsx("li", { className: "adechat-modelpicker-group", "aria-hidden": "true", children: group.providerLabel }),
1828
+ notice ? /* @__PURE__ */ jsx("li", { children: notice }) : null,
1829
+ group.models.map((model) => {
1830
+ const selectable = isModelSelectable(model, group.status);
1831
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
1832
+ "button",
1833
+ {
1834
+ type: "button",
1835
+ role: "option",
1836
+ className: "adechat-modelpicker-row",
1837
+ "aria-selected": model.id === selectedId,
1838
+ disabled: !selectable,
1839
+ title: selectable ? model.description : `${group.providerLabel} is not ready \u2014 sign in to use this model.`,
1840
+ onClick: () => onChange(model),
1841
+ children: [
1842
+ /* @__PURE__ */ jsx("span", { className: "adechat-modelpicker-rowname", children: model.displayName }),
1843
+ model.subProvider ? /* @__PURE__ */ jsx("span", { className: "adechat-modelpicker-rowmeta", children: model.subProvider }) : null
1844
+ ]
1845
+ }
1846
+ ) }, model.id);
1847
+ })
1848
+ ] });
1849
+ }
1850
+
1851
+ // src/theme/createTheme.ts
1852
+ var DAEX_CHAT_TOKENS = [
1853
+ /**
1854
+ * The outermost surface: the chat root and the composer bar. Separate from
1855
+ * `--adechat-bg` so it alone can be `transparent` while inset surfaces
1856
+ * (code blocks, command boxes) keep an opaque colour.
1857
+ */
1858
+ "--adechat-root-bg",
1859
+ "--adechat-bg",
1860
+ "--adechat-bg-subtle",
1861
+ "--adechat-bg-raised",
1862
+ "--adechat-fg",
1863
+ "--adechat-muted",
1864
+ "--adechat-accent",
1865
+ "--adechat-accent-fg",
1866
+ "--adechat-accent-subtle",
1867
+ "--adechat-border",
1868
+ "--adechat-border-strong",
1869
+ "--adechat-hover",
1870
+ "--adechat-danger",
1871
+ "--adechat-danger-subtle",
1872
+ "--adechat-success",
1873
+ "--adechat-radius",
1874
+ "--adechat-radius-sm",
1875
+ "--adechat-font",
1876
+ "--adechat-font-mono",
1877
+ "--adechat-font-size",
1878
+ "--adechat-space"
1879
+ ];
1880
+ var DEFAULTS = {
1881
+ accent: "#5b8cff",
1882
+ darkBackground: "#101114",
1883
+ lightBackground: "#ffffff",
1884
+ danger: "#e5484d",
1885
+ success: "#30a46c",
1886
+ radius: 10,
1887
+ fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
1888
+ monoFontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',
1889
+ fontSize: 14,
1890
+ space: 8
1891
+ };
1892
+ function parseHex(value) {
1893
+ const hex = value.trim().replace(/^#/, "");
1894
+ if (!/^[0-9a-fA-F]+$/.test(hex)) return null;
1895
+ if (hex.length === 3 || hex.length === 4) {
1896
+ const [r, g, b, a] = hex.split("").map((char) => parseInt(char + char, 16));
1897
+ return { r, g, b, a: (a ?? 255) / 255 };
1898
+ }
1899
+ if (hex.length === 6 || hex.length === 8) {
1900
+ const parts = hex.match(/.{2}/g).map((pair) => parseInt(pair, 16));
1901
+ return { r: parts[0], g: parts[1], b: parts[2], a: (parts[3] ?? 255) / 255 };
1902
+ }
1903
+ return null;
1904
+ }
1905
+ function rgba(color, alpha) {
1906
+ const parsed = parseHex(color);
1907
+ if (!parsed) {
1908
+ return color;
1909
+ }
1910
+ return `rgba(${parsed.r}, ${parsed.g}, ${parsed.b}, ${round(alpha * parsed.a)})`;
1911
+ }
1912
+ function round(value) {
1913
+ return Math.round(value * 1e3) / 1e3;
1914
+ }
1915
+ function relativeLuminance(color) {
1916
+ const parsed = parseHex(color);
1917
+ if (!parsed) return null;
1918
+ const channel = (raw) => {
1919
+ const srgb = raw / 255;
1920
+ return srgb <= 0.03928 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
1921
+ };
1922
+ return 0.2126 * channel(parsed.r) + 0.7152 * channel(parsed.g) + 0.0722 * channel(parsed.b);
1923
+ }
1924
+ function shade(color, amount, toward) {
1925
+ const parsed = parseHex(color);
1926
+ if (!parsed) return color;
1927
+ const target = toward === "light" ? 255 : 0;
1928
+ const mix = (channel) => Math.round(channel + (target - channel) * amount);
1929
+ return `rgb(${mix(parsed.r)}, ${mix(parsed.g)}, ${mix(parsed.b)})`;
1930
+ }
1931
+ function px(value, fallback) {
1932
+ if (value === void 0) return `${fallback}px`;
1933
+ return typeof value === "number" ? `${value}px` : value;
1934
+ }
1935
+ function contrastForeground(background, scheme) {
1936
+ const luminance = relativeLuminance(background);
1937
+ if (luminance === null) return scheme === "dark" ? "#f5f6f8" : "#16181d";
1938
+ return luminance > 0.5 ? "#16181d" : "#f5f6f8";
1939
+ }
1940
+ function createTheme(input = {}) {
1941
+ const transparent = input.background?.trim().toLowerCase() === "transparent";
1942
+ const requestedBackground = transparent ? void 0 : input.background;
1943
+ const backgroundLuminance = requestedBackground ? relativeLuminance(requestedBackground) : null;
1944
+ const scheme = input.scheme ?? (backgroundLuminance === null ? "dark" : backgroundLuminance > 0.5 ? "light" : "dark");
1945
+ const background = requestedBackground ?? (scheme === "light" ? DEFAULTS.lightBackground : DEFAULTS.darkBackground);
1946
+ const accent = input.accent ?? DEFAULTS.accent;
1947
+ const foreground = input.foreground ?? contrastForeground(background, scheme);
1948
+ const danger = input.danger ?? DEFAULTS.danger;
1949
+ const success = input.success ?? DEFAULTS.success;
1950
+ const toward = scheme === "dark" ? "light" : "dark";
1951
+ const contrastInk = scheme === "dark" ? "#ffffff" : "#000000";
1952
+ const radius = px(input.radius, DEFAULTS.radius);
1953
+ const radiusSm = typeof input.radius === "number" ? `${Math.max(2, Math.round(input.radius * 0.6))}px` : input.radius ? `calc(${radius} * 0.6)` : `${Math.round(DEFAULTS.radius * 0.6)}px`;
1954
+ return {
1955
+ // A reference, not a copy, for every opaque theme: a host that overrides
1956
+ // `--adechat-bg` by hand (on the root, where this is declared) still moves
1957
+ // the root and composer with it, as it did before this token existed.
1958
+ "--adechat-root-bg": transparent ? "transparent" : "var(--adechat-bg)",
1959
+ "--adechat-bg": background,
1960
+ "--adechat-bg-subtle": shade(background, 0.04, toward),
1961
+ "--adechat-bg-raised": shade(background, 0.08, toward),
1962
+ "--adechat-fg": foreground,
1963
+ "--adechat-muted": input.muted ?? rgba(contrastInk, scheme === "dark" ? 0.56 : 0.52),
1964
+ "--adechat-accent": accent,
1965
+ "--adechat-accent-fg": contrastForeground(accent, scheme),
1966
+ "--adechat-accent-subtle": rgba(accent, 0.14),
1967
+ "--adechat-border": rgba(contrastInk, scheme === "dark" ? 0.1 : 0.12),
1968
+ "--adechat-border-strong": rgba(contrastInk, scheme === "dark" ? 0.2 : 0.24),
1969
+ "--adechat-hover": rgba(contrastInk, scheme === "dark" ? 0.06 : 0.05),
1970
+ "--adechat-danger": danger,
1971
+ "--adechat-danger-subtle": rgba(danger, 0.14),
1972
+ "--adechat-success": success,
1973
+ "--adechat-radius": radius,
1974
+ "--adechat-radius-sm": radiusSm,
1975
+ "--adechat-font": input.fontFamily ?? DEFAULTS.fontFamily,
1976
+ "--adechat-font-mono": input.monoFontFamily ?? DEFAULTS.monoFontFamily,
1977
+ "--adechat-font-size": px(input.fontSize, DEFAULTS.fontSize),
1978
+ "--adechat-space": px(input.space, DEFAULTS.space)
1979
+ };
1980
+ }
1981
+ var defaultTheme = createTheme();
1982
+ function themeToCss(theme, selector = ":root") {
1983
+ const body = Object.keys(theme).map((token) => ` ${token}: ${theme[token]};`).join("\n");
1984
+ return `${selector} {
1985
+ ${body}
1986
+ }`;
1987
+ }
1988
+ var ADE_CHAT_TOKENS = DAEX_CHAT_TOKENS;
1989
+
1990
+ // src/theme/styles.ts
1991
+ var ADE_CHAT_STYLE_ID = "adechat-styles";
1992
+ var daexChatCss = `
1993
+ ${themeToCss(defaultTheme, ".adechat-root")}
1994
+
1995
+ .adechat-root {
1996
+ display: flex;
1997
+ flex-direction: column;
1998
+ min-height: 0;
1999
+ color: var(--adechat-fg);
2000
+ background: var(--adechat-root-bg, var(--adechat-bg));
2001
+ font-family: var(--adechat-font);
2002
+ font-size: var(--adechat-font-size);
2003
+ line-height: 1.5;
2004
+ box-sizing: border-box;
2005
+ }
2006
+ .adechat-root *,
2007
+ .adechat-root *::before,
2008
+ .adechat-root *::after { box-sizing: inherit; }
2009
+
2010
+ /* Transcript ------------------------------------------------------------- */
2011
+
2012
+ .adechat-transcript {
2013
+ flex: 1 1 auto;
2014
+ min-height: 0;
2015
+ overflow-y: auto;
2016
+ overflow-x: hidden;
2017
+ overscroll-behavior: contain;
2018
+ /* The windowed transcript restores the reader's position itself when older
2019
+ rows load; the browser's own anchoring would apply the shift twice. */
2020
+ overflow-anchor: none;
2021
+ display: flex;
2022
+ flex-direction: column;
2023
+ gap: calc(var(--adechat-space) * 1.5);
2024
+ padding: calc(var(--adechat-space) * 2);
2025
+ }
2026
+ .adechat-row-slot { display: flex; flex-direction: column; min-width: 0; }
2027
+ .adechat-transcript-spacer { flex: 0 0 auto; }
2028
+ .adechat-transcript-older {
2029
+ align-self: center;
2030
+ font: inherit;
2031
+ font-size: 0.85em;
2032
+ color: var(--adechat-muted);
2033
+ background: none;
2034
+ border: 1px solid var(--adechat-border);
2035
+ border-radius: var(--adechat-radius-sm);
2036
+ padding: 2px 10px;
2037
+ cursor: pointer;
2038
+ }
2039
+ .adechat-transcript-older:disabled { cursor: default; opacity: 0.6; }
2040
+ .adechat-transcript-empty {
2041
+ margin: auto;
2042
+ color: var(--adechat-muted);
2043
+ text-align: center;
2044
+ padding: calc(var(--adechat-space) * 3);
2045
+ }
2046
+
2047
+ .adechat-row { display: flex; flex-direction: column; }
2048
+ .adechat-row-user { align-items: flex-end; }
2049
+
2050
+ .adechat-bubble-user {
2051
+ max-width: 82%;
2052
+ padding: calc(var(--adechat-space) * 0.875) calc(var(--adechat-space) * 1.25);
2053
+ border-radius: var(--adechat-radius);
2054
+ background: var(--adechat-accent);
2055
+ color: var(--adechat-accent-fg);
2056
+ white-space: pre-wrap;
2057
+ word-break: break-word;
2058
+ }
2059
+ .adechat-attachments {
2060
+ display: flex;
2061
+ flex-wrap: wrap;
2062
+ gap: calc(var(--adechat-space) * 0.5);
2063
+ margin-top: calc(var(--adechat-space) * 0.5);
2064
+ }
2065
+ .adechat-attachment {
2066
+ font-size: 0.8em;
2067
+ padding: 2px 8px;
2068
+ border-radius: var(--adechat-radius-sm);
2069
+ border: 1px solid var(--adechat-border);
2070
+ color: var(--adechat-muted);
2071
+ }
2072
+
2073
+ .adechat-assistant {
2074
+ max-width: 100%;
2075
+ word-break: break-word;
2076
+ }
2077
+ .adechat-assistant > :first-child { margin-top: 0; }
2078
+ .adechat-assistant > :last-child { margin-bottom: 0; }
2079
+ .adechat-assistant p { margin: 0 0 0.75em; }
2080
+ .adechat-assistant h1,
2081
+ .adechat-assistant h2,
2082
+ .adechat-assistant h3 { margin: 1em 0 0.4em; line-height: 1.25; }
2083
+ .adechat-assistant h1 { font-size: 1.35em; }
2084
+ .adechat-assistant h2 { font-size: 1.2em; }
2085
+ .adechat-assistant h3 { font-size: 1.05em; }
2086
+ .adechat-assistant ul,
2087
+ .adechat-assistant ol { margin: 0 0 0.75em; padding-left: 1.4em; }
2088
+ .adechat-assistant li { margin: 0.15em 0; }
2089
+ .adechat-assistant a { color: var(--adechat-accent); }
2090
+ .adechat-assistant blockquote {
2091
+ margin: 0 0 0.75em;
2092
+ padding-left: calc(var(--adechat-space) * 1.25);
2093
+ border-left: 2px solid var(--adechat-border-strong);
2094
+ color: var(--adechat-muted);
2095
+ }
2096
+ .adechat-assistant hr {
2097
+ border: 0;
2098
+ border-top: 1px solid var(--adechat-border);
2099
+ margin: 1em 0;
2100
+ }
2101
+ .adechat-code-inline {
2102
+ font-family: var(--adechat-font-mono);
2103
+ font-size: 0.9em;
2104
+ padding: 1px 5px;
2105
+ border-radius: var(--adechat-radius-sm);
2106
+ background: var(--adechat-bg-raised);
2107
+ }
2108
+ .adechat-code-block {
2109
+ font-family: var(--adechat-font-mono);
2110
+ font-size: 0.88em;
2111
+ margin: 0 0 0.75em;
2112
+ padding: calc(var(--adechat-space) * 1.25);
2113
+ border-radius: var(--adechat-radius);
2114
+ border: 1px solid var(--adechat-border);
2115
+ background: var(--adechat-bg-subtle);
2116
+ overflow-x: auto;
2117
+ white-space: pre;
2118
+ }
2119
+
2120
+ /* Reasoning -------------------------------------------------------------- */
2121
+
2122
+ .adechat-reasoning { align-self: stretch; }
2123
+ .adechat-reasoning-toggle {
2124
+ display: inline-flex;
2125
+ align-items: center;
2126
+ gap: calc(var(--adechat-space) * 0.5);
2127
+ font: inherit;
2128
+ font-size: 0.88em;
2129
+ color: var(--adechat-muted);
2130
+ background: none;
2131
+ border: 0;
2132
+ padding: 2px 0;
2133
+ cursor: pointer;
2134
+ }
2135
+ .adechat-reasoning-toggle:hover { color: var(--adechat-fg); }
2136
+ .adechat-reasoning-body {
2137
+ margin-top: calc(var(--adechat-space) * 0.75);
2138
+ padding: calc(var(--adechat-space) * 1.25);
2139
+ border-radius: var(--adechat-radius);
2140
+ border: 1px solid var(--adechat-border);
2141
+ background: var(--adechat-bg-subtle);
2142
+ color: var(--adechat-muted);
2143
+ white-space: pre-wrap;
2144
+ font-size: 0.92em;
2145
+ }
2146
+
2147
+ /* Tool chips ------------------------------------------------------------- */
2148
+
2149
+ .adechat-chip {
2150
+ align-self: flex-start;
2151
+ max-width: 100%;
2152
+ border: 1px solid var(--adechat-border);
2153
+ border-radius: var(--adechat-radius);
2154
+ background: var(--adechat-bg-subtle);
2155
+ overflow: hidden;
2156
+ }
2157
+ .adechat-chip-head {
2158
+ display: flex;
2159
+ align-items: center;
2160
+ gap: calc(var(--adechat-space) * 0.75);
2161
+ width: 100%;
2162
+ font: inherit;
2163
+ font-size: 0.88em;
2164
+ text-align: left;
2165
+ color: var(--adechat-fg);
2166
+ background: none;
2167
+ border: 0;
2168
+ padding: calc(var(--adechat-space) * 0.625) calc(var(--adechat-space) * 1.25);
2169
+ cursor: pointer;
2170
+ }
2171
+ .adechat-chip-head:hover { background: var(--adechat-hover); }
2172
+ .adechat-chip-head[aria-disabled="true"] { cursor: default; }
2173
+ .adechat-chip-head[aria-disabled="true"]:hover { background: none; }
2174
+ .adechat-chip-label {
2175
+ overflow: hidden;
2176
+ text-overflow: ellipsis;
2177
+ white-space: nowrap;
2178
+ }
2179
+ .adechat-chip-elapsed { color: var(--adechat-muted); font-variant-numeric: tabular-nums; }
2180
+ .adechat-chip-icon { display: inline-flex; flex: 0 0 auto; }
2181
+ .adechat-chip-dot {
2182
+ flex: 0 0 auto;
2183
+ width: 6px;
2184
+ height: 6px;
2185
+ border-radius: 50%;
2186
+ background: var(--adechat-muted);
2187
+ }
2188
+ .adechat-chip-dot[data-status="running"] {
2189
+ background: var(--adechat-accent);
2190
+ animation: adechat-pulse 1.4s ease-in-out infinite;
2191
+ }
2192
+ .adechat-chip-dot[data-status="failed"] { background: var(--adechat-danger); }
2193
+ .adechat-chip-dot[data-status="completed"] { background: var(--adechat-success); }
2194
+ .adechat-chip-body {
2195
+ border-top: 1px solid var(--adechat-border);
2196
+ padding: calc(var(--adechat-space) * 1.25);
2197
+ display: flex;
2198
+ flex-direction: column;
2199
+ gap: calc(var(--adechat-space) * 0.75);
2200
+ }
2201
+ .adechat-chip-section-label {
2202
+ font-size: 0.75em;
2203
+ text-transform: uppercase;
2204
+ letter-spacing: 0.06em;
2205
+ color: var(--adechat-muted);
2206
+ margin-bottom: 4px;
2207
+ }
2208
+ .adechat-chip-actions {
2209
+ display: flex;
2210
+ flex-wrap: wrap;
2211
+ gap: calc(var(--adechat-space) * 0.5);
2212
+ padding: 0 calc(var(--adechat-space) * 1.25) calc(var(--adechat-space) * 0.75);
2213
+ }
2214
+ .adechat-chip-action {
2215
+ font: inherit;
2216
+ font-size: 0.8em;
2217
+ color: var(--adechat-accent);
2218
+ background: var(--adechat-accent-subtle);
2219
+ border: 0;
2220
+ border-radius: var(--adechat-radius-sm);
2221
+ padding: 2px 8px;
2222
+ cursor: pointer;
2223
+ }
2224
+ .adechat-chip-action:hover { filter: brightness(1.1); }
2225
+ .adechat-tool-result { margin-top: calc(var(--adechat-space) * 0.5); }
2226
+ .adechat-chip-pre {
2227
+ font-family: var(--adechat-font-mono);
2228
+ font-size: 0.85em;
2229
+ margin: 0;
2230
+ max-height: 320px;
2231
+ overflow: auto;
2232
+ white-space: pre-wrap;
2233
+ word-break: break-word;
2234
+ color: var(--adechat-muted);
2235
+ }
2236
+
2237
+ /* Errors ----------------------------------------------------------------- */
2238
+
2239
+ .adechat-error {
2240
+ align-self: stretch;
2241
+ border: 1px solid var(--adechat-danger);
2242
+ background: var(--adechat-danger-subtle);
2243
+ border-radius: var(--adechat-radius);
2244
+ padding: calc(var(--adechat-space) * 1.25);
2245
+ }
2246
+ .adechat-error-message { font-weight: 600; }
2247
+ .adechat-error-detail {
2248
+ margin: calc(var(--adechat-space) * 0.5) 0 0;
2249
+ font-family: var(--adechat-font-mono);
2250
+ font-size: 0.85em;
2251
+ white-space: pre-wrap;
2252
+ color: var(--adechat-muted);
2253
+ }
2254
+
2255
+ /* Approvals -------------------------------------------------------------- */
2256
+
2257
+ .adechat-approval {
2258
+ align-self: stretch;
2259
+ display: flex;
2260
+ flex-direction: column;
2261
+ gap: calc(var(--adechat-space) * 0.75);
2262
+ padding: calc(var(--adechat-space) * 1.25);
2263
+ border: 1px solid var(--adechat-border-strong);
2264
+ border-radius: var(--adechat-radius);
2265
+ background: var(--adechat-bg-subtle);
2266
+ }
2267
+ .adechat-approval[data-state="pending"] { border-color: var(--adechat-accent); }
2268
+ .adechat-approval[data-state="rejected"],
2269
+ .adechat-approval[data-state="cancelled"] { border-color: var(--adechat-border); }
2270
+ .adechat-approval[data-state="expired"] { border-color: var(--adechat-border); opacity: 0.75; }
2271
+ .adechat-approval-head {
2272
+ display: flex;
2273
+ align-items: baseline;
2274
+ gap: calc(var(--adechat-space) * 0.75);
2275
+ }
2276
+ .adechat-approval-title { font-weight: 600; flex: 1 1 auto; }
2277
+ .adechat-approval-settled { font-size: 0.85em; color: var(--adechat-muted); }
2278
+ .adechat-approval-command {
2279
+ margin: 0;
2280
+ padding: calc(var(--adechat-space) * 0.75) calc(var(--adechat-space) * 1);
2281
+ border-radius: var(--adechat-radius-sm);
2282
+ background: var(--adechat-bg);
2283
+ border: 1px solid var(--adechat-border);
2284
+ font-family: var(--adechat-font-mono);
2285
+ font-size: 0.85em;
2286
+ white-space: pre-wrap;
2287
+ overflow-x: auto;
2288
+ }
2289
+ .adechat-approval-path { margin: 0; font-family: var(--adechat-font-mono); font-size: 0.85em; }
2290
+ .adechat-approval-note { margin: 0; font-size: 0.88em; color: var(--adechat-muted); }
2291
+ .adechat-approval-error { margin: 0; font-size: 0.88em; color: var(--adechat-danger); }
2292
+ .adechat-approval-actions {
2293
+ display: flex;
2294
+ flex-wrap: wrap;
2295
+ gap: calc(var(--adechat-space) * 0.75);
2296
+ }
2297
+ /* The card never takes focus, so reaching it by keyboard has to be visible. */
2298
+ .adechat-approval-actions .adechat-button:focus-visible {
2299
+ outline: 2px solid var(--adechat-accent);
2300
+ outline-offset: 2px;
2301
+ }
2302
+
2303
+ /* Pending input, queue and account surfaces ------------------------------ */
2304
+ .adechat-pending-question {
2305
+ display: flex;
2306
+ flex-direction: column;
2307
+ gap: calc(var(--adechat-space) * 0.75);
2308
+ min-width: 0;
2309
+ margin: 0;
2310
+ padding: calc(var(--adechat-space) * 0.75);
2311
+ border: 1px solid var(--adechat-border);
2312
+ border-radius: var(--adechat-radius-sm);
2313
+ }
2314
+ .adechat-pending-question legend { padding: 0 calc(var(--adechat-space) * 0.5); font-weight: 600; }
2315
+ .adechat-pending-plan,
2316
+ .adechat-pending-description { margin: 0; white-space: pre-wrap; }
2317
+ .adechat-pending-option { display: flex; align-items: flex-start; gap: calc(var(--adechat-space) * 0.75); }
2318
+ .adechat-pending-option span { display: flex; flex-direction: column; gap: calc(var(--adechat-space) * 0.25); }
2319
+ .adechat-pending-option small { color: var(--adechat-muted); }
2320
+ .adechat-pending-answer,
2321
+ .adechat-queue-edit input,
2322
+ .adechat-api-key-form input,
2323
+ .adechat-sign-in-code-form input {
2324
+ min-width: 0;
2325
+ width: 100%;
2326
+ padding: calc(var(--adechat-space) * 0.75);
2327
+ border: 1px solid var(--adechat-border);
2328
+ border-radius: var(--adechat-radius-sm);
2329
+ background: var(--adechat-bg);
2330
+ color: var(--adechat-fg);
2331
+ font: inherit;
2332
+ }
2333
+ .adechat-pending-answer { min-height: 4.5em; resize: vertical; }
2334
+ .adechat-queue { padding: calc(var(--adechat-space) * 1.25); border-top: 1px solid var(--adechat-border); }
2335
+ .adechat-queue-list { display: flex; flex-direction: column; gap: calc(var(--adechat-space) * 0.75); margin: 0; padding: 0; list-style: none; }
2336
+ .adechat-queue-item { display: flex; align-items: center; gap: calc(var(--adechat-space) * 0.75); min-width: 0; }
2337
+ .adechat-queue-text { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
2338
+ .adechat-queue-actions,
2339
+ .adechat-queue-edit { display: flex; align-items: center; flex-wrap: wrap; gap: calc(var(--adechat-space) * 0.5); }
2340
+ .adechat-queue-edit { flex: 1 1 auto; }
2341
+ .adechat-queue-state,
2342
+ .adechat-account-state { margin: 0; color: var(--adechat-muted); }
2343
+ .adechat-queue-error,
2344
+ .adechat-account-error,
2345
+ .adechat-usage-limit-error,
2346
+ .adechat-slash-error { display: flex; align-items: center; flex-wrap: wrap; gap: calc(var(--adechat-space) * 0.75); color: var(--adechat-danger); }
2347
+ .adechat-slash-menu { display: flex; flex-direction: column; max-height: 16rem; overflow-y: auto; padding: calc(var(--adechat-space) * 0.5); border: 1px solid var(--adechat-border); border-radius: var(--adechat-radius-sm); background: var(--adechat-bg-raised); }
2348
+ .adechat-slash-option { display: grid; grid-template-columns: auto 1fr; gap: calc(var(--adechat-space) * 0.25) calc(var(--adechat-space) * 0.75); padding: calc(var(--adechat-space) * 0.75); border: 0; border-radius: var(--adechat-radius-sm); background: transparent; color: var(--adechat-fg); text-align: left; font: inherit; cursor: pointer; }
2349
+ .adechat-slash-option[aria-selected="true"],
2350
+ .adechat-slash-option:hover { background: var(--adechat-hover); }
2351
+ .adechat-slash-option small { color: var(--adechat-muted); }
2352
+ .adechat-slash-description { grid-column: 1 / -1; color: var(--adechat-muted); font-size: 0.85em; }
2353
+ .adechat-slash-state { margin: 0; padding: calc(var(--adechat-space) * 0.75); color: var(--adechat-muted); }
2354
+ .adechat-account-list { display: flex; flex-direction: column; gap: calc(var(--adechat-space) * 1); }
2355
+ .adechat-account { display: flex; align-items: center; flex-wrap: wrap; gap: calc(var(--adechat-space) * 1); padding: calc(var(--adechat-space) * 1.25); border: 1px solid var(--adechat-border); border-radius: var(--adechat-radius); background: var(--adechat-bg-subtle); }
2356
+ .adechat-account-summary { display: flex; flex: 1 1 14rem; flex-direction: column; gap: calc(var(--adechat-space) * 0.25); min-width: 0; }
2357
+ .adechat-account-summary span,
2358
+ .adechat-usage-meter-reset { color: var(--adechat-muted); font-size: 0.85em; }
2359
+ .adechat-usage-meter { display: flex; flex: 1 1 10rem; flex-direction: column; gap: calc(var(--adechat-space) * 0.5); }
2360
+ .adechat-usage-meter-label { display: flex; justify-content: space-between; gap: calc(var(--adechat-space) * 1); font-size: 0.85em; }
2361
+ .adechat-usage-meter-track { height: 0.45rem; overflow: hidden; border-radius: 999px; background: var(--adechat-border); }
2362
+ .adechat-usage-meter-track span { display: block; height: 100%; border-radius: inherit; background: var(--adechat-accent); }
2363
+ .adechat-sign-in,
2364
+ .adechat-sign-in-code-form,
2365
+ .adechat-api-key-form { display: flex; flex-direction: column; align-items: flex-start; gap: calc(var(--adechat-space) * 1); }
2366
+ .adechat-sign-in-code-form label,
2367
+ .adechat-api-key-form label { display: flex; flex-direction: column; gap: calc(var(--adechat-space) * 0.5); width: 100%; }
2368
+ .adechat-sign-in-code { overflow-wrap: anywhere; }
2369
+ .adechat-account-switcher { display: inline-flex; align-items: center; gap: calc(var(--adechat-space) * 0.75); }
2370
+ .adechat-account-switcher select { max-width: 100%; padding: calc(var(--adechat-space) * 0.5); border: 1px solid var(--adechat-border); border-radius: var(--adechat-radius-sm); background: var(--adechat-bg); color: var(--adechat-fg); font: inherit; }
2371
+ .adechat-usage-limit { display: flex; align-items: center; flex-wrap: wrap; gap: calc(var(--adechat-space) * 1); padding: calc(var(--adechat-space) * 1.25); border-bottom: 1px solid var(--adechat-border); background: var(--adechat-bg-subtle); }
2372
+ .adechat-usage-limit-copy { display: flex; flex: 1 1 14rem; flex-direction: column; gap: calc(var(--adechat-space) * 0.25); }
2373
+ .adechat-usage-limit-copy span { color: var(--adechat-muted); font-size: 0.9em; }
2374
+ .adechat-usage-limit-actions { display: flex; flex-wrap: wrap; gap: calc(var(--adechat-space) * 0.75); }
2375
+
2376
+ /* Live activity ---------------------------------------------------------- */
2377
+
2378
+ .adechat-activity {
2379
+ display: flex;
2380
+ align-items: center;
2381
+ gap: calc(var(--adechat-space) * 0.75);
2382
+ color: var(--adechat-muted);
2383
+ font-size: 0.9em;
2384
+ }
2385
+ .adechat-activity-dot {
2386
+ width: 6px;
2387
+ height: 6px;
2388
+ border-radius: 50%;
2389
+ background: var(--adechat-accent);
2390
+ animation: adechat-pulse 1.4s ease-in-out infinite;
2391
+ }
2392
+
2393
+ @keyframes adechat-pulse {
2394
+ 0%, 100% { opacity: 1; }
2395
+ 50% { opacity: 0.35; }
2396
+ }
2397
+
2398
+ /* Composer --------------------------------------------------------------- */
2399
+
2400
+ .adechat-composer {
2401
+ flex: 0 0 auto;
2402
+ display: flex;
2403
+ flex-direction: column;
2404
+ gap: calc(var(--adechat-space) * 0.75);
2405
+ padding: calc(var(--adechat-space) * 1.5);
2406
+ border-top: 1px solid var(--adechat-border);
2407
+ background: var(--adechat-root-bg, var(--adechat-bg));
2408
+ }
2409
+ .adechat-composer-surface {
2410
+ display: flex;
2411
+ flex-direction: column;
2412
+ gap: calc(var(--adechat-space) * 0.75);
2413
+ padding: calc(var(--adechat-space) * 1);
2414
+ border: 1px solid var(--adechat-border);
2415
+ border-radius: var(--adechat-radius);
2416
+ background: var(--adechat-bg-subtle);
2417
+ }
2418
+ .adechat-composer-surface:focus-within { border-color: var(--adechat-border-strong); }
2419
+ .adechat-composer-input {
2420
+ font: inherit;
2421
+ color: var(--adechat-fg);
2422
+ background: none;
2423
+ border: 0;
2424
+ outline: none;
2425
+ resize: none;
2426
+ width: 100%;
2427
+ min-height: 22px;
2428
+ max-height: 40vh;
2429
+ overflow-y: auto;
2430
+ }
2431
+ .adechat-composer-input::placeholder { color: var(--adechat-muted); }
2432
+ .adechat-composer-input:disabled { opacity: 0.6; cursor: not-allowed; }
2433
+ .adechat-composer-actions {
2434
+ display: flex;
2435
+ align-items: center;
2436
+ gap: calc(var(--adechat-space) * 0.75);
2437
+ }
2438
+ .adechat-composer-rail { display: flex; align-items: center; gap: calc(var(--adechat-space) * 0.5); min-width: 0; }
2439
+ .adechat-composer-spacer { flex: 1 1 auto; }
2440
+ .adechat-composer-hint { color: var(--adechat-muted); font-size: 0.8em; }
2441
+ .adechat-composer-error { color: var(--adechat-danger); font-size: 0.85em; }
2442
+
2443
+ .adechat-button {
2444
+ display: inline-flex;
2445
+ align-items: center;
2446
+ gap: calc(var(--adechat-space) * 0.5);
2447
+ font: inherit;
2448
+ font-size: 0.9em;
2449
+ padding: calc(var(--adechat-space) * 0.625) calc(var(--adechat-space) * 1.25);
2450
+ border-radius: var(--adechat-radius-sm);
2451
+ border: 1px solid var(--adechat-border);
2452
+ background: var(--adechat-bg-raised);
2453
+ color: var(--adechat-fg);
2454
+ cursor: pointer;
2455
+ }
2456
+ .adechat-button:hover:not(:disabled) { background: var(--adechat-hover); }
2457
+ .adechat-button:disabled { opacity: 0.45; cursor: not-allowed; }
2458
+ .adechat-button[data-variant="primary"] {
2459
+ background: var(--adechat-accent);
2460
+ border-color: var(--adechat-accent);
2461
+ color: var(--adechat-accent-fg);
2462
+ }
2463
+ .adechat-button[data-variant="danger"] {
2464
+ background: var(--adechat-danger-subtle);
2465
+ border-color: var(--adechat-danger);
2466
+ color: var(--adechat-danger);
2467
+ }
2468
+ .adechat-button-icon { padding: calc(var(--adechat-space) * 0.625); }
2469
+
2470
+ /* Model picker ----------------------------------------------------------- */
2471
+
2472
+ .adechat-modelpicker {
2473
+ display: flex;
2474
+ min-height: 0;
2475
+ height: 320px;
2476
+ width: 460px;
2477
+ max-width: 100%;
2478
+ border: 1px solid var(--adechat-border);
2479
+ border-radius: var(--adechat-radius);
2480
+ background: var(--adechat-bg-raised);
2481
+ overflow: hidden;
2482
+ }
2483
+ .adechat-modelpicker-rail {
2484
+ display: flex;
2485
+ flex-direction: column;
2486
+ gap: 2px;
2487
+ flex: 0 0 auto;
2488
+ width: 132px;
2489
+ padding: calc(var(--adechat-space) * 0.5);
2490
+ border-right: 1px solid var(--adechat-border);
2491
+ background: var(--adechat-bg-subtle);
2492
+ overflow-y: auto;
2493
+ }
2494
+ .adechat-modelpicker-railbutton {
2495
+ display: flex;
2496
+ align-items: center;
2497
+ gap: calc(var(--adechat-space) * 0.75);
2498
+ font: inherit;
2499
+ font-size: 0.88em;
2500
+ text-align: left;
2501
+ width: 100%;
2502
+ padding: calc(var(--adechat-space) * 0.625) calc(var(--adechat-space) * 0.875);
2503
+ border: 0;
2504
+ border-radius: var(--adechat-radius-sm);
2505
+ background: none;
2506
+ color: var(--adechat-muted);
2507
+ cursor: pointer;
2508
+ }
2509
+ .adechat-modelpicker-railbutton:hover { background: var(--adechat-hover); color: var(--adechat-fg); }
2510
+ .adechat-modelpicker-railbutton[aria-selected="true"] {
2511
+ background: var(--adechat-accent-subtle);
2512
+ color: var(--adechat-fg);
2513
+ }
2514
+ .adechat-modelpicker-raillabel {
2515
+ flex: 1 1 auto;
2516
+ overflow: hidden;
2517
+ text-overflow: ellipsis;
2518
+ white-space: nowrap;
2519
+ }
2520
+ .adechat-status-dot {
2521
+ flex: 0 0 auto;
2522
+ width: 6px;
2523
+ height: 6px;
2524
+ border-radius: 50%;
2525
+ }
2526
+ .adechat-status-dot[data-status="ok"] { background: var(--adechat-success); }
2527
+ .adechat-status-dot[data-status="unauthed"] { background: var(--adechat-danger); }
2528
+ .adechat-status-dot[data-status="missing"] { background: var(--adechat-muted); }
2529
+
2530
+ .adechat-modelpicker-main { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
2531
+ .adechat-modelpicker-search {
2532
+ font: inherit;
2533
+ font-size: 0.9em;
2534
+ color: var(--adechat-fg);
2535
+ background: none;
2536
+ border: 0;
2537
+ border-bottom: 1px solid var(--adechat-border);
2538
+ outline: none;
2539
+ padding: calc(var(--adechat-space) * 1) calc(var(--adechat-space) * 1.25);
2540
+ }
2541
+ .adechat-modelpicker-list {
2542
+ flex: 1 1 auto;
2543
+ min-height: 0;
2544
+ overflow-y: auto;
2545
+ padding: calc(var(--adechat-space) * 0.5);
2546
+ margin: 0;
2547
+ list-style: none;
2548
+ }
2549
+ .adechat-modelpicker-group {
2550
+ font-size: 0.72em;
2551
+ text-transform: uppercase;
2552
+ letter-spacing: 0.07em;
2553
+ color: var(--adechat-muted);
2554
+ padding: calc(var(--adechat-space) * 0.75) calc(var(--adechat-space) * 0.875) 4px;
2555
+ }
2556
+ .adechat-modelpicker-row {
2557
+ display: flex;
2558
+ align-items: baseline;
2559
+ gap: calc(var(--adechat-space) * 0.75);
2560
+ width: 100%;
2561
+ font: inherit;
2562
+ font-size: 0.9em;
2563
+ text-align: left;
2564
+ padding: calc(var(--adechat-space) * 0.625) calc(var(--adechat-space) * 0.875);
2565
+ border: 0;
2566
+ border-radius: var(--adechat-radius-sm);
2567
+ background: none;
2568
+ color: var(--adechat-fg);
2569
+ cursor: pointer;
2570
+ }
2571
+ .adechat-modelpicker-row:hover:not(:disabled) { background: var(--adechat-hover); }
2572
+ .adechat-modelpicker-row:disabled { opacity: 0.45; cursor: not-allowed; }
2573
+ .adechat-modelpicker-row[aria-selected="true"] { background: var(--adechat-accent-subtle); }
2574
+ .adechat-modelpicker-rowname { flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2575
+ .adechat-modelpicker-rowmeta { flex: 1 1 auto; color: var(--adechat-muted); font-size: 0.85em; text-align: right; }
2576
+ .adechat-modelpicker-effort {
2577
+ display: flex;
2578
+ align-items: center;
2579
+ flex-wrap: wrap;
2580
+ gap: calc(var(--adechat-space) * 0.5);
2581
+ padding: calc(var(--adechat-space) * 0.75) calc(var(--adechat-space) * 1);
2582
+ border-top: 1px solid var(--adechat-border);
2583
+ }
2584
+ .adechat-modelpicker-effortlabel { color: var(--adechat-muted); font-size: 0.8em; margin-right: auto; }
2585
+ .adechat-modelpicker-effortoption {
2586
+ font: inherit;
2587
+ font-size: 0.8em;
2588
+ color: var(--adechat-fg);
2589
+ background: none;
2590
+ border: 1px solid var(--adechat-border);
2591
+ border-radius: var(--adechat-radius-sm);
2592
+ padding: 2px 8px;
2593
+ cursor: pointer;
2594
+ }
2595
+ .adechat-modelpicker-effortoption:hover { background: var(--adechat-hover); }
2596
+ .adechat-modelpicker-effortoption[aria-checked="true"] {
2597
+ background: var(--adechat-accent-subtle);
2598
+ border-color: var(--adechat-accent);
2599
+ }
2600
+ .adechat-modelpicker-empty { padding: calc(var(--adechat-space) * 2); color: var(--adechat-muted); font-size: 0.9em; }
2601
+
2602
+ /* Provider card ---------------------------------------------------------- */
2603
+
2604
+ .adechat-providercard {
2605
+ display: flex;
2606
+ flex-direction: column;
2607
+ gap: calc(var(--adechat-space) * 1);
2608
+ padding: calc(var(--adechat-space) * 1.5);
2609
+ border: 1px solid var(--adechat-border);
2610
+ border-radius: var(--adechat-radius);
2611
+ background: var(--adechat-bg-subtle);
2612
+ color: var(--adechat-fg);
2613
+ }
2614
+ .adechat-providercard-head { display: flex; align-items: center; gap: calc(var(--adechat-space) * 0.75); }
2615
+ .adechat-providercard-name { font-weight: 600; flex: 1 1 auto; }
2616
+ .adechat-providercard-state { font-size: 0.85em; color: var(--adechat-muted); }
2617
+ .adechat-providercard-detail { font-size: 0.88em; color: var(--adechat-muted); margin: 0; }
2618
+ .adechat-providercard-probe {
2619
+ display: flex;
2620
+ align-items: baseline;
2621
+ gap: calc(var(--adechat-space) * 0.75);
2622
+ margin: 0;
2623
+ font-size: 0.82em;
2624
+ color: var(--adechat-muted);
2625
+ min-width: 0;
2626
+ }
2627
+ .adechat-providercard-probe code {
2628
+ font-family: var(--adechat-font-mono);
2629
+ overflow: hidden;
2630
+ text-overflow: ellipsis;
2631
+ white-space: nowrap;
2632
+ }
2633
+ .adechat-command {
2634
+ display: flex;
2635
+ align-items: center;
2636
+ gap: calc(var(--adechat-space) * 0.75);
2637
+ padding: calc(var(--adechat-space) * 0.75) calc(var(--adechat-space) * 1);
2638
+ border: 1px solid var(--adechat-border);
2639
+ border-radius: var(--adechat-radius-sm);
2640
+ background: var(--adechat-bg);
2641
+ }
2642
+ .adechat-command-text {
2643
+ flex: 1 1 auto;
2644
+ font-family: var(--adechat-font-mono);
2645
+ font-size: 0.85em;
2646
+ overflow-x: auto;
2647
+ white-space: nowrap;
2648
+ }
2649
+
2650
+ /* Motion ----------------------------------------------------------------- */
2651
+
2652
+ @media (prefers-reduced-motion: reduce) {
2653
+ .adechat-root *,
2654
+ .adechat-root *::before,
2655
+ .adechat-root *::after {
2656
+ animation-duration: 0.001ms !important;
2657
+ animation-iteration-count: 1 !important;
2658
+ transition-duration: 0.001ms !important;
2659
+ }
2660
+ .adechat-chip-dot[data-status="running"],
2661
+ .adechat-activity-dot { animation: none; opacity: 0.7; }
2662
+ }
2663
+ `;
2664
+ function injectDaexChatStyles(target, options = {}) {
2665
+ const doc = target ?? (typeof document === "undefined" ? null : document);
2666
+ if (!doc) return;
2667
+ if (doc.getElementById(ADE_CHAT_STYLE_ID)) return;
2668
+ const style = doc.createElement("style");
2669
+ style.id = ADE_CHAT_STYLE_ID;
2670
+ if (options.nonce) {
2671
+ style.setAttribute("nonce", options.nonce);
2672
+ style.nonce = options.nonce;
2673
+ }
2674
+ style.textContent = daexChatCss;
2675
+ doc.head.appendChild(style);
2676
+ }
2677
+ var adeChatCss = daexChatCss;
2678
+ var injectAdeChatStyles = injectDaexChatStyles;
2679
+
2680
+ // src/theme/AdeChatStyles.tsx
2681
+ function DaexChatStyles({ nonce } = {}) {
2682
+ useEffect(() => {
2683
+ injectDaexChatStyles(void 0, nonce ? { nonce } : {});
2684
+ }, [nonce]);
2685
+ return null;
2686
+ }
2687
+ var AdeChatStyles = DaexChatStyles;
2688
+
2689
+ // src/activity/labels.ts
2690
+ var DEFAULT_ELAPSED_AFTER_MS = 3e3;
2691
+ var DEFAULT_THINKING_LABEL = "Working\u2026";
2692
+ var TIER = 1e6;
2693
+ var QUALIFIED_WILDCARD_BONUS = 1e4;
2694
+ var RENAMED_SERVERS = { "ade-cto": "daex-cto" };
2695
+ function currentServerName(server) {
2696
+ return server === null ? null : RENAMED_SERVERS[server] ?? server;
2697
+ }
2698
+ function scoreLabelKey(key, candidate, identity) {
2699
+ if (key === candidate) return 4 * TIER;
2700
+ const parsed = parseToolIdentity(key);
2701
+ const wildcard = parsed.tool.endsWith("*");
2702
+ const toolPrefix = wildcard ? parsed.tool.slice(0, -1) : parsed.tool;
2703
+ if (parsed.server !== null) {
2704
+ if (currentServerName(identity.server) !== currentServerName(parsed.server)) return -1;
2705
+ if (!wildcard) return parsed.tool === identity.tool ? 3 * TIER : -1;
2706
+ if (!identity.tool.startsWith(toolPrefix)) return -1;
2707
+ return TIER + QUALIFIED_WILDCARD_BONUS + toolPrefix.length;
2708
+ }
2709
+ if (!wildcard) {
2710
+ return identity.server !== null && key === identity.tool ? 2 * TIER : -1;
2711
+ }
2712
+ let best = -1;
2713
+ if (candidate.startsWith(toolPrefix)) best = TIER + toolPrefix.length;
2714
+ if (identity.server !== null && identity.tool.startsWith(toolPrefix)) {
2715
+ best = Math.max(best, TIER + toolPrefix.length);
2716
+ }
2717
+ return best;
2718
+ }
2719
+ function matchLabelKey(keys, candidate, identity = parseToolIdentity(candidate)) {
2720
+ let best = null;
2721
+ let bestScore = -1;
2722
+ for (const key of keys) {
2723
+ const score = scoreLabelKey(key, candidate, identity);
2724
+ if (score < 0) continue;
2725
+ if (score >= 4 * TIER) return key;
2726
+ if (score >= bestScore) {
2727
+ best = key;
2728
+ bestScore = score;
2729
+ }
2730
+ }
2731
+ return best;
2732
+ }
2733
+ function entryForPhase(entry, phase) {
2734
+ if (typeof entry === "string") {
2735
+ return phase === "running" ? entry : null;
2736
+ }
2737
+ const value = entry[phase];
2738
+ return typeof value === "string" && value.length > 0 ? value : null;
2739
+ }
2740
+ function resolveActivityLabel(source, config) {
2741
+ if (!config) return null;
2742
+ const custom = config.resolve?.(source);
2743
+ if (typeof custom === "string" && custom.length > 0) return custom;
2744
+ if (source.kind === "thinking") {
2745
+ return config.thinkingLabel ?? null;
2746
+ }
2747
+ const key = source.tool;
2748
+ if (!key || !config.map) return null;
2749
+ const identity = source.kind === "tool" ? source.event.identity : void 0;
2750
+ const matched = matchLabelKey(Object.keys(config.map), key, identity);
2751
+ if (!matched) return null;
2752
+ return entryForPhase(config.map[matched], source.phase);
2753
+ }
2754
+ function resolveActivityIcon(tool, config, identity) {
2755
+ if (!tool || !config?.icons) return void 0;
2756
+ const matched = matchLabelKey(Object.keys(config.icons), tool, identity);
2757
+ return matched ? config.icons[matched] : void 0;
2758
+ }
2759
+ function phaseForToolStatus(status) {
2760
+ if (status === "running") return "running";
2761
+ if (status === "failed") return "error";
2762
+ return "done";
2763
+ }
2764
+ function formatElapsed(elapsedMs, elapsedAfterMs = DEFAULT_ELAPSED_AFTER_MS) {
2765
+ if (!Number.isFinite(elapsedMs) || elapsedMs < elapsedAfterMs) return null;
2766
+ const totalSeconds = Math.floor(elapsedMs / 1e3);
2767
+ if (totalSeconds < 60) return `${totalSeconds}s`;
2768
+ const minutes = Math.floor(totalSeconds / 60);
2769
+ const seconds = totalSeconds % 60;
2770
+ if (minutes < 60) return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
2771
+ const hours = Math.floor(minutes / 60);
2772
+ return `${hours}h ${minutes % 60}m`;
2773
+ }
2774
+ function describeToolActivity(input) {
2775
+ const { chip, config } = input;
2776
+ const phase = phaseForToolStatus(chip.status);
2777
+ const label = resolveActivityLabel({ kind: "tool", tool: chip.tool, phase, event: chip }, config) ?? chip.tool;
2778
+ const elapsed = phase === "running" && typeof input.elapsedMs === "number" ? formatElapsed(input.elapsedMs, config?.elapsedAfterMs ?? DEFAULT_ELAPSED_AFTER_MS) : null;
2779
+ return { label, elapsed, icon: resolveActivityIcon(chip.tool, config, chip.identity) };
2780
+ }
2781
+ var DEFAULT_LABELS = {
2782
+ accept: "Allow once",
2783
+ acceptAlways: "Always allow",
2784
+ reject: "Reject"
2785
+ };
2786
+ var SETTLED_COPY = {
2787
+ accepted: "Allowed",
2788
+ accepted_always: "Allowed for the rest of this session",
2789
+ rejected: "Rejected",
2790
+ cancelled: "Cancelled",
2791
+ expired: "The turn ended before this was answered."
2792
+ };
2793
+ var UNANSWERABLE_REQUEST_KINDS = /* @__PURE__ */ new Set([
2794
+ "question",
2795
+ "structured_question",
2796
+ "plan_approval",
2797
+ "model_selection"
2798
+ ]);
2799
+ var NO_APPROVE_NOTICE = "This host cannot answer approvals.";
2800
+ var UNANSWERABLE_NOTICE = "The assistant is waiting for an answer this UI cannot provide.";
2801
+ function approvalRequestFromRow(row) {
2802
+ const request = {
2803
+ itemId: row.id,
2804
+ kind: row.kind,
2805
+ description: row.description
2806
+ };
2807
+ if (row.requestKind !== void 0) request.requestKind = row.requestKind;
2808
+ if (row.turnId !== null) request.turnId = row.turnId;
2809
+ if (row.detail !== void 0) request.detail = row.detail;
2810
+ return request;
2811
+ }
2812
+ function readText(value) {
2813
+ if (typeof value === "string") return value.trim() ? value : null;
2814
+ if (Array.isArray(value) && value.every((part) => typeof part === "string")) {
2815
+ const joined = value.join(" ").trim();
2816
+ return joined.length ? joined : null;
2817
+ }
2818
+ return null;
2819
+ }
2820
+ function readApprovalCommand(detail) {
2821
+ const record2 = readRecord(detail);
2822
+ if (!record2) return null;
2823
+ return readText(record2.command) ?? readText(readRecord(record2.input)?.command);
2824
+ }
2825
+ function readApprovalPaths(detail) {
2826
+ const record2 = readRecord(detail);
2827
+ if (!record2) return {};
2828
+ const path = readText(record2.path) ?? readText(readRecord(record2.input)?.path);
2829
+ const grantRoot = readText(record2.grantRoot);
2830
+ return {
2831
+ ...path ? { path } : {},
2832
+ ...grantRoot ? { grantRoot } : {}
2833
+ };
2834
+ }
2835
+ function ApprovalCard({ row, onApprove, options }) {
2836
+ const [submitted, setSubmitted] = useState(null);
2837
+ const [failure, setFailure] = useState(null);
2838
+ const request = approvalRequestFromRow(row);
2839
+ const unanswerable = row.requestKind !== void 0 && UNANSWERABLE_REQUEST_KINDS.has(row.requestKind);
2840
+ const answerable = Boolean(onApprove) && !unanswerable;
2841
+ const respond = useCallback(
2842
+ (decision) => {
2843
+ if (!onApprove) return;
2844
+ setSubmitted(decision);
2845
+ setFailure(null);
2846
+ void (async () => {
2847
+ try {
2848
+ await onApprove(row.id, decision);
2849
+ } catch (cause) {
2850
+ setSubmitted(null);
2851
+ setFailure(cause instanceof Error ? cause.message : String(cause));
2852
+ }
2853
+ })();
2854
+ },
2855
+ [onApprove, row.id]
2856
+ );
2857
+ if (options?.render) {
2858
+ return /* @__PURE__ */ jsx(Fragment, { children: options.render(request, respond) });
2859
+ }
2860
+ const state = resolveDisplayState(row.state, submitted);
2861
+ const settled = state !== "pending";
2862
+ const command = row.kind === "command" ? readApprovalCommand(row.detail) : null;
2863
+ const paths = row.kind === "file_change" ? readApprovalPaths(row.detail) : {};
2864
+ const title = options?.labels?.title?.(request) ?? row.description;
2865
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-approval", "data-state": state, "data-kind": row.kind, children: [
2866
+ /* @__PURE__ */ jsxs("div", { className: "adechat-approval-head", children: [
2867
+ /* @__PURE__ */ jsx("span", { className: "adechat-approval-title", children: title }),
2868
+ settled ? /* @__PURE__ */ jsx("span", { className: "adechat-approval-settled", children: SETTLED_COPY[state] }) : null
2869
+ ] }),
2870
+ command ? /* @__PURE__ */ jsx("pre", { className: "adechat-approval-command", children: command }) : null,
2871
+ paths.path ? /* @__PURE__ */ jsx("p", { className: "adechat-approval-path", children: /* @__PURE__ */ jsx("code", { children: paths.path }) }) : null,
2872
+ paths.grantRoot ? /* @__PURE__ */ jsxs("p", { className: "adechat-approval-note", children: [
2873
+ "Inside ",
2874
+ paths.grantRoot
2875
+ ] }) : null,
2876
+ unanswerable ? /* @__PURE__ */ jsx("p", { className: "adechat-approval-note", children: UNANSWERABLE_NOTICE }) : null,
2877
+ !unanswerable && !onApprove ? /* @__PURE__ */ jsx("p", { className: "adechat-approval-note", children: NO_APPROVE_NOTICE }) : null,
2878
+ answerable ? /* @__PURE__ */ jsxs("div", { className: "adechat-approval-actions", children: [
2879
+ /* @__PURE__ */ jsx(
2880
+ "button",
2881
+ {
2882
+ type: "button",
2883
+ className: "adechat-button",
2884
+ "data-variant": "primary",
2885
+ disabled: settled,
2886
+ onClick: () => respond("accept"),
2887
+ children: options?.labels?.accept ?? DEFAULT_LABELS.accept
2888
+ }
2889
+ ),
2890
+ /* @__PURE__ */ jsx(
2891
+ "button",
2892
+ {
2893
+ type: "button",
2894
+ className: "adechat-button",
2895
+ disabled: settled,
2896
+ onClick: () => respond("accept_always"),
2897
+ children: options?.labels?.acceptAlways ?? DEFAULT_LABELS.acceptAlways
2898
+ }
2899
+ ),
2900
+ /* @__PURE__ */ jsx(
2901
+ "button",
2902
+ {
2903
+ type: "button",
2904
+ className: "adechat-button",
2905
+ "data-variant": "danger",
2906
+ disabled: settled,
2907
+ onClick: () => respond("reject"),
2908
+ children: options?.labels?.reject ?? DEFAULT_LABELS.reject
2909
+ }
2910
+ )
2911
+ ] }) : null,
2912
+ failure ? /* @__PURE__ */ jsxs("p", { className: "adechat-approval-error", role: "alert", children: [
2913
+ "Could not send that answer: ",
2914
+ failure
2915
+ ] }) : null
2916
+ ] });
2917
+ }
2918
+ function resolveDisplayState(rowState, submitted) {
2919
+ if (rowState === "accepted" && submitted === "accept_always") return "accepted_always";
2920
+ if (rowState !== "pending") return rowState;
2921
+ if (submitted === "accept") return "accepted";
2922
+ if (submitted === "accept_always") return "accepted_always";
2923
+ if (submitted === "reject") return "rejected";
2924
+ return "pending";
2925
+ }
2926
+ function readOptions(value) {
2927
+ if (!Array.isArray(value)) return [];
2928
+ return value.flatMap((entry) => {
2929
+ const option = readRecord(entry);
2930
+ if (typeof option?.label !== "string" || typeof option.value !== "string") return [];
2931
+ return [{ label: option.label, value: option.value, ...typeof option.description === "string" ? { description: option.description } : {} }];
2932
+ });
2933
+ }
2934
+ function readQuestions(value) {
2935
+ if (!Array.isArray(value)) return [];
2936
+ return value.flatMap((entry) => {
2937
+ const question = readRecord(entry);
2938
+ if (typeof question?.id !== "string" || typeof question.question !== "string") return [];
2939
+ const options = readOptions(question.options);
2940
+ return [{
2941
+ id: question.id,
2942
+ question: question.question,
2943
+ ...typeof question.header === "string" ? { header: question.header } : {},
2944
+ ...options.length ? { options } : {},
2945
+ ...question.multiSelect === true ? { multiSelect: true } : {},
2946
+ ...typeof question.allowsFreeform === "boolean" ? { allowsFreeform: question.allowsFreeform } : {},
2947
+ ...question.isSecret === true ? { isSecret: true } : {}
2948
+ }];
2949
+ });
2950
+ }
2951
+ function pendingInputFromRow(row) {
2952
+ const detail = readRecord(row.detail);
2953
+ const nested = readRecord(detail?.request) ?? readRecord(detail?.pendingInput) ?? detail;
2954
+ const questions = row.questions ?? readQuestions(nested?.questions);
2955
+ const options = row.options ?? readOptions(nested?.options);
2956
+ return {
2957
+ requestId: row.requestId ?? (typeof nested?.requestId === "string" ? nested.requestId : row.id),
2958
+ title: row.title ?? (typeof nested?.title === "string" ? nested.title : "The assistant needs your input"),
2959
+ description: row.description,
2960
+ questions,
2961
+ options,
2962
+ ...row.allowsFreeform !== void 0 ? { allowsFreeform: row.allowsFreeform } : typeof nested?.allowsFreeform === "boolean" ? { allowsFreeform: nested.allowsFreeform } : {},
2963
+ ...typeof nested?.canProceedWithoutAnswer === "boolean" ? { canProceedWithoutAnswer: nested.canProceedWithoutAnswer } : {}
2964
+ };
2965
+ }
2966
+ function PendingInputCard({ row, onRespond }) {
2967
+ const request = useMemo(() => pendingInputFromRow(row), [row]);
2968
+ const [picks, setPicks] = useState({});
2969
+ const [notes, setNotes] = useState({});
2970
+ const [submitted, setSubmitted] = useState(false);
2971
+ const [busy, setBusy] = useState(false);
2972
+ const [failure, setFailure] = useState(null);
2973
+ const isPlan = row.requestKind === "plan_approval";
2974
+ const canRespond = Boolean(onRespond) && row.state === "pending" && !busy && !submitted;
2975
+ const hasAnswer = request.questions.length ? request.questions.every((question) => {
2976
+ const selected = picks[question.id] ?? [];
2977
+ return selected.length > 0 || Boolean((notes[question.id] ?? "").trim()) || request.canProceedWithoutAnswer === true;
2978
+ }) : Boolean((notes.response ?? "").trim()) || request.canProceedWithoutAnswer === true;
2979
+ const respond = async (response) => {
2980
+ if (!onRespond || !canRespond) return;
2981
+ setBusy(true);
2982
+ setFailure(null);
2983
+ try {
2984
+ await onRespond(request.requestId, response);
2985
+ setPicks({});
2986
+ setNotes({});
2987
+ setSubmitted(true);
2988
+ } catch (cause) {
2989
+ setFailure(cause instanceof Error ? cause.message : String(cause));
2990
+ } finally {
2991
+ setBusy(false);
2992
+ }
2993
+ };
2994
+ const submitAnswers = () => {
2995
+ const answers = {};
2996
+ if (request.questions.length) {
2997
+ for (const question of request.questions) {
2998
+ const selected = picks[question.id] ?? [];
2999
+ const note = (notes[question.id] ?? "").trim();
3000
+ const values = [...selected, ...note ? [note] : []];
3001
+ if (values.length === 1) answers[question.id] = values[0];
3002
+ else if (values.length > 1) answers[question.id] = values;
3003
+ }
3004
+ } else {
3005
+ const responseText = (notes.response ?? "").trim();
3006
+ if (responseText) {
3007
+ void respond({ responseText });
3008
+ return;
3009
+ }
3010
+ }
3011
+ void respond({ answers });
3012
+ };
3013
+ const title = isPlan ? "Plan ready for review" : request.title;
3014
+ const settledLabel = row.state === "accepted" ? "Answered" : row.state === "rejected" ? "Declined" : row.state === "cancelled" ? "Cancelled" : row.state === "expired" ? "The turn ended before this was answered." : submitted ? "Answer sent" : null;
3015
+ return /* @__PURE__ */ jsxs("section", { className: "adechat-approval adechat-pending-input", "data-state": row.state, children: [
3016
+ /* @__PURE__ */ jsxs("div", { className: "adechat-approval-head", children: [
3017
+ /* @__PURE__ */ jsx("strong", { className: "adechat-approval-title", children: title }),
3018
+ settledLabel ? /* @__PURE__ */ jsx("span", { className: "adechat-approval-settled", children: settledLabel }) : null
3019
+ ] }),
3020
+ isPlan ? /* @__PURE__ */ jsx("div", { className: "adechat-pending-plan", children: request.description || request.questions[0]?.question || "The assistant has prepared a plan." }) : null,
3021
+ !isPlan && request.questions.length ? request.questions.map((question, index) => {
3022
+ const options = question.options?.length ? question.options : index === 0 ? request.options : [];
3023
+ const allowText = question.allowsFreeform ?? request.allowsFreeform ?? options.length === 0;
3024
+ const answer = notes[question.id] ?? "";
3025
+ return /* @__PURE__ */ jsxs("fieldset", { className: "adechat-pending-question", disabled: !canRespond, children: [
3026
+ /* @__PURE__ */ jsxs("legend", { children: [
3027
+ question.header ? /* @__PURE__ */ jsxs("span", { children: [
3028
+ question.header,
3029
+ ": "
3030
+ ] }) : null,
3031
+ question.question
3032
+ ] }),
3033
+ options.map((option) => {
3034
+ const selected = picks[question.id] ?? [];
3035
+ const checked = selected.includes(option.value);
3036
+ const toggle = () => setPicks((current) => {
3037
+ const values = current[question.id] ?? [];
3038
+ const next = question.multiSelect ? checked ? values.filter((value) => value !== option.value) : [...values, option.value] : checked ? [] : [option.value];
3039
+ return { ...current, [question.id]: next };
3040
+ });
3041
+ return /* @__PURE__ */ jsxs("label", { className: "adechat-pending-option", children: [
3042
+ /* @__PURE__ */ jsx(
3043
+ "input",
3044
+ {
3045
+ type: question.multiSelect ? "checkbox" : "radio",
3046
+ name: `adechat-question-${row.id}-${question.id}`,
3047
+ checked,
3048
+ onChange: toggle,
3049
+ disabled: !canRespond
3050
+ }
3051
+ ),
3052
+ /* @__PURE__ */ jsxs("span", { children: [
3053
+ option.label,
3054
+ option.description ? /* @__PURE__ */ jsx("small", { children: option.description }) : null
3055
+ ] })
3056
+ ] }, option.value);
3057
+ }),
3058
+ allowText ? question.isSecret ? /* @__PURE__ */ jsx(
3059
+ "input",
3060
+ {
3061
+ className: "adechat-pending-answer",
3062
+ type: "password",
3063
+ autoComplete: "off",
3064
+ "aria-label": `Your answer to ${question.question}`,
3065
+ placeholder: "Enter a private answer\u2026",
3066
+ value: answer,
3067
+ onChange: (event) => setNotes((current) => ({ ...current, [question.id]: event.target.value })),
3068
+ disabled: !canRespond
3069
+ }
3070
+ ) : /* @__PURE__ */ jsx(
3071
+ "textarea",
3072
+ {
3073
+ className: "adechat-pending-answer",
3074
+ "aria-label": `Your answer to ${question.question}`,
3075
+ placeholder: "Add a note\u2026",
3076
+ value: answer,
3077
+ onChange: (event) => setNotes((current) => ({ ...current, [question.id]: event.target.value })),
3078
+ disabled: !canRespond
3079
+ }
3080
+ ) : null
3081
+ ] }, question.id);
3082
+ }) : null,
3083
+ !isPlan && request.questions.length === 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
3084
+ request.description ? /* @__PURE__ */ jsx("p", { className: "adechat-pending-description", children: request.description }) : null,
3085
+ request.allowsFreeform !== false ? /* @__PURE__ */ jsx(
3086
+ "textarea",
3087
+ {
3088
+ className: "adechat-pending-answer",
3089
+ "aria-label": "Your answer",
3090
+ placeholder: "Write your answer\u2026",
3091
+ value: notes.response ?? "",
3092
+ onChange: (event) => setNotes((current) => ({ ...current, response: event.target.value })),
3093
+ disabled: !canRespond
3094
+ }
3095
+ ) : null
3096
+ ] }) : null,
3097
+ !onRespond && row.state === "pending" ? /* @__PURE__ */ jsx("p", { className: "adechat-approval-note", children: "This client cannot answer questions or approve plans." }) : null,
3098
+ onRespond && row.state === "pending" ? /* @__PURE__ */ jsx("div", { className: "adechat-approval-actions", children: isPlan ? /* @__PURE__ */ jsxs(Fragment, { children: [
3099
+ /* @__PURE__ */ jsx("button", { className: "adechat-button", "data-variant": "primary", type: "button", disabled: !canRespond, onClick: () => void respond({ decision: "accept" }), children: "Approve plan" }),
3100
+ /* @__PURE__ */ jsx("button", { className: "adechat-button", type: "button", disabled: !canRespond, onClick: () => void respond({ decision: "decline" }), children: "Keep planning" })
3101
+ ] }) : /* @__PURE__ */ jsx("button", { className: "adechat-button", "data-variant": "primary", type: "button", disabled: !canRespond || !hasAnswer, onClick: submitAnswers, children: busy ? "Sending\u2026" : "Send answer" }) }) : null,
3102
+ failure ? /* @__PURE__ */ jsxs("p", { className: "adechat-approval-error", role: "alert", children: [
3103
+ "Could not send that answer: ",
3104
+ failure
3105
+ ] }) : null
3106
+ ] });
3107
+ }
3108
+ var LinkHandlerContext = createContext(null);
3109
+ function DaexLinkHandlerProvider({
3110
+ onLinkClick,
3111
+ children
3112
+ }) {
3113
+ const inherited = useContext(LinkHandlerContext);
3114
+ return /* @__PURE__ */ jsx(LinkHandlerContext.Provider, { value: onLinkClick ?? inherited, children });
3115
+ }
3116
+ function DaexLink({
3117
+ href,
3118
+ source,
3119
+ className,
3120
+ children
3121
+ }) {
3122
+ const onLinkClick = useContext(LinkHandlerContext);
3123
+ if (!onLinkClick) {
3124
+ return /* @__PURE__ */ jsx("a", { className, href, target: "_blank", rel: "noreferrer noopener", children });
3125
+ }
3126
+ const onClick = (event) => {
3127
+ event.preventDefault();
3128
+ const text = event.currentTarget.textContent ?? href;
3129
+ onLinkClick(href, { source, text });
3130
+ };
3131
+ const onAuxClick = (event) => {
3132
+ if (event.button === 1) onClick(event);
3133
+ };
3134
+ return /* @__PURE__ */ jsx("a", { className, href, rel: "noreferrer noopener", onClick, onAuxClick, children });
3135
+ }
3136
+ var AdeLink = DaexLink;
3137
+ var AdeLinkHandlerProvider = DaexLinkHandlerProvider;
3138
+ var FENCE = /^\s*(`{3,}|~{3,})\s*([\w+-]*)\s*$/;
3139
+ var HEADING = /^(#{1,3})\s+(.*)$/;
3140
+ var UNORDERED = /^\s*[-*+]\s+(.*)$/;
3141
+ var ORDERED = /^\s*\d+[.)]\s+(.*)$/;
3142
+ var QUOTE = /^\s*>\s?(.*)$/;
3143
+ var RULE = /^\s*(-{3,}|\*{3,}|_{3,})\s*$/;
3144
+ function parseMarkdownBlocks(source) {
3145
+ const lines = source.replace(/\r\n/g, "\n").split("\n");
3146
+ const blocks = [];
3147
+ let index = 0;
3148
+ while (index < lines.length) {
3149
+ const line = lines[index];
3150
+ const fence = FENCE.exec(line);
3151
+ if (fence) {
3152
+ const marker = fence[1];
3153
+ const language = fence[2] || null;
3154
+ const body = [];
3155
+ index += 1;
3156
+ while (index < lines.length && !lines[index].trimStart().startsWith(marker)) {
3157
+ body.push(lines[index]);
3158
+ index += 1;
3159
+ }
3160
+ if (index < lines.length) index += 1;
3161
+ blocks.push({ kind: "code", language, text: body.join("\n") });
3162
+ continue;
3163
+ }
3164
+ if (!line.trim().length) {
3165
+ index += 1;
3166
+ continue;
3167
+ }
3168
+ if (RULE.test(line)) {
3169
+ blocks.push({ kind: "rule" });
3170
+ index += 1;
3171
+ continue;
3172
+ }
3173
+ const heading = HEADING.exec(line);
3174
+ if (heading) {
3175
+ blocks.push({
3176
+ kind: "heading",
3177
+ level: heading[1].length,
3178
+ text: heading[2].trim()
3179
+ });
3180
+ index += 1;
3181
+ continue;
3182
+ }
3183
+ const listMatch = UNORDERED.exec(line) ?? ORDERED.exec(line);
3184
+ if (listMatch) {
3185
+ const ordered = UNORDERED.exec(line) === null;
3186
+ const items = [];
3187
+ while (index < lines.length) {
3188
+ const candidate = lines[index];
3189
+ const match = ordered ? ORDERED.exec(candidate) : UNORDERED.exec(candidate);
3190
+ if (!match) break;
3191
+ items.push(match[1]);
3192
+ index += 1;
3193
+ }
3194
+ blocks.push({ kind: "list", ordered, items });
3195
+ continue;
3196
+ }
3197
+ if (QUOTE.test(line)) {
3198
+ const body = [];
3199
+ while (index < lines.length) {
3200
+ const match = QUOTE.exec(lines[index]);
3201
+ if (!match) break;
3202
+ body.push(match[1]);
3203
+ index += 1;
3204
+ }
3205
+ blocks.push({ kind: "quote", text: body.join("\n") });
3206
+ continue;
3207
+ }
3208
+ const paragraph = [];
3209
+ while (index < lines.length) {
3210
+ const candidate = lines[index];
3211
+ if (!candidate.trim().length || FENCE.test(candidate) || HEADING.test(candidate) || UNORDERED.test(candidate) || ORDERED.test(candidate) || QUOTE.test(candidate) || RULE.test(candidate)) break;
3212
+ paragraph.push(candidate.trim());
3213
+ index += 1;
3214
+ }
3215
+ blocks.push({ kind: "paragraph", text: paragraph.join("\n") });
3216
+ }
3217
+ return blocks;
3218
+ }
3219
+ var INLINE = /(`+)([^`]*?)\1|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_|\[([^\]]+)\]\(([^)\s]+)\)|(https?:\/\/[^\s<>"')]+)/g;
3220
+ function parseInline(source) {
3221
+ const tokens = [];
3222
+ let lastIndex = 0;
3223
+ INLINE.lastIndex = 0;
3224
+ for (let match = INLINE.exec(source); match; match = INLINE.exec(source)) {
3225
+ if (match.index > lastIndex) {
3226
+ tokens.push({ kind: "text", value: source.slice(lastIndex, match.index) });
3227
+ }
3228
+ if (match[2] !== void 0) tokens.push({ kind: "code", value: match[2] });
3229
+ else if (match[3] !== void 0) tokens.push({ kind: "strong", value: match[3] });
3230
+ else if (match[4] !== void 0) tokens.push({ kind: "strong", value: match[4] });
3231
+ else if (match[5] !== void 0) tokens.push({ kind: "em", value: match[5] });
3232
+ else if (match[6] !== void 0) tokens.push({ kind: "em", value: match[6] });
3233
+ else if (match[7] !== void 0 && match[8] !== void 0) {
3234
+ tokens.push({ kind: "link", value: match[7], href: match[8] });
3235
+ } else if (match[9] !== void 0) {
3236
+ tokens.push({ kind: "link", value: match[9], href: match[9] });
3237
+ }
3238
+ lastIndex = match.index + match[0].length;
3239
+ }
3240
+ if (lastIndex < source.length) tokens.push({ kind: "text", value: source.slice(lastIndex) });
3241
+ return tokens;
3242
+ }
3243
+ var PROTOCOL_RELATIVE = /^[/\\]{2}/;
3244
+ function safeHref(href) {
3245
+ const trimmed = href.trim();
3246
+ if (PROTOCOL_RELATIVE.test(trimmed)) return null;
3247
+ if (/^(https?:|mailto:|tel:|#|\/|\.)/i.test(trimmed)) return trimmed;
3248
+ return null;
3249
+ }
3250
+ function renderInline(source, keyPrefix) {
3251
+ return parseInline(source).map((token, index) => {
3252
+ const key = `${keyPrefix}:${index}`;
3253
+ switch (token.kind) {
3254
+ case "code":
3255
+ return /* @__PURE__ */ jsx("code", { className: "adechat-code-inline", children: token.value }, key);
3256
+ case "strong":
3257
+ return /* @__PURE__ */ jsx("strong", { children: token.value }, key);
3258
+ case "em":
3259
+ return /* @__PURE__ */ jsx("em", { children: token.value }, key);
3260
+ case "link": {
3261
+ const href = safeHref(token.href);
3262
+ if (!href) return /* @__PURE__ */ jsx(Fragment$1, { children: token.value }, key);
3263
+ return /* @__PURE__ */ jsx(DaexLink, { href, source: "markdown", children: token.value }, key);
3264
+ }
3265
+ default:
3266
+ return /* @__PURE__ */ jsx(Fragment$1, { children: token.value }, key);
3267
+ }
3268
+ });
3269
+ }
3270
+ function renderMarkdown(source) {
3271
+ return parseMarkdownBlocks(source).map((block, index) => {
3272
+ const key = `block:${index}`;
3273
+ switch (block.kind) {
3274
+ case "code":
3275
+ return /* @__PURE__ */ jsx("pre", { className: "adechat-code-block", "data-language": block.language ?? void 0, children: /* @__PURE__ */ jsx("code", { children: block.text }) }, key);
3276
+ case "heading": {
3277
+ const Tag = `h${block.level}`;
3278
+ return /* @__PURE__ */ jsx(Tag, { children: renderInline(block.text, key) }, key);
3279
+ }
3280
+ case "list": {
3281
+ const Tag = block.ordered ? "ol" : "ul";
3282
+ return /* @__PURE__ */ jsx(Tag, { children: block.items.map((item, itemIndex) => /* @__PURE__ */ jsx("li", { children: renderInline(item, `${key}:${itemIndex}`) }, `${key}:${itemIndex}`)) }, key);
3283
+ }
3284
+ case "quote":
3285
+ return /* @__PURE__ */ jsx("blockquote", { children: renderInline(block.text, key) }, key);
3286
+ case "rule":
3287
+ return /* @__PURE__ */ jsx("hr", {}, key);
3288
+ default:
3289
+ return /* @__PURE__ */ jsx("p", { children: renderInline(block.text, key) }, key);
3290
+ }
3291
+ });
3292
+ }
3293
+ function useElapsedMs(startedAt, running) {
3294
+ const [now, setNow] = useState(() => Date.now());
3295
+ useEffect(() => {
3296
+ if (!running || startedAt === void 0) return;
3297
+ setNow(Date.now());
3298
+ const timer = setInterval(() => setNow(Date.now()), 1e3);
3299
+ return () => clearInterval(timer);
3300
+ }, [running, startedAt]);
3301
+ if (startedAt === void 0 || !running) return void 0;
3302
+ return Math.max(0, now - startedAt);
3303
+ }
3304
+ function ToolChip({ chip, labels, startedAt, expanded, onToggle, actions }) {
3305
+ const [internalExpanded, setInternalExpanded] = useState(false);
3306
+ const isExpanded = expanded ?? internalExpanded;
3307
+ const elapsedMs = useElapsedMs(startedAt, chip.status === "running");
3308
+ const { label, elapsed, icon } = describeToolActivity({
3309
+ chip,
3310
+ ...labels ? { config: labels } : {},
3311
+ ...elapsedMs !== void 0 ? { elapsedMs } : {}
3312
+ });
3313
+ const hasArgs = eventHasPayload(chip.args);
3314
+ const hasResult = eventHasPayload(chip.result);
3315
+ const expandable = hasArgs || hasResult;
3316
+ const toggle = () => {
3317
+ if (!expandable) return;
3318
+ const next = !isExpanded;
3319
+ setInternalExpanded(next);
3320
+ onToggle?.(next);
3321
+ };
3322
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-chip", "data-status": chip.status, children: [
3323
+ /* @__PURE__ */ jsxs(
3324
+ "button",
3325
+ {
3326
+ type: "button",
3327
+ className: "adechat-chip-head",
3328
+ onClick: toggle,
3329
+ "aria-expanded": expandable ? isExpanded : void 0,
3330
+ "aria-disabled": expandable ? void 0 : "true",
3331
+ children: [
3332
+ /* @__PURE__ */ jsx("span", { className: "adechat-chip-dot", "data-status": chip.status, "aria-hidden": "true" }),
3333
+ icon ? /* @__PURE__ */ jsx("span", { className: "adechat-chip-icon", children: icon }) : null,
3334
+ /* @__PURE__ */ jsx("span", { className: "adechat-chip-label", children: label }),
3335
+ elapsed ? /* @__PURE__ */ jsx("span", { className: "adechat-chip-elapsed", children: elapsed }) : null
3336
+ ]
3337
+ }
3338
+ ),
3339
+ actions?.length ? /* @__PURE__ */ jsx("div", { className: "adechat-chip-actions", children: actions.map((action) => /* @__PURE__ */ jsx(
3340
+ "button",
3341
+ {
3342
+ type: "button",
3343
+ className: "adechat-chip-action",
3344
+ onClick: () => action.onSelect(),
3345
+ children: action.label
3346
+ },
3347
+ action.label
3348
+ )) }) : null,
3349
+ isExpanded && expandable ? /* @__PURE__ */ jsxs("div", { className: "adechat-chip-body", children: [
3350
+ hasArgs ? /* @__PURE__ */ jsxs("div", { children: [
3351
+ /* @__PURE__ */ jsx("div", { className: "adechat-chip-section-label", children: "Arguments" }),
3352
+ /* @__PURE__ */ jsx("pre", { className: "adechat-chip-pre", children: formatStructuredValue(chip.args) })
3353
+ ] }) : null,
3354
+ hasResult ? /* @__PURE__ */ jsxs("div", { children: [
3355
+ /* @__PURE__ */ jsx("div", { className: "adechat-chip-section-label", children: "Result" }),
3356
+ /* @__PURE__ */ jsx("pre", { className: "adechat-chip-pre", children: formatStructuredValue(chip.result) })
3357
+ ] }) : null
3358
+ ] }) : null
3359
+ ] });
3360
+ }
3361
+ var BOTTOM_THRESHOLD_PX = 32;
3362
+ var ESTIMATED_ROW_HEIGHT_PX = 72;
3363
+ function upperBound(values, target) {
3364
+ let low = 0;
3365
+ let high = values.length;
3366
+ while (low < high) {
3367
+ const mid = low + high >>> 1;
3368
+ if (values[mid] <= target) low = mid + 1;
3369
+ else high = mid;
3370
+ }
3371
+ return low;
3372
+ }
3373
+ function useWindowedRows(visible, { threshold, overscan }) {
3374
+ const scrollRef = useRef(null);
3375
+ const pinnedRef = useRef(true);
3376
+ const [viewport, setViewport] = useState({ top: 0, height: 0 });
3377
+ const heightsRef = useRef(/* @__PURE__ */ new Map());
3378
+ const [measureVersion, setMeasureVersion] = useState(0);
3379
+ const gapRef = useRef(0);
3380
+ const frameRef = useRef(null);
3381
+ const frameTasksRef = useRef(/* @__PURE__ */ new Set());
3382
+ const scheduleFrame = useCallback((task) => {
3383
+ frameTasksRef.current.add(task);
3384
+ if (frameRef.current !== null) return;
3385
+ const run = () => {
3386
+ frameRef.current = null;
3387
+ const tasks = [...frameTasksRef.current];
3388
+ frameTasksRef.current.clear();
3389
+ for (const next of tasks) next();
3390
+ };
3391
+ frameRef.current = typeof requestAnimationFrame === "function" ? requestAnimationFrame(run) : setTimeout(run, 16);
3392
+ }, []);
3393
+ const readViewport = useCallback(() => {
3394
+ const node = scrollRef.current;
3395
+ if (!node) return;
3396
+ setViewport(
3397
+ (current) => current.top === node.scrollTop && current.height === node.clientHeight ? current : { top: node.scrollTop, height: node.clientHeight }
3398
+ );
3399
+ }, []);
3400
+ const onScroll = useCallback(() => {
3401
+ const node = scrollRef.current;
3402
+ if (!node) return;
3403
+ const distance = node.scrollHeight - node.scrollTop - node.clientHeight;
3404
+ pinnedRef.current = distance <= BOTTOM_THRESHOLD_PX;
3405
+ scheduleFrame(readViewport);
3406
+ }, [readViewport, scheduleFrame]);
3407
+ const observer = useMemo(() => {
3408
+ if (typeof ResizeObserver === "undefined") return null;
3409
+ return new ResizeObserver((entries) => {
3410
+ let changed = false;
3411
+ for (const entry of entries) {
3412
+ const target = entry.target;
3413
+ if (target === scrollRef.current) {
3414
+ changed = true;
3415
+ continue;
3416
+ }
3417
+ const key = target.dataset.rowKey;
3418
+ if (!key) continue;
3419
+ const height = target.offsetHeight;
3420
+ if (heightsRef.current.get(key) !== height) {
3421
+ heightsRef.current.set(key, height);
3422
+ changed = true;
3423
+ }
3424
+ }
3425
+ if (changed) {
3426
+ scheduleFrame(() => {
3427
+ readViewport();
3428
+ setMeasureVersion((value) => value + 1);
3429
+ });
3430
+ }
3431
+ });
3432
+ }, [readViewport, scheduleFrame]);
3433
+ useEffect(() => {
3434
+ const node = scrollRef.current;
3435
+ if (node) {
3436
+ const gap2 = Number.parseFloat(getComputedStyle(node).rowGap);
3437
+ gapRef.current = Number.isFinite(gap2) ? gap2 : 0;
3438
+ observer?.observe(node);
3439
+ readViewport();
3440
+ }
3441
+ return () => {
3442
+ observer?.disconnect();
3443
+ if (frameRef.current !== null) {
3444
+ if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(frameRef.current);
3445
+ else clearTimeout(frameRef.current);
3446
+ frameRef.current = null;
3447
+ }
3448
+ frameTasksRef.current.clear();
3449
+ };
3450
+ }, [readViewport, observer]);
3451
+ const windowed = observer !== null && viewport.height > 0 && visible.length > threshold;
3452
+ const offsets = useMemo(() => {
3453
+ if (!windowed) return null;
3454
+ let measuredTotal = 0;
3455
+ let measuredCount = 0;
3456
+ for (const row of visible) {
3457
+ const height = heightsRef.current.get(row.key);
3458
+ if (height !== void 0) {
3459
+ measuredTotal += height;
3460
+ measuredCount += 1;
3461
+ }
3462
+ }
3463
+ const estimate = measuredCount ? measuredTotal / measuredCount : ESTIMATED_ROW_HEIGHT_PX;
3464
+ const gap2 = gapRef.current;
3465
+ const result = new Array(visible.length + 1);
3466
+ result[0] = 0;
3467
+ for (let index = 0; index < visible.length; index += 1) {
3468
+ const height = heightsRef.current.get(visible[index].key) ?? estimate;
3469
+ result[index + 1] = result[index] + height + gap2;
3470
+ }
3471
+ return result;
3472
+ }, [windowed, visible, measureVersion]);
3473
+ let start = 0;
3474
+ let end = visible.length - 1;
3475
+ if (offsets) {
3476
+ const total = offsets[visible.length];
3477
+ const top = pinnedRef.current ? Math.max(0, total - viewport.height) : viewport.top;
3478
+ const first = Math.max(0, upperBound(offsets, top) - 1);
3479
+ const last = Math.min(visible.length - 1, upperBound(offsets, top + viewport.height) - 1);
3480
+ start = Math.max(0, first - overscan);
3481
+ end = Math.min(visible.length - 1, last + overscan);
3482
+ }
3483
+ const gap = gapRef.current;
3484
+ const topSpacer = offsets && start > 0 ? Math.max(0, offsets[start] - gap) : 0;
3485
+ const bottomSpacer = offsets && end < visible.length - 1 ? Math.max(0, offsets[visible.length] - offsets[end + 1] - gap) : 0;
3486
+ const rendered = offsets ? visible.slice(start, end + 1) : visible;
3487
+ return { rendered, topSpacer, bottomSpacer, scrollRef, pinnedRef, onScroll, observer, offsets };
3488
+ }
3489
+ function RowSlot({
3490
+ rowKey,
3491
+ observer,
3492
+ children
3493
+ }) {
3494
+ const ref = useRef(null);
3495
+ useLayoutEffect(() => {
3496
+ const node = ref.current;
3497
+ if (!node || !observer) return;
3498
+ observer.observe(node);
3499
+ return () => observer.unobserve(node);
3500
+ }, [observer]);
3501
+ return /* @__PURE__ */ jsx("div", { ref, className: "adechat-row-slot", "data-row-key": rowKey, children });
3502
+ }
3503
+ var TOP_LOAD_THRESHOLD_PX = 48;
3504
+ var DEFAULT_WINDOW_THRESHOLD = 150;
3505
+ var DEFAULT_OVERSCAN = 8;
3506
+ var DEFAULT_APPROVAL_WAITING_LABEL = "Waiting for your approval\u2026";
3507
+ function Transcript({
3508
+ rows,
3509
+ status = "idle",
3510
+ labels,
3511
+ hideToolCalls = false,
3512
+ hideReasoning = false,
3513
+ expandReasoning = false,
3514
+ renderMarkdown: renderMarkdown2 = renderMarkdown,
3515
+ onLinkClick,
3516
+ onApprove,
3517
+ onRespond,
3518
+ approvals,
3519
+ renderToolResult,
3520
+ toolChipActions,
3521
+ hasOlder = false,
3522
+ loadingOlder = false,
3523
+ onLoadOlder,
3524
+ windowThreshold = DEFAULT_WINDOW_THRESHOLD,
3525
+ overscan = DEFAULT_OVERSCAN,
3526
+ emptyState,
3527
+ className
3528
+ }) {
3529
+ const visible = useMemo(
3530
+ () => rows.filter((row) => {
3531
+ if (hideToolCalls && row.event.type === "tool_chip") return false;
3532
+ if (hideReasoning && row.event.type === "reasoning") return false;
3533
+ return row.event.type !== "status";
3534
+ }),
3535
+ [rows, hideToolCalls, hideReasoning]
3536
+ );
3537
+ const {
3538
+ rendered,
3539
+ topSpacer,
3540
+ bottomSpacer,
3541
+ scrollRef,
3542
+ pinnedRef,
3543
+ onScroll: onWindowScroll,
3544
+ observer,
3545
+ offsets
3546
+ } = useWindowedRows(visible, { threshold: windowThreshold, overscan });
3547
+ const loadOlderRef = useRef({
3548
+ hasOlder,
3549
+ loadingOlder
3550
+ });
3551
+ loadOlderRef.current = onLoadOlder ? { hasOlder, loadingOlder, onLoadOlder } : { hasOlder, loadingOlder };
3552
+ const handleScroll = useCallback(() => {
3553
+ const node = scrollRef.current;
3554
+ if (!node) return;
3555
+ onWindowScroll();
3556
+ const older = loadOlderRef.current;
3557
+ if (node.scrollTop <= TOP_LOAD_THRESHOLD_PX && older.hasOlder && !older.loadingOlder && older.onLoadOlder && node.scrollHeight > node.clientHeight) {
3558
+ void older.onLoadOlder();
3559
+ }
3560
+ }, [onWindowScroll, scrollRef]);
3561
+ const firstKeyRef = useRef(null);
3562
+ const scrollHeightRef = useRef(0);
3563
+ useLayoutEffect(() => {
3564
+ const node = scrollRef.current;
3565
+ if (!node) return;
3566
+ const firstKey = visible[0]?.key ?? null;
3567
+ const prepended = firstKeyRef.current !== null && firstKey !== firstKeyRef.current && visible.some((row, index) => index > 0 && row.key === firstKeyRef.current);
3568
+ if (pinnedRef.current) {
3569
+ node.scrollTop = node.scrollHeight;
3570
+ } else if (prepended) {
3571
+ node.scrollTop += node.scrollHeight - scrollHeightRef.current;
3572
+ }
3573
+ firstKeyRef.current = firstKey;
3574
+ scrollHeightRef.current = node.scrollHeight;
3575
+ }, [visible, status, offsets, pinnedRef, scrollRef]);
3576
+ const tail = visible[visible.length - 1];
3577
+ const awaitingApproval = tail?.event.type === "approval" && tail.event.state === "pending";
3578
+ const showActivity = awaitingApproval || status === "running" && (visible.length === 0 || tail.event.type !== "tool_chip");
3579
+ return /* @__PURE__ */ jsx(DaexLinkHandlerProvider, { onLinkClick, children: /* @__PURE__ */ jsxs(
3580
+ "div",
3581
+ {
3582
+ ref: scrollRef,
3583
+ className: ["adechat-transcript", className].filter(Boolean).join(" "),
3584
+ onScroll: handleScroll,
3585
+ role: "log",
3586
+ "aria-live": "polite",
3587
+ "aria-relevant": "additions text",
3588
+ children: [
3589
+ hasOlder && onLoadOlder ? /* @__PURE__ */ jsx(
3590
+ "button",
3591
+ {
3592
+ type: "button",
3593
+ className: "adechat-transcript-older",
3594
+ onClick: () => void onLoadOlder(),
3595
+ disabled: loadingOlder,
3596
+ children: loadingOlder ? "Loading older messages\u2026" : "Load older messages"
3597
+ }
3598
+ ) : null,
3599
+ visible.length === 0 && !showActivity ? /* @__PURE__ */ jsx("div", { className: "adechat-transcript-empty", children: emptyState ?? "No messages yet." }) : null,
3600
+ topSpacer > 0 ? /* @__PURE__ */ jsx("div", { className: "adechat-transcript-spacer", style: { height: topSpacer }, "aria-hidden": "true" }) : null,
3601
+ rendered.map((row) => /* @__PURE__ */ jsx(RowSlot, { rowKey: row.key, observer, children: /* @__PURE__ */ jsx(
3602
+ TranscriptRowView,
3603
+ {
3604
+ row,
3605
+ ...labels ? { labels } : {},
3606
+ expandReasoning,
3607
+ renderMarkdown: renderMarkdown2,
3608
+ ...onApprove ? { onApprove } : {},
3609
+ ...onRespond ? { onRespond } : {},
3610
+ ...approvals ? { approvals } : {},
3611
+ ...renderToolResult ? { renderToolResult } : {},
3612
+ ...toolChipActions ? { toolChipActions } : {}
3613
+ }
3614
+ ) }, row.key)),
3615
+ bottomSpacer > 0 ? /* @__PURE__ */ jsx("div", { className: "adechat-transcript-spacer", style: { height: bottomSpacer }, "aria-hidden": "true" }) : null,
3616
+ showActivity ? /* @__PURE__ */ jsx(
3617
+ ActivityIndicator,
3618
+ {
3619
+ labels,
3620
+ ...awaitingApproval ? { label: DEFAULT_APPROVAL_WAITING_LABEL } : {}
3621
+ }
3622
+ ) : null
3623
+ ]
3624
+ }
3625
+ ) });
3626
+ }
3627
+ var TranscriptRowView = memo(function TranscriptRowView2({
3628
+ row,
3629
+ labels,
3630
+ expandReasoning,
3631
+ renderMarkdown: renderMarkdown2,
3632
+ onApprove,
3633
+ onRespond,
3634
+ approvals,
3635
+ renderToolResult,
3636
+ toolChipActions
3637
+ }) {
3638
+ const event = row.event;
3639
+ if (event.type === "approval") {
3640
+ if (event.requestKind === "question" || event.requestKind === "structured_question" || event.requestKind === "plan_approval") {
3641
+ return /* @__PURE__ */ jsx("div", { className: "adechat-row", children: /* @__PURE__ */ jsx(PendingInputCard, { row: event, ...onRespond ? { onRespond } : {} }) });
3642
+ }
3643
+ return /* @__PURE__ */ jsx("div", { className: "adechat-row", children: /* @__PURE__ */ jsx(
3644
+ ApprovalCard,
3645
+ {
3646
+ row: event,
3647
+ ...onApprove ? { onApprove } : {},
3648
+ ...approvals ? { options: approvals } : {}
3649
+ }
3650
+ ) });
3651
+ }
3652
+ if (event.type === "user_message") {
3653
+ const text = event.displayText ?? event.text;
3654
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-row adechat-row-user", children: [
3655
+ /* @__PURE__ */ jsx("div", { className: "adechat-bubble-user", children: text }),
3656
+ event.attachments?.length ? /* @__PURE__ */ jsx("div", { className: "adechat-attachments", children: event.attachments.map((attachment) => /* @__PURE__ */ jsx("span", { className: "adechat-attachment", children: attachment.name }, attachment.id)) }) : null
3657
+ ] });
3658
+ }
3659
+ if (event.type === "text") {
3660
+ return /* @__PURE__ */ jsx("div", { className: "adechat-row", children: /* @__PURE__ */ jsx("div", { className: "adechat-assistant", children: renderMarkdown2(event.text) }) });
3661
+ }
3662
+ if (event.type === "reasoning") {
3663
+ return /* @__PURE__ */ jsx(ReasoningRow, { text: event.text, defaultExpanded: expandReasoning });
3664
+ }
3665
+ if (event.type === "tool_chip") {
3666
+ const actions = toolChipActions?.(event);
3667
+ const extra = renderToolResult?.(event);
3668
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-row", children: [
3669
+ /* @__PURE__ */ jsx(
3670
+ ToolChip,
3671
+ {
3672
+ chip: event,
3673
+ ...labels ? { labels } : {},
3674
+ ...actions?.length ? { actions } : {},
3675
+ startedAt: Date.parse(row.timestamp) || void 0
3676
+ }
3677
+ ),
3678
+ extra !== void 0 && extra !== null && extra !== false ? /* @__PURE__ */ jsx("div", { className: "adechat-tool-result", children: extra }) : null
3679
+ ] });
3680
+ }
3681
+ if (event.type === "error") {
3682
+ const label = resolveActivityLabel({ kind: "error", tool: null, phase: "error", event }, labels) ?? event.message;
3683
+ return /* @__PURE__ */ jsx("div", { className: "adechat-row", children: /* @__PURE__ */ jsxs("div", { className: "adechat-error", role: "alert", children: [
3684
+ /* @__PURE__ */ jsx("div", { className: "adechat-error-message", children: label }),
3685
+ event.detail ? /* @__PURE__ */ jsx("pre", { className: "adechat-error-detail", children: event.detail }) : null
3686
+ ] }) });
3687
+ }
3688
+ return null;
3689
+ });
3690
+ function ReasoningRow({ text, defaultExpanded }) {
3691
+ const [expanded, setExpanded] = useState(defaultExpanded);
3692
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-row adechat-reasoning", children: [
3693
+ /* @__PURE__ */ jsx(
3694
+ "button",
3695
+ {
3696
+ type: "button",
3697
+ className: "adechat-reasoning-toggle",
3698
+ onClick: () => setExpanded((value) => !value),
3699
+ "aria-expanded": expanded,
3700
+ children: expanded ? "Hide reasoning" : "Show reasoning"
3701
+ }
3702
+ ),
3703
+ expanded ? /* @__PURE__ */ jsx("div", { className: "adechat-reasoning-body", children: text }) : null
3704
+ ] });
3705
+ }
3706
+ function ActivityIndicator({
3707
+ labels,
3708
+ label: labelOverride
3709
+ }) {
3710
+ const [dots, setDots] = useState(0);
3711
+ const reducedMotion = usePrefersReducedMotion();
3712
+ useEffect(() => {
3713
+ if (reducedMotion) return;
3714
+ const timer = setInterval(() => setDots((value) => (value + 1) % 4), 450);
3715
+ return () => clearInterval(timer);
3716
+ }, [reducedMotion]);
3717
+ const label = labelOverride ?? resolveActivityLabel({ kind: "thinking", tool: null, phase: "running", event: null }, labels) ?? DEFAULT_THINKING_LABEL;
3718
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-activity", role: "status", children: [
3719
+ /* @__PURE__ */ jsx("span", { className: "adechat-activity-dot", "aria-hidden": "true" }),
3720
+ /* @__PURE__ */ jsxs("span", { children: [
3721
+ label,
3722
+ reducedMotion ? "" : ".".repeat(dots)
3723
+ ] })
3724
+ ] });
3725
+ }
3726
+ function usePrefersReducedMotion() {
3727
+ const [reduced, setReduced] = useState(false);
3728
+ useEffect(() => {
3729
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
3730
+ const query = window.matchMedia("(prefers-reduced-motion: reduce)");
3731
+ setReduced(query.matches);
3732
+ const onChange = (event) => setReduced(event.matches);
3733
+ if (typeof query.addEventListener === "function") {
3734
+ query.addEventListener("change", onChange);
3735
+ return () => query.removeEventListener("change", onChange);
3736
+ }
3737
+ query.addListener(onChange);
3738
+ return () => query.removeListener(onChange);
3739
+ }, []);
3740
+ return reduced;
3741
+ }
3742
+ function UsageLimitNotice({ status, onResumeNow, onContinueOnAlternate }) {
3743
+ const [busy, setBusy] = useState(false);
3744
+ const [error, setError] = useState(null);
3745
+ if (!status) return null;
3746
+ const alternate = status.alternateAccount ?? (status.alternateAccounts?.[0] ? {
3747
+ instanceId: status.alternateAccounts[0].id,
3748
+ label: status.alternateAccounts[0].label
3749
+ } : null);
3750
+ const resumeLabel = status.state === "resuming" ? "Resume scheduled" : "Resume now";
3751
+ const run = async (action) => {
3752
+ if (!action || busy) return;
3753
+ setBusy(true);
3754
+ setError(null);
3755
+ try {
3756
+ await action();
3757
+ } catch (cause) {
3758
+ setError(cause instanceof Error ? cause.message : String(cause));
3759
+ } finally {
3760
+ setBusy(false);
3761
+ }
3762
+ };
3763
+ return /* @__PURE__ */ jsxs("aside", { className: "adechat-usage-limit", role: "status", "aria-live": "polite", children: [
3764
+ /* @__PURE__ */ jsxs("div", { className: "adechat-usage-limit-copy", children: [
3765
+ /* @__PURE__ */ jsx("strong", { children: "Usage limit reached" }),
3766
+ /* @__PURE__ */ jsx("span", { children: status.resetAt ? `Resets ${new Date(status.resetAt).toLocaleString()}` : "This conversation is waiting for usage room." })
3767
+ ] }),
3768
+ /* @__PURE__ */ jsxs("div", { className: "adechat-usage-limit-actions", children: [
3769
+ onResumeNow ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", disabled: busy, onClick: () => void run(onResumeNow), children: busy ? "Working\u2026" : resumeLabel }) : null,
3770
+ alternate && onContinueOnAlternate ? /* @__PURE__ */ jsxs("button", { type: "button", className: "adechat-button", "data-variant": "primary", disabled: busy, onClick: () => void run(onContinueOnAlternate), children: [
3771
+ "Continue on ",
3772
+ alternate.label
3773
+ ] }) : null
3774
+ ] }),
3775
+ error ? /* @__PURE__ */ jsxs("span", { className: "adechat-usage-limit-error", role: "alert", children: [
3776
+ "Could not continue: ",
3777
+ error
3778
+ ] }) : null
3779
+ ] });
3780
+ }
3781
+
3782
+ // src/actionResult.ts
3783
+ async function requireAccepted(result) {
3784
+ const value = await result;
3785
+ if (value && typeof value === "object" && value.ok === false) {
3786
+ const message = value.message;
3787
+ throw new Error(typeof message === "string" && message ? message : "The runtime refused this action.");
3788
+ }
3789
+ }
3790
+ var useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
3791
+ function DaexChat(props) {
3792
+ return /* @__PURE__ */ jsx(DaexChatProvider, { client: props.client, ...props.labels ? { labels: props.labels } : {}, children: /* @__PURE__ */ jsx(AdeChatInner, { ...props }) });
3793
+ }
3794
+ function AdeChatInner({
3795
+ client,
3796
+ threadKey,
3797
+ defaultModelId,
3798
+ modelId,
3799
+ onModelChange,
3800
+ labels,
3801
+ theme,
3802
+ disableStyles = false,
3803
+ placeholder,
3804
+ sendOnEnter,
3805
+ value,
3806
+ onValueChange,
3807
+ onSend,
3808
+ children,
3809
+ threadRef,
3810
+ onRequestAttachment,
3811
+ attachments,
3812
+ onAttachmentsChange,
3813
+ modelRail,
3814
+ actions,
3815
+ reasoningEffort,
3816
+ onReasoningEffortChange,
3817
+ hideToolCalls,
3818
+ hideReasoning,
3819
+ renderMarkdown: renderMarkdown2,
3820
+ onLinkClick,
3821
+ approvals,
3822
+ renderToolResult,
3823
+ toolChipActions,
3824
+ historyPageSize,
3825
+ styleNonce,
3826
+ emptyState,
3827
+ hideModelPicker = false,
3828
+ className
3829
+ }) {
3830
+ const [internalModelId, setInternalModelId] = useState(defaultModelId ?? null);
3831
+ const [pickerOpen, setPickerOpen] = useState(false);
3832
+ const [selectedLabel, setSelectedLabel] = useState(null);
3833
+ const { models, statuses, loading: catalogLoading } = useDaexProviders(client);
3834
+ const fallbackModel = useMemo(
3835
+ () => models.find(
3836
+ (model) => isModelSelectable(model, statuses.find((status) => status.id === model.providerId))
3837
+ ) ?? null,
3838
+ [models, statuses]
3839
+ );
3840
+ const activeModelId = modelId ?? internalModelId ?? fallbackModel?.id ?? null;
3841
+ const activeModel = useMemo(
3842
+ () => models.find((model) => model.id === activeModelId) ?? null,
3843
+ [models, activeModelId]
3844
+ );
3845
+ const thread = useDaexThread(threadKey, {
3846
+ client,
3847
+ enabled: Boolean(activeModelId) || !catalogLoading,
3848
+ ...activeModelId ? { modelId: activeModelId } : {},
3849
+ ...historyPageSize !== void 0 ? { historyPageSize } : {}
3850
+ });
3851
+ const [usageLimitEvent, setUsageLimitEvent] = useState(null);
3852
+ const usageLimit = usageLimitEvent?.key === threadKey ? usageLimitEvent.status : null;
3853
+ const [queueRefreshKey, setQueueRefreshKey] = useState(0);
3854
+ useEffect(() => {
3855
+ setUsageLimitEvent(null);
3856
+ if (!thread.thread?.usageLimit || typeof client.on !== "function") return;
3857
+ try {
3858
+ return client.on("usageLimit", (event) => {
3859
+ if (event.key !== threadKey) return;
3860
+ setUsageLimitEvent(event);
3861
+ });
3862
+ } catch {
3863
+ return;
3864
+ }
3865
+ }, [client, threadKey, thread.thread?.usageLimit]);
3866
+ const threadStateRef = useRef(thread);
3867
+ threadStateRef.current = thread;
3868
+ useIsomorphicLayoutEffect(() => {
3869
+ if (threadRef) threadRef.current = thread;
3870
+ });
3871
+ useEffect(() => {
3872
+ if (!threadRef) return;
3873
+ return () => {
3874
+ threadRef.current = null;
3875
+ };
3876
+ }, [threadRef]);
3877
+ const style = useMemo(
3878
+ () => theme ? { ...theme } : void 0,
3879
+ [theme]
3880
+ );
3881
+ const { setModel, canSetModel, ready: threadReady, status: threadStatus } = thread;
3882
+ const turnRunning = threadStatus.state === "running";
3883
+ const [modelError, setModelError] = useState(null);
3884
+ useEffect(() => {
3885
+ if (!threadReady || !activeModelId || !canSetModel || turnRunning) return;
3886
+ let cancelled = false;
3887
+ setModel(activeModelId).then(() => {
3888
+ if (!cancelled) setModelError(null);
3889
+ }).catch((cause) => {
3890
+ if (cancelled) return;
3891
+ setModelError(cause instanceof Error ? cause : new Error(String(cause)));
3892
+ });
3893
+ return () => {
3894
+ cancelled = true;
3895
+ };
3896
+ }, [threadReady, activeModelId, canSetModel, setModel, turnRunning]);
3897
+ const pickerRef = useRef(null);
3898
+ useEffect(() => {
3899
+ if (!pickerOpen) return;
3900
+ const onPointerDown = (event) => {
3901
+ if (!pickerRef.current?.contains(event.target)) setPickerOpen(false);
3902
+ };
3903
+ const onKeyDown = (event) => {
3904
+ if (event.key === "Escape") setPickerOpen(false);
3905
+ };
3906
+ document.addEventListener("mousedown", onPointerDown);
3907
+ document.addEventListener("keydown", onKeyDown);
3908
+ return () => {
3909
+ document.removeEventListener("mousedown", onPointerDown);
3910
+ document.removeEventListener("keydown", onKeyDown);
3911
+ };
3912
+ }, [pickerOpen]);
3913
+ const modelPickerDisabledReason = threadReady && !canSetModel ? "This conversation is already open and its runtime cannot change models mid-thread." : turnRunning ? "Wait for the current reply to finish before changing model." : null;
3914
+ const resolvedModel = thread.model;
3915
+ const resolvedName = resolvedModel?.displayName && (!activeModelId || resolvedModel.modelId === activeModelId || !activeModel) ? resolvedModel.displayName : null;
3916
+ const railLabel = selectedLabel ?? activeModel?.displayName ?? resolvedName ?? activeModelId ?? "Choose model";
3917
+ const defaultRail = hideModelPicker ? null : /* @__PURE__ */ jsxs("div", { ref: pickerRef, style: { position: "relative" }, children: [
3918
+ /* @__PURE__ */ jsx(
3919
+ "button",
3920
+ {
3921
+ type: "button",
3922
+ className: "adechat-button",
3923
+ onClick: () => setPickerOpen((open) => !open),
3924
+ "aria-expanded": pickerOpen,
3925
+ "aria-haspopup": "listbox",
3926
+ disabled: modelPickerDisabledReason !== null,
3927
+ ...modelPickerDisabledReason ? { title: modelPickerDisabledReason } : {},
3928
+ children: railLabel
3929
+ }
3930
+ ),
3931
+ modelError ? /* @__PURE__ */ jsxs("div", { role: "alert", className: "adechat-model-error", children: [
3932
+ "Could not switch model: ",
3933
+ modelError.message
3934
+ ] }) : null,
3935
+ pickerOpen ? /* @__PURE__ */ jsx("div", { style: { position: "absolute", bottom: "calc(100% + 8px)", left: 0, zIndex: 20 }, children: /* @__PURE__ */ jsx(
3936
+ ModelPicker,
3937
+ {
3938
+ client,
3939
+ value: activeModelId,
3940
+ ...reasoningEffort !== void 0 ? { reasoningEffort } : {},
3941
+ ...onReasoningEffortChange ? { onReasoningEffortChange } : {},
3942
+ onChange: (model) => {
3943
+ if (modelId === void 0) setInternalModelId(model.id);
3944
+ setSelectedLabel(model.displayName);
3945
+ setPickerOpen(false);
3946
+ onModelChange?.(model);
3947
+ }
3948
+ }
3949
+ ) }) : null
3950
+ ] });
3951
+ const attachmentProps = {
3952
+ ...onRequestAttachment ? { onRequestAttachment } : {},
3953
+ ...attachments !== void 0 ? { attachments } : {},
3954
+ ...onAttachmentsChange ? { onAttachmentsChange } : {}
3955
+ };
3956
+ const approvalHandler = thread.canApprove ? { onApprove: thread.approve } : {};
3957
+ return /* @__PURE__ */ jsxs("div", { className: ["adechat-root", className].filter(Boolean).join(" "), style, children: [
3958
+ disableStyles ? null : /* @__PURE__ */ jsx(DaexChatStyles, { ...styleNonce ? { nonce: styleNonce } : {} }),
3959
+ /* @__PURE__ */ jsx(
3960
+ Transcript,
3961
+ {
3962
+ rows: thread.rows,
3963
+ status: thread.status.state,
3964
+ ...labels ? { labels } : {},
3965
+ ...hideToolCalls !== void 0 ? { hideToolCalls } : {},
3966
+ ...hideReasoning !== void 0 ? { hideReasoning } : {},
3967
+ ...renderMarkdown2 ? { renderMarkdown: renderMarkdown2 } : {},
3968
+ ...onLinkClick ? { onLinkClick } : {},
3969
+ ...approvals ? { approvals } : {},
3970
+ ...approvalHandler,
3971
+ ...thread.canRespond ? { onRespond: thread.respond } : {},
3972
+ ...renderToolResult ? { renderToolResult } : {},
3973
+ ...toolChipActions ? { toolChipActions } : {},
3974
+ hasOlder: thread.hasOlder,
3975
+ loadingOlder: thread.loadingOlder,
3976
+ onLoadOlder: thread.loadOlder,
3977
+ ...emptyState !== void 0 ? { emptyState } : {}
3978
+ }
3979
+ ),
3980
+ /* @__PURE__ */ jsx(
3981
+ UsageLimitNotice,
3982
+ {
3983
+ status: usageLimit,
3984
+ ...thread.thread?.usageLimit?.resumeNow ? { onResumeNow: () => requireAccepted(thread.thread.usageLimit.resumeNow()) } : {},
3985
+ ...thread.thread?.usageLimit?.continueOnAlternate ? { onContinueOnAlternate: () => requireAccepted(thread.thread.usageLimit.continueOnAlternate()) } : {}
3986
+ }
3987
+ ),
3988
+ children ? children(thread) : null,
3989
+ thread.thread?.queue ? /* @__PURE__ */ jsx(QueueStrip, { queue: thread.thread.queue, refreshKey: `${queueRefreshKey}:${thread.status.state}` }, threadKey) : null,
3990
+ /* @__PURE__ */ jsx(
3991
+ Composer,
3992
+ {
3993
+ onSend: async (input) => {
3994
+ const result = onSend ? await onSend(input, threadStateRef.current) : void 0;
3995
+ if (result === false) return false;
3996
+ if (result === "handled") {
3997
+ setQueueRefreshKey((value2) => value2 + 1);
3998
+ return;
3999
+ }
4000
+ await threadStateRef.current.send(input);
4001
+ setQueueRefreshKey((value2) => value2 + 1);
4002
+ },
4003
+ onSteer: async (input) => {
4004
+ await thread.steer(input);
4005
+ setQueueRefreshKey((value2) => value2 + 1);
4006
+ },
4007
+ onInterrupt: thread.interrupt,
4008
+ status: thread.status.state,
4009
+ ready: thread.ready,
4010
+ ...placeholder !== void 0 ? { placeholder } : {},
4011
+ ...sendOnEnter !== void 0 ? { sendOnEnter } : {},
4012
+ ...value !== void 0 ? { value } : {},
4013
+ ...onValueChange ? { onValueChange } : {},
4014
+ ...attachmentProps,
4015
+ modelRail: modelRail !== void 0 ? modelRail : defaultRail,
4016
+ ...actions !== void 0 ? { actions } : {},
4017
+ error: thread.error?.message ?? null,
4018
+ ...thread.slashCommands !== void 0 ? { slashCommands: thread.slashCommands } : {},
4019
+ slashCommandsLoading: thread.slashCommandsLoading,
4020
+ slashCommandsError: thread.slashCommandsError,
4021
+ onRetrySlashCommands: thread.reloadSlashCommands
4022
+ }
4023
+ )
4024
+ ] });
4025
+ }
4026
+ var AdeChat = DaexChat;
4027
+ function resolveState(status) {
4028
+ if (!status.installed) return "not_installed";
4029
+ if (!status.authenticated) return "unauthenticated";
4030
+ return "ready";
4031
+ }
4032
+ var STATE_COPY = {
4033
+ ready: "Ready",
4034
+ unauthenticated: "Not signed in",
4035
+ not_installed: "Not installed"
4036
+ };
4037
+ function resolveStateCopy(status) {
4038
+ const state = resolveState(status);
4039
+ if (state === "not_installed" && status.source === "derived") return "Not detected";
4040
+ return STATE_COPY[state];
4041
+ }
4042
+ function truncateBinaryPath(value, maxLength = 44) {
4043
+ if (value.length <= maxLength) return value;
4044
+ const separator = value.lastIndexOf("\\") > value.lastIndexOf("/") ? "\\" : "/";
4045
+ const index = value.lastIndexOf(separator);
4046
+ if (index <= 0) return `\u2026${value.slice(value.length - maxLength + 1)}`;
4047
+ const tail = value.slice(index);
4048
+ if (tail.length + 1 >= maxLength) return `\u2026${tail}`;
4049
+ return `${value.slice(0, maxLength - tail.length - 1)}\u2026${tail}`;
4050
+ }
4051
+ function ProviderCard({
4052
+ status,
4053
+ renderAction,
4054
+ onCopy,
4055
+ showDetail = false,
4056
+ onLinkClick,
4057
+ className
4058
+ }) {
4059
+ const state = resolveState(status);
4060
+ const command = state === "not_installed" ? status.installCommand : state === "unauthenticated" ? status.loginCommand : void 0;
4061
+ const commandKind = state === "not_installed" ? "install" : "login";
4062
+ const docsHref = status.docsUrl ? safeHref(status.docsUrl) : null;
4063
+ return /* @__PURE__ */ jsx(DaexLinkHandlerProvider, { onLinkClick, children: /* @__PURE__ */ jsxs(
4064
+ "div",
4065
+ {
4066
+ className: ["adechat-providercard", className].filter(Boolean).join(" "),
4067
+ "data-state": state,
4068
+ children: [
4069
+ /* @__PURE__ */ jsxs("div", { className: "adechat-providercard-head", children: [
4070
+ /* @__PURE__ */ jsx(
4071
+ "span",
4072
+ {
4073
+ className: "adechat-status-dot",
4074
+ "data-status": state === "ready" ? "ok" : state === "unauthenticated" ? "unauthed" : "missing",
4075
+ "aria-hidden": "true"
4076
+ }
4077
+ ),
4078
+ /* @__PURE__ */ jsx("span", { className: "adechat-providercard-name", children: status.displayName ?? status.id }),
4079
+ /* @__PURE__ */ jsx("span", { className: "adechat-providercard-state", children: resolveStateCopy(status) })
4080
+ ] }),
4081
+ status.detail ? /* @__PURE__ */ jsx("p", { className: "adechat-providercard-detail", children: status.detail }) : null,
4082
+ showDetail && (status.version || status.binaryPath) ? /* @__PURE__ */ jsxs("p", { className: "adechat-providercard-probe", children: [
4083
+ status.version ? /* @__PURE__ */ jsx("span", { children: status.version }) : null,
4084
+ status.binaryPath ? /* @__PURE__ */ jsx("code", { title: status.binaryPath, children: truncateBinaryPath(status.binaryPath) }) : null
4085
+ ] }) : null,
4086
+ command ? renderAction?.(command, commandKind) ?? /* @__PURE__ */ jsx(CopyableCommand, { command, ...onCopy ? { onCopy } : {} }) : null,
4087
+ docsHref ? /* @__PURE__ */ jsx(
4088
+ DaexLink,
4089
+ {
4090
+ className: "adechat-providercard-detail",
4091
+ href: docsHref,
4092
+ source: "provider-docs",
4093
+ children: "Documentation"
4094
+ }
4095
+ ) : null
4096
+ ]
4097
+ }
4098
+ ) });
4099
+ }
4100
+ function CopyableCommand({
4101
+ command,
4102
+ onCopy
4103
+ }) {
4104
+ const [copied, setCopied] = useState(false);
4105
+ useEffect(() => {
4106
+ if (!copied) return;
4107
+ const timer = setTimeout(() => setCopied(false), 1600);
4108
+ return () => clearTimeout(timer);
4109
+ }, [copied]);
4110
+ const copy = useCallback(async () => {
4111
+ try {
4112
+ if (onCopy) await onCopy(command);
4113
+ else if (typeof navigator !== "undefined" && navigator.clipboard) {
4114
+ await navigator.clipboard.writeText(command);
4115
+ } else return;
4116
+ setCopied(true);
4117
+ } catch {
4118
+ }
4119
+ }, [command, onCopy]);
4120
+ return /* @__PURE__ */ jsxs("div", { className: "adechat-command", children: [
4121
+ /* @__PURE__ */ jsx("code", { className: "adechat-command-text", children: command }),
4122
+ /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", onClick: () => void copy(), children: copied ? "Copied" : "Copy" })
4123
+ ] });
4124
+ }
4125
+ function ProviderCards(props) {
4126
+ return props.statuses ? /* @__PURE__ */ jsx(ProviderCardsView, { ...props, statuses: props.statuses }) : /* @__PURE__ */ jsx(ConnectedProviderCards, { ...props });
4127
+ }
4128
+ function ConnectedProviderCards(props) {
4129
+ const connected = useDaexProviders(props.client);
4130
+ return /* @__PURE__ */ jsx(ProviderCardsView, { ...props, statuses: connected.statuses });
4131
+ }
4132
+ function ProviderCardsView({
4133
+ statuses = [],
4134
+ onlyNeedsAttention = true,
4135
+ renderAction,
4136
+ onCopy,
4137
+ showDetail,
4138
+ onLinkClick,
4139
+ className
4140
+ }) {
4141
+ const visible = onlyNeedsAttention ? statuses.filter((status) => resolveState(status) !== "ready") : statuses;
4142
+ if (visible.length === 0) return null;
4143
+ return /* @__PURE__ */ jsx(Fragment, { children: visible.map((status) => /* @__PURE__ */ jsx(
4144
+ ProviderCard,
4145
+ {
4146
+ status,
4147
+ ...renderAction ? { renderAction } : {},
4148
+ ...onCopy ? { onCopy } : {},
4149
+ ...showDetail !== void 0 ? { showDetail } : {},
4150
+ ...onLinkClick ? { onLinkClick } : {},
4151
+ ...className ? { className } : {}
4152
+ },
4153
+ status.id
4154
+ )) });
4155
+ }
4156
+
4157
+ // src/adapters/sdkClient.ts
4158
+ function record(value) {
4159
+ return value && typeof value === "object" ? value : {};
4160
+ }
4161
+ function optionalString(value) {
4162
+ return typeof value === "string" && value ? value : void 0;
4163
+ }
4164
+ function optionalNumber(value) {
4165
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4166
+ }
4167
+ function threadStatusFromEnvelope(envelope) {
4168
+ const event = record(envelope?.event);
4169
+ const type = event.type;
4170
+ const turnId = optionalString(event.turnId) ?? null;
4171
+ if (type === "error") {
4172
+ return {
4173
+ state: "error",
4174
+ turnId,
4175
+ message: optionalString(event.message) ?? optionalString(event.detail) ?? "The turn failed."
4176
+ };
4177
+ }
4178
+ if (type === "done") return { state: "idle", turnId };
4179
+ if (type === "status") {
4180
+ switch (event.turnStatus) {
4181
+ case "started":
4182
+ return { state: "running", turnId };
4183
+ case "completed":
4184
+ case "interrupted":
4185
+ return { state: "idle", turnId };
4186
+ // Also the SDK's synthetic status for a runtime that exited mid-turn
4187
+ // (`synthetic: true`), which no `done` follows.
4188
+ case "failed":
4189
+ return {
4190
+ state: "error",
4191
+ turnId,
4192
+ message: optionalString(event.message) ?? "The turn failed."
4193
+ };
4194
+ default:
4195
+ return null;
4196
+ }
4197
+ }
4198
+ return null;
4199
+ }
4200
+ function threadUsageFromEnvelope(envelope) {
4201
+ const event = record(envelope?.event);
4202
+ const source = event.type === "context_usage" ? record(event.usage) : event;
4203
+ const usage = {};
4204
+ const input = optionalNumber(source.inputTokens) ?? optionalNumber(source.input_tokens);
4205
+ const output = optionalNumber(source.outputTokens) ?? optionalNumber(source.output_tokens);
4206
+ const total = optionalNumber(source.totalTokens) ?? optionalNumber(source.total_tokens) ?? (input !== void 0 && output !== void 0 ? input + output : void 0);
4207
+ const contextWindow = optionalNumber(source.maxTokens) ?? optionalNumber(source.contextWindow) ?? optionalNumber(source.context_window);
4208
+ if (input !== void 0) usage.inputTokens = input;
4209
+ if (output !== void 0) usage.outputTokens = output;
4210
+ if (total !== void 0) usage.totalTokens = total;
4211
+ if (contextWindow !== void 0) usage.contextWindow = contextWindow;
4212
+ return Object.keys(usage).length > 0 ? usage : null;
4213
+ }
4214
+ function providerStatusesFromSdk(statuses, options = {}) {
4215
+ const hints = options.commandHints ?? {};
4216
+ const entries = Object.values(statuses ?? {});
4217
+ const ordered = options.providerFilter ? options.providerFilter.map((id) => entries.find((entry) => entry.provider === id)).filter((entry) => Boolean(entry)) : entries;
4218
+ return ordered.map((entry) => {
4219
+ const hint = hints[entry.provider] ?? {};
4220
+ const status = {
4221
+ id: entry.provider,
4222
+ displayName: entry.displayName || entry.provider,
4223
+ // A runtime that probes the filesystem answers this directly. Only when
4224
+ // it does not does "DAEX knows models for it" stand in — the closest
4225
+ // honest reading available from a catalog alone. It is never inferred
4226
+ // from `authenticated`: that would render an unauthenticated provider as
4227
+ // "not installed" and send the user to the wrong copyable command.
4228
+ //
4229
+ // The same derivation exists in `@daex-dev/sdk` (`src/providers.ts`,
4230
+ // `deriveProviderStatus`). This copy is load-bearing rather than
4231
+ // redundant: it serves 0.1 clients, WebSocket proxies and test doubles
4232
+ // that send a record with neither `installed` nor `source`, which the SDK
4233
+ // never has to consider. Keep the two rules identical.
4234
+ installed: entry.installed ?? entry.modelCount > 0,
4235
+ authenticated: entry.authenticated
4236
+ };
4237
+ status.source = entry.source ?? (entry.installed === void 0 ? "derived" : "probed");
4238
+ if (entry.binaryPath) status.binaryPath = entry.binaryPath;
4239
+ if (entry.version) status.version = entry.version;
4240
+ if (entry.checkedAt) status.checkedAt = entry.checkedAt;
4241
+ const installCommand = hint.installCommand ?? entry.installCommand;
4242
+ const loginCommand = hint.loginCommand ?? entry.loginCommand;
4243
+ const docsUrl = hint.docsUrl ?? entry.docsUrl;
4244
+ if (installCommand) status.installCommand = installCommand;
4245
+ if (loginCommand) status.loginCommand = loginCommand;
4246
+ if (docsUrl) status.docsUrl = docsUrl;
4247
+ const detail = describeProvider(entry);
4248
+ if (detail) status.detail = detail;
4249
+ return status;
4250
+ });
4251
+ }
4252
+ function describeProvider(entry) {
4253
+ if (entry.detail) return entry.detail;
4254
+ if (entry.modelCount === 0) return "DAEX has no models for this provider.";
4255
+ if (!entry.authenticated) return "Not signed in.";
4256
+ if (entry.requiresConfiguration) return "Needs configuration before it can run.";
4257
+ if (!entry.available) return "Signed in, but no model is usable right now.";
4258
+ if (entry.stale) return "Status was read from a stale catalog.";
4259
+ return void 0;
4260
+ }
4261
+ function modelDescriptorsFromSdk(models, options = {}) {
4262
+ const allowed = options.providerFilter ? new Set(options.providerFilter) : null;
4263
+ return (models ?? []).filter((model) => !allowed || allowed.has(model.provider)).map((model) => {
4264
+ const descriptor = {
4265
+ id: model.id,
4266
+ providerId: model.provider,
4267
+ displayName: model.displayName || model.id
4268
+ };
4269
+ if (model.description) descriptor.description = model.description;
4270
+ if (model.reasoningEfforts?.length) descriptor.reasoningEfforts = [...model.reasoningEfforts];
4271
+ if (model.defaultReasoningEffort) descriptor.defaultReasoningEffort = model.defaultReasoningEffort;
4272
+ if (model.isAvailable === false) descriptor.available = false;
4273
+ return descriptor;
4274
+ });
4275
+ }
4276
+ function toSendText(input) {
4277
+ return typeof input === "string" ? input : input.text;
4278
+ }
4279
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
4280
+ ".bmp",
4281
+ ".gif",
4282
+ ".heic",
4283
+ ".heif",
4284
+ ".ico",
4285
+ ".jpeg",
4286
+ ".jpg",
4287
+ ".png",
4288
+ ".svg",
4289
+ ".tif",
4290
+ ".tiff",
4291
+ ".webp"
4292
+ ]);
4293
+ function isImageAttachmentPath(filePath) {
4294
+ const extension = filePath.match(/\.[^./\\]+$/)?.[0]?.toLowerCase();
4295
+ return extension ? IMAGE_EXTENSIONS.has(extension) : false;
4296
+ }
4297
+ function inferAttachmentType(filePath, mimeType) {
4298
+ if (mimeType?.toLowerCase().startsWith("image/")) return "image";
4299
+ return isImageAttachmentPath(filePath) ? "image" : "file";
4300
+ }
4301
+ function attachmentKind(attachment) {
4302
+ if (attachment.type) return attachment.type;
4303
+ return inferAttachmentType(attachment.uri || attachment.name || "", attachment.mimeType);
4304
+ }
4305
+ function sdkSendArgs(input) {
4306
+ const refs = toFileRefs(input);
4307
+ return refs ? { text: toSendText(input), opts: { attachments: refs } } : { text: toSendText(input) };
4308
+ }
4309
+ function toFileRefs(input) {
4310
+ if (typeof input === "string") return void 0;
4311
+ const attachments = input.attachments ?? [];
4312
+ const refs = attachments.map((attachment) => {
4313
+ if (!attachment.uri) return null;
4314
+ const ref = { path: attachment.uri, type: attachmentKind(attachment) };
4315
+ if (attachment.name) ref.name = attachment.name;
4316
+ if (attachment.mimeType) ref.mimeType = attachment.mimeType;
4317
+ if (attachment.sizeBytes !== void 0) ref.bytes = attachment.sizeBytes;
4318
+ if (attachment.hydrate !== void 0) ref.hydrate = attachment.hydrate;
4319
+ return ref;
4320
+ }).filter((ref) => ref !== null);
4321
+ return refs.length > 0 ? refs : void 0;
4322
+ }
4323
+ var AdaptedThread = class {
4324
+ constructor(inner) {
4325
+ this.inner = inner;
4326
+ if (inner.setModel) {
4327
+ this.setModel = (modelId) => inner.setModel(modelId);
4328
+ }
4329
+ if (inner.approve) {
4330
+ this.approve = (itemId, decision, responseText) => responseText === void 0 ? inner.approve(itemId, decision) : inner.approve(itemId, decision, responseText);
4331
+ }
4332
+ if (inner.pendingApprovals) {
4333
+ this.pendingApprovals = () => inner.pendingApprovals();
4334
+ }
4335
+ if (inner.respond) {
4336
+ this.respond = (requestId, response) => inner.respond(requestId, response);
4337
+ }
4338
+ if (inner.queue) {
4339
+ const queue = inner.queue;
4340
+ this.queue = {
4341
+ ...queue.list ? { list: () => queue.list() } : {},
4342
+ ...queue.cancel ? { cancel: (id) => queue.cancel(id) } : {},
4343
+ ...queue.edit ? { edit: (id, text) => queue.edit(id, text) } : {},
4344
+ ...queue.move ? { move: (id, index) => queue.move(id, index) } : {},
4345
+ ...queue.dispatch ? { dispatch: (id) => queue.dispatch(id) } : {},
4346
+ ...queue.cancelDispatched ? { cancelDispatched: (id) => queue.cancelDispatched(id) } : {},
4347
+ ...queue.restore ? { restore: () => queue.restore() } : {}
4348
+ };
4349
+ }
4350
+ if (inner.slashCommands) {
4351
+ this.slashCommands = () => inner.slashCommands();
4352
+ }
4353
+ if (inner.usageLimit) {
4354
+ const usageLimit = inner.usageLimit;
4355
+ this.usageLimit = {
4356
+ ...usageLimit.resumeNow ? { resumeNow: () => usageLimit.resumeNow() } : {},
4357
+ ...usageLimit.continueOnAlternate ? { continueOnAlternate: () => usageLimit.continueOnAlternate() } : {}
4358
+ };
4359
+ }
4360
+ if (inner.switchAccount) {
4361
+ this.switchAccount = (instanceId) => inner.switchAccount(instanceId);
4362
+ }
4363
+ if (inner.update) {
4364
+ this.update = (patch) => inner.update(patch);
4365
+ }
4366
+ if (inner.retry) {
4367
+ this.retry = () => inner.retry();
4368
+ }
4369
+ if (inner.editLast) {
4370
+ this.editLast = (input) => {
4371
+ const dropAttachments = typeof input !== "string" && input.attachments?.length === 0;
4372
+ if (dropAttachments) return inner.editLast(toSendText(input), { attachments: [] });
4373
+ const { text, opts } = sdkSendArgs(input);
4374
+ return inner.editLast(text, opts);
4375
+ };
4376
+ }
4377
+ if (inner.historyPage) {
4378
+ this.historyPage = async (request) => {
4379
+ const page = await inner.historyPage(request ?? {});
4380
+ return {
4381
+ events: page?.events ?? [],
4382
+ hasMore: page?.hasMore === true,
4383
+ nextBeforeSequence: page?.nextBeforeSequence ?? null
4384
+ };
4385
+ };
4386
+ }
4387
+ }
4388
+ inner;
4389
+ /**
4390
+ * Present only when the underlying SDK thread supports it, so `canSetModel`
4391
+ * reflects the inner thread's real capability rather than the wrapper's.
4392
+ * Assigned in the constructor instead of initialized to `undefined` because
4393
+ * `exactOptionalPropertyTypes` makes those two different things: an absent
4394
+ * property and a property holding `undefined` are distinguishable, and only
4395
+ * the former reads as "not supported".
4396
+ */
4397
+ setModel;
4398
+ /**
4399
+ * Present only when the inner thread can answer approvals, for the same
4400
+ * reason as `setModel`: the card renders read-only rather than offering a
4401
+ * button whose click would throw.
4402
+ */
4403
+ approve;
4404
+ pendingApprovals;
4405
+ respond;
4406
+ queue;
4407
+ slashCommands;
4408
+ usageLimit;
4409
+ switchAccount;
4410
+ /** Present only when the inner thread has `update`. */
4411
+ update;
4412
+ /** Present only when the inner thread has `retry` / `editLast`. */
4413
+ retry;
4414
+ editLast;
4415
+ /** Present only when the inner thread pages, so the hook can feature-detect it. */
4416
+ historyPage;
4417
+ /**
4418
+ * Read through to the inner thread every time: the SDK replaces its value
4419
+ * after `setModel`, so a copy taken at construction would go stale.
4420
+ */
4421
+ get model() {
4422
+ return readThreadModelSelection(this.inner.model);
4423
+ }
4424
+ get key() {
4425
+ return this.inner.key;
4426
+ }
4427
+ async send(input) {
4428
+ const { text, opts } = sdkSendArgs(input);
4429
+ await this.inner.send(text, opts);
4430
+ }
4431
+ async steer(input) {
4432
+ const { text, opts } = sdkSendArgs(input);
4433
+ await this.inner.steer(text, opts);
4434
+ }
4435
+ async interrupt() {
4436
+ await this.inner.interrupt();
4437
+ }
4438
+ async history() {
4439
+ return await this.inner.history();
4440
+ }
4441
+ /**
4442
+ * Taken as a discriminated tuple rather than two loose parameters: narrowing
4443
+ * on `args[0]` narrows `args[1]` with it, so the channel and its listener stay
4444
+ * connected without a cast to reunite them.
4445
+ */
4446
+ on(...args) {
4447
+ if (args[0] === "event") {
4448
+ return this.inner.on("event", args[1]);
4449
+ }
4450
+ if (args[0] === "status") {
4451
+ const listener2 = args[1];
4452
+ return this.inner.on("status", (envelope) => {
4453
+ const status = threadStatusFromEnvelope(envelope);
4454
+ if (status) listener2(status);
4455
+ });
4456
+ }
4457
+ const listener = args[1];
4458
+ return this.inner.on("usage", (envelope) => {
4459
+ const usage = threadUsageFromEnvelope(envelope);
4460
+ if (usage) listener(usage);
4461
+ });
4462
+ }
4463
+ };
4464
+ function adaptSdkClient(sdk, options = {}) {
4465
+ let catalog = [];
4466
+ const openOptionsFor = (opts) => {
4467
+ const defaults = options.defaults ?? {};
4468
+ const modelId = opts?.modelId ?? defaults.model;
4469
+ const fromCatalog = modelId ? catalog.find((model) => model.id === modelId) : void 0;
4470
+ const provider = opts?.providerId ?? fromCatalog?.provider ?? defaults.provider;
4471
+ return {
4472
+ ...defaults,
4473
+ ...provider ? { provider } : {},
4474
+ ...modelId ? { model: modelId } : {}
4475
+ };
4476
+ };
4477
+ const refresh = sdk.providers.refresh;
4478
+ const on = sdk.on;
4479
+ return {
4480
+ providers: {
4481
+ status: async () => providerStatusesFromSdk(await sdk.providers.status(), options),
4482
+ onChange: (cb) => sdk.providers.onChange((statuses) => cb(providerStatusesFromSdk(statuses, options))),
4483
+ // Forwarded only when the SDK client has it, so a host can tell a
4484
+ // re-probing runtime from one that only derives statuses from a catalog.
4485
+ ...refresh ? {
4486
+ refresh: async () => providerStatusesFromSdk(await refresh.call(sdk.providers), options)
4487
+ } : {},
4488
+ ...sdk.providers.capabilities ? { capabilities: (provider) => sdk.providers.capabilities(provider) } : {}
4489
+ },
4490
+ models: {
4491
+ list: async () => {
4492
+ catalog = await sdk.models.list();
4493
+ return modelDescriptorsFromSdk(catalog, options);
4494
+ }
4495
+ },
4496
+ threads: {
4497
+ open: async (key, opts) => new AdaptedThread(await sdk.threads.open(key, openOptionsFor(opts)))
4498
+ },
4499
+ ...sdk.accounts ? { accounts: sdk.accounts } : {},
4500
+ ...sdk.credentials ? { credentials: sdk.credentials } : {},
4501
+ ...on ? {
4502
+ on: (event, cb) => {
4503
+ if (event === "usageLimit") {
4504
+ try {
4505
+ const subscribe = on;
4506
+ return subscribe.call(sdk, "usageLimit", cb);
4507
+ } catch (cause) {
4508
+ if (cause instanceof Error && /Unknown client event/.test(cause.message)) return () => {
4509
+ };
4510
+ throw cause;
4511
+ }
4512
+ }
4513
+ return on.call(sdk, event, cb);
4514
+ }
4515
+ } : {}
4516
+ };
4517
+ }
4518
+ function UsageMeter({ usage, label = "Usage", className }) {
4519
+ return /* @__PURE__ */ jsxs("div", { className: ["adechat-usage-meter", className].filter(Boolean).join(" "), "aria-label": label, children: [
4520
+ usage.windows.map((window2) => /* @__PURE__ */ jsx(UsageWindow, { window: window2 }, window2.type)),
4521
+ usage.state !== "ok" && usage.note ? /* @__PURE__ */ jsx("small", { className: "adechat-usage-meter-reset", children: usage.note }) : null
4522
+ ] });
4523
+ }
4524
+ function UsageWindow({ window: window2 }) {
4525
+ const percent = window2.unlimited ? 100 : Math.max(0, Math.min(100, window2.percentLeft));
4526
+ const summary = window2.unlimited ? "Unlimited" : window2.countLeft !== void 0 && window2.countTotal !== void 0 ? `${window2.countLeft} of ${window2.countTotal} left` : `${Math.round(percent)}% left`;
4527
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
4528
+ /* @__PURE__ */ jsxs("div", { className: "adechat-usage-meter-label", children: [
4529
+ /* @__PURE__ */ jsx("span", { children: window2.label }),
4530
+ /* @__PURE__ */ jsx("span", { children: summary })
4531
+ ] }),
4532
+ /* @__PURE__ */ jsx(
4533
+ "div",
4534
+ {
4535
+ className: "adechat-usage-meter-track",
4536
+ role: "meter",
4537
+ "aria-label": `${window2.label} left`,
4538
+ "aria-valuemin": 0,
4539
+ "aria-valuemax": 100,
4540
+ "aria-valuenow": Math.round(percent),
4541
+ children: /* @__PURE__ */ jsx("span", { style: { width: `${percent}%` } })
4542
+ }
4543
+ ),
4544
+ window2.resetsAt ? /* @__PURE__ */ jsxs("small", { className: "adechat-usage-meter-reset", children: [
4545
+ "Resets ",
4546
+ new Date(window2.resetsAt).toLocaleString()
4547
+ ] }) : null
4548
+ ] });
4549
+ }
4550
+ function AccountList({ client, accounts: supplied, onSelect, className }) {
4551
+ const [accounts, setAccounts] = useState(supplied ?? []);
4552
+ const [loading, setLoading] = useState(false);
4553
+ const [loaded, setLoaded] = useState(supplied !== void 0);
4554
+ const [error, setError] = useState(null);
4555
+ const [busy, setBusy] = useState(false);
4556
+ const api = client?.accounts;
4557
+ const refresh = useCallback(async () => {
4558
+ if (supplied !== void 0) {
4559
+ setAccounts(supplied);
4560
+ setLoaded(true);
4561
+ return;
4562
+ }
4563
+ if (!api?.list) return;
4564
+ setLoading(true);
4565
+ try {
4566
+ setAccounts(await api.list());
4567
+ setLoaded(true);
4568
+ setError(null);
4569
+ } catch (cause) {
4570
+ setLoaded(false);
4571
+ setError(cause instanceof Error ? cause.message : String(cause));
4572
+ } finally {
4573
+ setLoading(false);
4574
+ }
4575
+ }, [api, supplied]);
4576
+ useEffect(() => {
4577
+ void refresh();
4578
+ }, [refresh]);
4579
+ const run = async (action) => {
4580
+ if (busy) return;
4581
+ setBusy(true);
4582
+ setError(null);
4583
+ try {
4584
+ await action();
4585
+ await refresh();
4586
+ } catch (cause) {
4587
+ setError(cause instanceof Error ? cause.message : String(cause));
4588
+ } finally {
4589
+ setBusy(false);
4590
+ }
4591
+ };
4592
+ if (supplied === void 0 && !api?.list) {
4593
+ return /* @__PURE__ */ jsx("p", { className: joinClass("adechat-account-state", className), children: "Account management is unavailable in this client." });
4594
+ }
4595
+ return /* @__PURE__ */ jsxs("section", { className: joinClass("adechat-account-list", className), "aria-label": "Provider accounts", children: [
4596
+ loading && !loaded ? /* @__PURE__ */ jsx("p", { className: "adechat-account-state", children: "Loading accounts\u2026" }) : null,
4597
+ error ? /* @__PURE__ */ jsxs("div", { className: "adechat-account-error", role: "alert", children: [
4598
+ /* @__PURE__ */ jsxs("span", { children: [
4599
+ "Couldn\u2019t load accounts: ",
4600
+ error
4601
+ ] }),
4602
+ /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", disabled: loading, onClick: () => void refresh(), children: "Retry" })
4603
+ ] }) : null,
4604
+ loaded && accounts.length === 0 ? /* @__PURE__ */ jsx("p", { className: "adechat-account-state", children: "No accounts are available." }) : null,
4605
+ loaded ? accounts.map((account) => /* @__PURE__ */ jsxs("article", { className: "adechat-account", children: [
4606
+ /* @__PURE__ */ jsxs("div", { className: "adechat-account-summary", children: [
4607
+ /* @__PURE__ */ jsx("strong", { children: account.label || account.provider }),
4608
+ /* @__PURE__ */ jsx("span", { children: [account.email, account.plan, account.signedIn ? "Signed in" : "Signed out", account.isDefault ? "Default" : null].filter(Boolean).join(" \xB7 ") })
4609
+ ] }),
4610
+ account.usage ? /* @__PURE__ */ jsx(UsageMeter, { usage: account.usage, label: `${account.label} usage` }) : null,
4611
+ onSelect ? /* @__PURE__ */ jsx("button", { className: "adechat-button", type: "button", disabled: busy, onClick: () => void run(() => onSelect(account)), children: "Select" }) : null,
4612
+ api?.setDefault && !account.isDefault ? /* @__PURE__ */ jsx("button", { className: "adechat-button", type: "button", disabled: busy, onClick: () => void run(() => api.setDefault(account.id)), children: "Make default" }) : null,
4613
+ api?.signOut && account.signedIn ? /* @__PURE__ */ jsx("button", { className: "adechat-button", type: "button", disabled: busy, onClick: () => void run(() => api.signOut(account.id)), children: "Sign out" }) : null,
4614
+ api?.remove ? /* @__PURE__ */ jsx("button", { className: "adechat-button", type: "button", "data-variant": "danger", disabled: busy, onClick: () => void run(() => api.remove(account.id)), children: "Remove" }) : null
4615
+ ] }, account.id)) : null
4616
+ ] });
4617
+ }
4618
+ function joinClass(...values) {
4619
+ return values.filter(Boolean).join(" ");
4620
+ }
4621
+ function AccountSwitcher({ accounts, currentAccountId, thread, onSwitch, className }) {
4622
+ const [busy, setBusy] = useState(false);
4623
+ const [error, setError] = useState(null);
4624
+ const switchTo = onSwitch ?? (thread?.switchAccount ? (id) => requireAccepted(thread.switchAccount(id)) : void 0);
4625
+ if (!switchTo) return null;
4626
+ const choices = accounts.filter((account) => account.signedIn);
4627
+ if (choices.length < 2) return null;
4628
+ return /* @__PURE__ */ jsxs("label", { className: ["adechat-account-switcher", className].filter(Boolean).join(" "), children: [
4629
+ /* @__PURE__ */ jsx("span", { children: "Account" }),
4630
+ /* @__PURE__ */ jsxs(
4631
+ "select",
4632
+ {
4633
+ value: currentAccountId ?? "",
4634
+ disabled: busy,
4635
+ onChange: (event) => {
4636
+ const id = event.target.value;
4637
+ if (!id || id === currentAccountId) return;
4638
+ setBusy(true);
4639
+ setError(null);
4640
+ void Promise.resolve(switchTo(id)).catch((cause) => setError(cause instanceof Error ? cause.message : String(cause))).finally(() => setBusy(false));
4641
+ },
4642
+ children: [
4643
+ /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: "Select an account" }),
4644
+ choices.map((account) => /* @__PURE__ */ jsx("option", { value: account.id, children: account.label || account.provider }, account.id))
4645
+ ]
4646
+ }
4647
+ ),
4648
+ error ? /* @__PURE__ */ jsxs("span", { className: "adechat-account-error", role: "alert", children: [
4649
+ "Could not switch account: ",
4650
+ error
4651
+ ] }) : null
4652
+ ] });
4653
+ }
4654
+ function ApiKeyForm({ provider, client, onSubmit, className }) {
4655
+ const [key, setKey] = useState("");
4656
+ const [label, setLabel] = useState("");
4657
+ const [busy, setBusy] = useState(false);
4658
+ const [saved, setSaved] = useState(false);
4659
+ const [failed, setFailed] = useState(false);
4660
+ const save = onSubmit ?? client?.credentials?.add?.bind(client.credentials);
4661
+ const submit = async (event) => {
4662
+ event.preventDefault();
4663
+ if (!save || !key || busy) return;
4664
+ setBusy(true);
4665
+ setSaved(false);
4666
+ setFailed(false);
4667
+ try {
4668
+ await save({ provider, key, ...label.trim() ? { label: label.trim() } : {} });
4669
+ setKey("");
4670
+ setSaved(true);
4671
+ } catch {
4672
+ setFailed(true);
4673
+ } finally {
4674
+ setBusy(false);
4675
+ }
4676
+ };
4677
+ if (!save) return null;
4678
+ return /* @__PURE__ */ jsxs("form", { className: ["adechat-api-key-form", className].filter(Boolean).join(" "), onSubmit: (event) => void submit(event), children: [
4679
+ /* @__PURE__ */ jsxs("label", { children: [
4680
+ "Label",
4681
+ /* @__PURE__ */ jsx("input", { value: label, onChange: (event) => setLabel(event.target.value), autoComplete: "off", disabled: busy })
4682
+ ] }),
4683
+ /* @__PURE__ */ jsxs("label", { children: [
4684
+ "API key",
4685
+ /* @__PURE__ */ jsx("input", { type: "password", value: key, onChange: (event) => setKey(event.target.value), autoComplete: "new-password", spellCheck: false, disabled: busy })
4686
+ ] }),
4687
+ /* @__PURE__ */ jsx("button", { type: "submit", className: "adechat-button", "data-variant": "primary", disabled: busy || !key, children: busy ? "Saving\u2026" : "Save API key" }),
4688
+ saved ? /* @__PURE__ */ jsx("span", { className: "adechat-sign-in-state", role: "status", children: "API key saved." }) : null,
4689
+ failed ? /* @__PURE__ */ jsx("span", { className: "adechat-account-error", role: "alert", children: "Could not save this API key." }) : null
4690
+ ] });
4691
+ }
4692
+ function SignInCard({ handle: providedHandle, onStart, onComplete, className }) {
4693
+ const [handle, setHandle] = useState(providedHandle ?? null);
4694
+ const [update, setUpdate] = useState({ state: "running" });
4695
+ const [code, setCode] = useState("");
4696
+ const [busy, setBusy] = useState(false);
4697
+ const [error, setError] = useState(null);
4698
+ const onCompleteRef = useRef(onComplete);
4699
+ onCompleteRef.current = onComplete;
4700
+ useEffect(() => setHandle(providedHandle ?? null), [providedHandle]);
4701
+ useEffect(() => {
4702
+ if (!handle) return;
4703
+ let active = true;
4704
+ const stop = handle.on("update", (next) => {
4705
+ if (active) setUpdate(next);
4706
+ });
4707
+ void handle.done.then((account) => {
4708
+ if (!active) return;
4709
+ setUpdate((current) => ({ ...current, state: "succeeded" }));
4710
+ onCompleteRef.current?.(account);
4711
+ }).catch((cause) => {
4712
+ if (active) {
4713
+ setUpdate((current) => ({ ...current, state: "failed" }));
4714
+ setError(cause instanceof Error ? cause.message : String(cause));
4715
+ }
4716
+ });
4717
+ return () => {
4718
+ active = false;
4719
+ stop();
4720
+ };
4721
+ }, [handle]);
4722
+ const start = async () => {
4723
+ if (!onStart || busy) return;
4724
+ setBusy(true);
4725
+ setError(null);
4726
+ try {
4727
+ setHandle(await onStart());
4728
+ } catch (cause) {
4729
+ setError(cause instanceof Error ? cause.message : String(cause));
4730
+ } finally {
4731
+ setBusy(false);
4732
+ }
4733
+ };
4734
+ const submit = async (event) => {
4735
+ event.preventDefault();
4736
+ if (!handle || !code.trim() || busy) return;
4737
+ setBusy(true);
4738
+ setError(null);
4739
+ try {
4740
+ await handle.submitCode(code);
4741
+ setCode("");
4742
+ } catch (cause) {
4743
+ setError(cause instanceof Error ? cause.message : String(cause));
4744
+ } finally {
4745
+ setBusy(false);
4746
+ }
4747
+ };
4748
+ const cancel = async () => {
4749
+ if (!handle || busy) return;
4750
+ setBusy(true);
4751
+ setError(null);
4752
+ try {
4753
+ await handle.cancel();
4754
+ setUpdate((current) => ({ ...current, state: "cancelled" }));
4755
+ } catch (cause) {
4756
+ setError(cause instanceof Error ? cause.message : String(cause));
4757
+ } finally {
4758
+ setBusy(false);
4759
+ }
4760
+ };
4761
+ return /* @__PURE__ */ jsxs("section", { className: ["adechat-sign-in", className].filter(Boolean).join(" "), "aria-label": "Sign in", children: [
4762
+ update.url ? /* @__PURE__ */ jsx("a", { href: update.url, target: "_blank", rel: "noreferrer noopener", children: "Continue sign-in" }) : null,
4763
+ update.deviceCode ? /* @__PURE__ */ jsxs("p", { className: "adechat-sign-in-code", children: [
4764
+ "Device code: ",
4765
+ /* @__PURE__ */ jsx("code", { children: update.deviceCode })
4766
+ ] }) : null,
4767
+ update.message ? /* @__PURE__ */ jsx("p", { className: "adechat-account-state", children: update.message }) : null,
4768
+ update.state === "verifying" ? /* @__PURE__ */ jsx("p", { className: "adechat-sign-in-state", role: "status", children: "Checking the sign-in\u2026" }) : null,
4769
+ update.state === "succeeded" ? /* @__PURE__ */ jsx("p", { className: "adechat-sign-in-state", role: "status", children: "Signed in." }) : null,
4770
+ update.state === "expired" ? /* @__PURE__ */ jsx("p", { className: "adechat-account-error", role: "alert", children: "This sign-in expired. Start it again." }) : null,
4771
+ update.state === "cancelled" ? /* @__PURE__ */ jsx("p", { className: "adechat-sign-in-state", role: "status", children: "Sign-in cancelled." }) : null,
4772
+ update.state === "failed" && !error ? /* @__PURE__ */ jsx("p", { className: "adechat-account-error", role: "alert", children: "Sign-in could not continue." }) : null,
4773
+ update.awaitingCode && handle ? /* @__PURE__ */ jsxs("form", { className: "adechat-sign-in-code-form", onSubmit: (event) => void submit(event), children: [
4774
+ /* @__PURE__ */ jsxs("label", { children: [
4775
+ "Paste the code from the sign-in page",
4776
+ /* @__PURE__ */ jsx("input", { autoComplete: "one-time-code", value: code, onChange: (event) => setCode(event.target.value), disabled: busy })
4777
+ ] }),
4778
+ /* @__PURE__ */ jsx("button", { type: "submit", className: "adechat-button", "data-variant": "primary", disabled: busy || !code.trim(), children: "Submit code" })
4779
+ ] }) : null,
4780
+ handle && !["succeeded", "failed", "cancelled", "expired"].includes(update.state) ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", onClick: () => void cancel(), disabled: busy, children: "Cancel sign-in" }) : null,
4781
+ !handle && onStart ? /* @__PURE__ */ jsx("button", { type: "button", className: "adechat-button", onClick: () => void start(), disabled: busy, children: busy ? "Starting\u2026" : "Start sign-in" }) : null,
4782
+ error ? /* @__PURE__ */ jsxs("p", { className: "adechat-account-error", role: "alert", children: [
4783
+ "Sign-in could not continue: ",
4784
+ error
4785
+ ] }) : null
4786
+ ] });
4787
+ }
4788
+
4789
+ export { ADE_CHAT_TOKENS, AccountList, AccountSwitcher, ActivityIndicator, AdeChat, AdeChatProvider, AdeChatStyles, AdeLink, AdeLinkHandlerProvider, ApiKeyForm, ApprovalCard, Composer, DAEX_CHAT_TOKENS, DEFAULT_APPROVAL_WAITING_LABEL, DEFAULT_ELAPSED_AFTER_MS, DEFAULT_HISTORY_PAGE_SIZE, DEFAULT_THINKING_LABEL, DaexChat, DaexChatProvider, DaexChatStyles, DaexLink, DaexLinkHandlerProvider, ModelPicker, NO_APPROVE_NOTICE, PendingInputCard, ProviderCard, ProviderCards, QueueStrip, SignInCard, ToolChip, Transcript, TranscriptRowBuilder, UNANSWERABLE_NOTICE, UsageLimitNotice, UsageMeter, adaptSdkClient, adeChatCss, approvalRequestFromRow, attachmentKind, blockedHint, buildTranscriptRows, collapseTranscriptEvents, createTheme, daexChatCss, defaultTheme, describeToolActivity, eventHasPayload, formatElapsed, formatStructuredValue, groupModelsByProvider, groupTranscriptRows, inferAttachmentType, injectAdeChatStyles, injectDaexChatStyles, isModelSelectable, isProviderUsable, matchLabelKey, mergeAttachments, mergeStreamingText, modelDescriptorsFromSdk, parseInline, parseMarkdownBlocks, parseToolIdentity, phaseForToolStatus, providerStatusesFromSdk, readApprovalCommand, readApprovalPaths, renderMarkdown, resolveActivityIcon, resolveActivityLabel, resolveComposerAction, resolveComposerState, resolveKeyIntent, resolveStateCopy, resolveToolName, safeHref, scoreModelSearch, shouldMergeTextRows, themeToCss, threadStatusFromEnvelope, threadUsageFromEnvelope, truncateBinaryPath, useAdeChatClient, useAdeChatContext, useAdeProviders, useAdeThread, useDaexChatClient, useDaexChatContext, useDaexProviders, useDaexThread, usePrefersReducedMotion };
4790
+ //# sourceMappingURL=index.js.map
4791
+ //# sourceMappingURL=index.js.map