@tinyweb_dev/agent-framework-chat-ui 0.2.0 → 0.4.0

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.
Files changed (101) hide show
  1. package/dist/components/Composer.d.ts +38 -0
  2. package/dist/components/Composer.d.ts.map +1 -0
  3. package/dist/components/Header.d.ts +7 -0
  4. package/dist/components/Header.d.ts.map +1 -0
  5. package/dist/components/Hero.d.ts +6 -0
  6. package/dist/components/Hero.d.ts.map +1 -0
  7. package/dist/components/RealtimeCallOverlay.d.ts +68 -0
  8. package/dist/components/RealtimeCallOverlay.d.ts.map +1 -0
  9. package/dist/components/RealtimeOrb.d.ts +21 -0
  10. package/dist/components/RealtimeOrb.d.ts.map +1 -0
  11. package/{src/components/Sidebar.tsx → dist/components/Sidebar.d.ts} +5 -9
  12. package/dist/components/Sidebar.d.ts.map +1 -0
  13. package/dist/components/TinywebChat.d.ts +3 -0
  14. package/dist/components/TinywebChat.d.ts.map +1 -0
  15. package/dist/components/Transcript.d.ts +20 -0
  16. package/dist/components/Transcript.d.ts.map +1 -0
  17. package/dist/components/WireOrbEffect.d.ts +17 -0
  18. package/dist/components/WireOrbEffect.d.ts.map +1 -0
  19. package/dist/components/condense/CondensePill.d.ts +11 -0
  20. package/dist/components/condense/CondensePill.d.ts.map +1 -0
  21. package/dist/components/messages/AssistantMessage.d.ts +10 -0
  22. package/dist/components/messages/AssistantMessage.d.ts.map +1 -0
  23. package/dist/components/messages/ErrorMessage.d.ts +7 -0
  24. package/dist/components/messages/ErrorMessage.d.ts.map +1 -0
  25. package/dist/components/messages/ToolMessage.d.ts +17 -0
  26. package/dist/components/messages/ToolMessage.d.ts.map +1 -0
  27. package/dist/components/messages/UserMessage.d.ts +7 -0
  28. package/dist/components/messages/UserMessage.d.ts.map +1 -0
  29. package/dist/components/tool/ExecRenderer.d.ts +14 -0
  30. package/dist/components/tool/ExecRenderer.d.ts.map +1 -0
  31. package/dist/components/tool/ImageRenderer.d.ts +16 -0
  32. package/dist/components/tool/ImageRenderer.d.ts.map +1 -0
  33. package/dist/components/tool/JsonRenderer.d.ts +11 -0
  34. package/dist/components/tool/JsonRenderer.d.ts.map +1 -0
  35. package/dist/components/tool/ToolCard.d.ts +29 -0
  36. package/dist/components/tool/ToolCard.d.ts.map +1 -0
  37. package/dist/components/tool/builtinRenderers.d.ts +9 -0
  38. package/dist/components/tool/builtinRenderers.d.ts.map +1 -0
  39. package/dist/hooks/useAgentChat.d.ts +46 -0
  40. package/dist/hooks/useAgentChat.d.ts.map +1 -0
  41. package/dist/hooks/useAnchorLatestUser.d.ts +15 -0
  42. package/dist/hooks/useAnchorLatestUser.d.ts.map +1 -0
  43. package/dist/hooks/useInitialScrollToEnd.d.ts +15 -0
  44. package/dist/hooks/useInitialScrollToEnd.d.ts.map +1 -0
  45. package/dist/hooks/useNdjsonStream.d.ts +11 -0
  46. package/dist/hooks/useNdjsonStream.d.ts.map +1 -0
  47. package/dist/hooks/useRealtimeCall.d.ts +112 -0
  48. package/dist/hooks/useRealtimeCall.d.ts.map +1 -0
  49. package/dist/index.cjs +3243 -0
  50. package/dist/index.cjs.map +1 -0
  51. package/dist/index.d.ts +20 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +3209 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/markdown/render.d.ts +2 -0
  56. package/dist/markdown/render.d.ts.map +1 -0
  57. package/{src → dist}/styles.css +29 -0
  58. package/dist/types.d.ts +257 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/util/attachments.d.ts +28 -0
  61. package/dist/util/attachments.d.ts.map +1 -0
  62. package/dist/util/escape.d.ts +2 -0
  63. package/dist/util/escape.d.ts.map +1 -0
  64. package/dist/util/theme.d.ts +13 -0
  65. package/dist/util/theme.d.ts.map +1 -0
  66. package/dist/util/tool-detect.d.ts +26 -0
  67. package/dist/util/tool-detect.d.ts.map +1 -0
  68. package/dist/util/tool-labels.d.ts +11 -0
  69. package/dist/util/tool-labels.d.ts.map +1 -0
  70. package/package.json +14 -14
  71. package/src/components/Composer.tsx +0 -267
  72. package/src/components/Header.tsx +0 -16
  73. package/src/components/Hero.tsx +0 -16
  74. package/src/components/RealtimeCallOverlay.tsx +0 -894
  75. package/src/components/RealtimeOrb.tsx +0 -388
  76. package/src/components/TinywebChat.tsx +0 -95
  77. package/src/components/Transcript.tsx +0 -146
  78. package/src/components/WireOrbEffect.tsx +0 -556
  79. package/src/components/condense/CondensePill.tsx +0 -77
  80. package/src/components/messages/AssistantMessage.tsx +0 -15
  81. package/src/components/messages/ErrorMessage.tsx +0 -12
  82. package/src/components/messages/ToolMessage.tsx +0 -49
  83. package/src/components/messages/UserMessage.tsx +0 -37
  84. package/src/components/tool/ExecRenderer.tsx +0 -71
  85. package/src/components/tool/ImageRenderer.tsx +0 -47
  86. package/src/components/tool/JsonRenderer.tsx +0 -24
  87. package/src/components/tool/ToolCard.tsx +0 -65
  88. package/src/components/tool/builtinRenderers.tsx +0 -456
  89. package/src/hooks/useAgentChat.ts +0 -454
  90. package/src/hooks/useAnchorLatestUser.ts +0 -99
  91. package/src/hooks/useInitialScrollToEnd.ts +0 -41
  92. package/src/hooks/useNdjsonStream.ts +0 -71
  93. package/src/hooks/useRealtimeCall.ts +0 -452
  94. package/src/index.ts +0 -45
  95. package/src/markdown/render.ts +0 -121
  96. package/src/types.ts +0 -241
  97. package/src/util/attachments.ts +0 -87
  98. package/src/util/escape.ts +0 -16
  99. package/src/util/theme.ts +0 -40
  100. package/src/util/tool-detect.ts +0 -65
  101. package/src/util/tool-labels.ts +0 -34
package/dist/index.js ADDED
@@ -0,0 +1,3209 @@
1
+ import { useState, useRef, useCallback, useEffect, useMemo, useLayoutEffect } from 'react';
2
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
3
+ import { connectRealtimeSession } from '@tinyweb_dev/agent-framework-realtime/client';
4
+ import * as THREE from 'three';
5
+ import { isAgentEvent } from '@tinyweb_dev/agent-framework-protocol';
6
+ import { Canvas, useFrame } from '@react-three/fiber';
7
+
8
+ // src/components/TinywebChat.tsx
9
+
10
+ // src/util/attachments.ts
11
+ var DEFAULT_IMAGE_MIMES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
12
+ var DEFAULT_MAX_BYTES_PER_FILE = 8 * 1024 * 1024;
13
+ var DEFAULT_MAX_BYTES_TOTAL = 16 * 1024 * 1024;
14
+ var DEFAULT_MAX_COUNT = 4;
15
+ var fileToBase64 = (file) => new Promise((resolve, reject) => {
16
+ const reader = new FileReader();
17
+ reader.onload = () => {
18
+ const result = reader.result;
19
+ if (typeof result !== "string") return reject(new Error("FileReader: non-string result"));
20
+ const idx = result.indexOf("base64,");
21
+ resolve(idx >= 0 ? result.slice(idx + "base64,".length) : result);
22
+ };
23
+ reader.onerror = () => reject(reader.error ?? new Error("FileReader error"));
24
+ reader.readAsDataURL(file);
25
+ });
26
+ var convertFile = async (file, current, limits) => {
27
+ const maxCount = limits?.maxCount ?? DEFAULT_MAX_COUNT;
28
+ const maxBytesPerFile = limits?.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;
29
+ const maxBytesTotal = limits?.maxBytesTotal ?? DEFAULT_MAX_BYTES_TOTAL;
30
+ const mimes = limits?.imageMimes ?? DEFAULT_IMAGE_MIMES;
31
+ if (current.length >= maxCount)
32
+ return {
33
+ ok: false,
34
+ error: { code: "attachment_too_many", message: `T\u1ED1i \u0111a ${maxCount} \u1EA3nh` }
35
+ };
36
+ if (!mimes.includes(file.type))
37
+ return {
38
+ ok: false,
39
+ error: {
40
+ code: "attachment_unsupported_type",
41
+ message: `\u0110\u1ECBnh d\u1EA1ng kh\xF4ng h\u1ED7 tr\u1EE3: ${file.type || "(unknown)"}`
42
+ }
43
+ };
44
+ if (file.size > maxBytesPerFile)
45
+ return {
46
+ ok: false,
47
+ error: {
48
+ code: "attachment_too_large",
49
+ message: `${file.name}: v\u01B0\u1EE3t qu\xE1 ${Math.round(maxBytesPerFile / 1024 / 1024)}MB`
50
+ }
51
+ };
52
+ const currentBytes = current.reduce((s, a) => s + (a.data ? Math.floor(a.data.length * 3 / 4) : 0), 0);
53
+ if (currentBytes + file.size > maxBytesTotal)
54
+ return {
55
+ ok: false,
56
+ error: {
57
+ code: "attachment_too_large",
58
+ message: `T\u1ED5ng dung l\u01B0\u1EE3ng v\u01B0\u1EE3t ${Math.round(maxBytesTotal / 1024 / 1024)}MB`
59
+ }
60
+ };
61
+ const data = await fileToBase64(file);
62
+ const previewUrl = URL.createObjectURL(file);
63
+ return {
64
+ ok: true,
65
+ image: { type: "image", mediaType: file.type, data, filename: file.name, previewUrl }
66
+ };
67
+ };
68
+ var revokePreview = (img) => {
69
+ if (img.previewUrl) URL.revokeObjectURL(img.previewUrl);
70
+ };
71
+ var Composer = (props) => {
72
+ const [value, setValue] = useState("");
73
+ const [images, setImages] = useState([]);
74
+ const [error, setError] = useState(null);
75
+ const [dragOver, setDragOver] = useState(false);
76
+ const fileInputRef = useRef(null);
77
+ const textareaRef = useRef(null);
78
+ useEffect(
79
+ () => () => {
80
+ images.forEach(revokePreview);
81
+ },
82
+ // eslint-disable-next-line react-hooks/exhaustive-deps
83
+ []
84
+ );
85
+ const limits = props.attachmentLimits;
86
+ const addFiles = async (files) => {
87
+ setError(null);
88
+ let next = images;
89
+ for (const file of Array.from(files)) {
90
+ const r = await convertFile(file, next, limits);
91
+ if (!r.ok) {
92
+ setError(r.error.message);
93
+ break;
94
+ }
95
+ next = next.concat(r.image);
96
+ }
97
+ setImages(next);
98
+ };
99
+ const removeAt = (idx) => {
100
+ const removed = images[idx];
101
+ if (removed) revokePreview(removed);
102
+ setImages(images.filter((_, i) => i !== idx));
103
+ setError(null);
104
+ };
105
+ const submit = () => {
106
+ const text = value.trim();
107
+ if (!text && images.length === 0 || props.disabled) return;
108
+ const out = images;
109
+ setValue("");
110
+ setImages([]);
111
+ setError(null);
112
+ props.onSend(text, out.length > 0 ? { images: out } : void 0);
113
+ const raf = globalThis.requestAnimationFrame;
114
+ if (raf) raf(() => textareaRef.current?.focus());
115
+ else textareaRef.current?.focus();
116
+ };
117
+ const onKeyDown = (e) => {
118
+ if (e.key !== "Enter" || e.shiftKey) return;
119
+ e.preventDefault();
120
+ submit();
121
+ };
122
+ const onPaste = (e) => {
123
+ const items = e.clipboardData?.items;
124
+ if (!items) return;
125
+ const files = [];
126
+ for (let i = 0; i < items.length; i++) {
127
+ const it = items[i];
128
+ if (it && it.kind === "file") {
129
+ const f = it.getAsFile();
130
+ if (f && DEFAULT_IMAGE_MIMES.includes(f.type)) files.push(f);
131
+ }
132
+ }
133
+ if (files.length > 0) {
134
+ e.preventDefault();
135
+ void addFiles(files);
136
+ }
137
+ };
138
+ const onDrop = (e) => {
139
+ e.preventDefault();
140
+ setDragOver(false);
141
+ const files = e.dataTransfer?.files;
142
+ if (files && files.length > 0) void addFiles(files);
143
+ };
144
+ const onPickFiles = (e) => {
145
+ const files = e.target.files;
146
+ if (files && files.length > 0) void addFiles(files);
147
+ e.target.value = "";
148
+ };
149
+ return /* @__PURE__ */ jsxs(
150
+ "div",
151
+ {
152
+ className: `composer${dragOver ? " composer-drop" : ""}`,
153
+ onDragEnter: (e) => {
154
+ e.preventDefault();
155
+ setDragOver(true);
156
+ },
157
+ onDragOver: (e) => e.preventDefault(),
158
+ onDragLeave: (e) => {
159
+ if (e.currentTarget === e.target) setDragOver(false);
160
+ },
161
+ onDrop,
162
+ children: [
163
+ images.length > 0 && /* @__PURE__ */ jsx("div", { className: "composer-attachments", "data-testid": "tinyweb-composer-attachments", children: images.map((img, i) => /* @__PURE__ */ jsxs("div", { className: "composer-thumb", children: [
164
+ img.previewUrl ? (
165
+ // eslint-disable-next-line @next/next/no-img-element
166
+ /* @__PURE__ */ jsx("img", { src: img.previewUrl, alt: img.filename ?? `image ${i + 1}` })
167
+ ) : /* @__PURE__ */ jsx("span", { className: "composer-thumb-fallback", children: img.filename ?? "image" }),
168
+ /* @__PURE__ */ jsx(
169
+ "button",
170
+ {
171
+ type: "button",
172
+ className: "composer-thumb-remove",
173
+ "aria-label": "Remove image",
174
+ onClick: () => removeAt(i),
175
+ children: "\xD7"
176
+ }
177
+ )
178
+ ] }, i)) }),
179
+ error && /* @__PURE__ */ jsx("div", { className: "composer-error", role: "alert", children: error }),
180
+ /* @__PURE__ */ jsxs("div", { className: "composer-inner", children: [
181
+ /* @__PURE__ */ jsx(
182
+ "button",
183
+ {
184
+ type: "button",
185
+ className: "attach-btn",
186
+ "aria-label": "Attach image",
187
+ disabled: props.disabled,
188
+ onClick: () => fileInputRef.current?.click(),
189
+ "data-testid": "tinyweb-composer-attach",
190
+ children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("path", { d: "m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" }) })
191
+ }
192
+ ),
193
+ props.onStartCall && /* @__PURE__ */ jsx(
194
+ "button",
195
+ {
196
+ type: "button",
197
+ className: "call-btn",
198
+ "aria-label": "Start voice call",
199
+ title: "Start voice call",
200
+ disabled: props.disabled || props.busy,
201
+ onClick: props.onStartCall,
202
+ "data-testid": "tinyweb-composer-call",
203
+ children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("path", { d: "M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92Z" }) })
204
+ }
205
+ ),
206
+ /* @__PURE__ */ jsx(
207
+ "input",
208
+ {
209
+ ref: fileInputRef,
210
+ type: "file",
211
+ accept: "image/*",
212
+ multiple: true,
213
+ style: { display: "none" },
214
+ onChange: onPickFiles,
215
+ "data-testid": "tinyweb-composer-file"
216
+ }
217
+ ),
218
+ /* @__PURE__ */ jsx(
219
+ "textarea",
220
+ {
221
+ ref: textareaRef,
222
+ rows: 1,
223
+ placeholder: props.placeholder ?? "Ask me anything\u2026",
224
+ value,
225
+ disabled: props.disabled,
226
+ onChange: (e) => setValue(e.target.value),
227
+ onKeyDown,
228
+ onPaste,
229
+ "data-testid": "tinyweb-composer-input"
230
+ }
231
+ ),
232
+ props.busy && props.onStop ? /* @__PURE__ */ jsx(
233
+ "button",
234
+ {
235
+ type: "button",
236
+ className: "send-btn stop-btn",
237
+ "aria-label": "Stop",
238
+ title: "Stop generating",
239
+ onClick: props.onStop,
240
+ "data-testid": "tinyweb-composer-stop",
241
+ children: /* @__PURE__ */ jsx(
242
+ "svg",
243
+ {
244
+ viewBox: "0 0 24 24",
245
+ fill: "currentColor",
246
+ stroke: "currentColor",
247
+ strokeWidth: 1,
248
+ strokeLinejoin: "round",
249
+ children: /* @__PURE__ */ jsx("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2" })
250
+ }
251
+ )
252
+ }
253
+ ) : /* @__PURE__ */ jsx(
254
+ "button",
255
+ {
256
+ type: "button",
257
+ className: "send-btn",
258
+ "aria-label": "Send",
259
+ disabled: props.disabled || !value.trim() && images.length === 0,
260
+ onClick: submit,
261
+ "data-testid": "tinyweb-composer-send",
262
+ children: /* @__PURE__ */ jsxs(
263
+ "svg",
264
+ {
265
+ viewBox: "0 0 24 24",
266
+ fill: "none",
267
+ stroke: "currentColor",
268
+ strokeWidth: 2.2,
269
+ strokeLinecap: "round",
270
+ strokeLinejoin: "round",
271
+ children: [
272
+ /* @__PURE__ */ jsx("path", { d: "M22 2 11 13" }),
273
+ /* @__PURE__ */ jsx("path", { d: "M22 2 15 22l-4-9-9-4 20-7Z" })
274
+ ]
275
+ }
276
+ )
277
+ }
278
+ )
279
+ ] })
280
+ ]
281
+ }
282
+ );
283
+ };
284
+ var Header = (props) => /* @__PURE__ */ jsxs("header", { className: "header", children: [
285
+ /* @__PURE__ */ jsxs("div", { className: "brand", children: [
286
+ /* @__PURE__ */ jsx("div", { className: "brand-mark", "aria-hidden": "true" }),
287
+ /* @__PURE__ */ jsx("h1", { children: props.title })
288
+ ] }),
289
+ props.right
290
+ ] });
291
+ var DEFAULT_IDLE_MS = 10 * 60 * 1e3;
292
+ var useRealtimeCall = (options) => {
293
+ const [status, setStatus] = useState("idle");
294
+ const [error, setError] = useState(null);
295
+ const [userTranscript, setUserTranscript] = useState("");
296
+ const [agentTranscript, setAgentTranscript] = useState("");
297
+ const [lastToolCall, setLastToolCall] = useState(null);
298
+ const [toolRunning, setToolRunning] = useState(false);
299
+ const [muted, setMutedState] = useState(false);
300
+ const sessionRef = useRef(null);
301
+ const audioCtxRef = useRef(null);
302
+ const micStreamRef = useRef(null);
303
+ const idleTimerRef = useRef(null);
304
+ const cancelledRef = useRef(false);
305
+ const idleMs = options.idleTimeoutMs ?? DEFAULT_IDLE_MS;
306
+ const levelRef = useRef(0);
307
+ const rafRef = useRef(null);
308
+ const [outputAnalyser, setOutputAnalyser] = useState(null);
309
+ const [inputAnalyser, setInputAnalyser] = useState(null);
310
+ const cleanup = useCallback(async () => {
311
+ cancelledRef.current = true;
312
+ if (idleTimerRef.current) {
313
+ clearTimeout(idleTimerRef.current);
314
+ idleTimerRef.current = null;
315
+ }
316
+ if (rafRef.current !== null) {
317
+ cancelAnimationFrame(rafRef.current);
318
+ rafRef.current = null;
319
+ }
320
+ levelRef.current = 0;
321
+ setOutputAnalyser(null);
322
+ setInputAnalyser(null);
323
+ const session = sessionRef.current;
324
+ sessionRef.current = null;
325
+ if (session) await session.close().catch(() => void 0);
326
+ const micStream = micStreamRef.current;
327
+ micStreamRef.current = null;
328
+ if (micStream) {
329
+ micStream.getTracks().forEach((t) => t.stop());
330
+ }
331
+ const ctx = audioCtxRef.current;
332
+ audioCtxRef.current = null;
333
+ if (ctx && ctx.state !== "closed") {
334
+ await ctx.close().catch(() => void 0);
335
+ }
336
+ }, []);
337
+ const resetIdleTimer = useCallback(() => {
338
+ if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
339
+ idleTimerRef.current = setTimeout(() => {
340
+ setStatus("ending");
341
+ void cleanup().then(() => setStatus("idle"));
342
+ }, idleMs);
343
+ }, [cleanup, idleMs]);
344
+ const start = useCallback(async () => {
345
+ if (status === "connecting" || status === "active") return;
346
+ cancelledRef.current = false;
347
+ setError(null);
348
+ setUserTranscript("");
349
+ setAgentTranscript("");
350
+ setLastToolCall(null);
351
+ setToolRunning(false);
352
+ setStatus("connecting");
353
+ const micStream = await navigator.mediaDevices.getUserMedia({
354
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
355
+ }).catch((err) => {
356
+ const msg = err instanceof Error ? err.message : String(err);
357
+ setError(`mic permission denied: ${msg}`);
358
+ setStatus("error");
359
+ return null;
360
+ });
361
+ if (!micStream) return;
362
+ if (cancelledRef.current) {
363
+ micStream.getTracks().forEach((t) => t.stop());
364
+ return;
365
+ }
366
+ micStreamRef.current = micStream;
367
+ const audioCtx = new AudioContext();
368
+ audioCtxRef.current = audioCtx;
369
+ if (audioCtx.state === "suspended") {
370
+ await audioCtx.resume().catch(() => void 0);
371
+ }
372
+ if (cancelledRef.current) {
373
+ await cleanup();
374
+ return;
375
+ }
376
+ const body = typeof options.tokenBody === "function" ? options.tokenBody() : options.tokenBody;
377
+ const handlerMap = /* @__PURE__ */ new Map();
378
+ if (options.toolHandlers) {
379
+ for (const [k, v] of Object.entries(options.toolHandlers)) {
380
+ handlerMap.set(k, v);
381
+ }
382
+ }
383
+ const proxyPath = options.toolProxyPath;
384
+ const proxyHeaders = options.toolProxyHeaders;
385
+ const fallbackToolHandler = proxyPath ? async (name, args) => {
386
+ const url = `${proxyPath.replace(/\/+$/, "")}/${encodeURIComponent(name)}`;
387
+ const res = await fetch(url, {
388
+ method: "POST",
389
+ headers: { "content-type": "application/json", ...proxyHeaders ?? {} },
390
+ body: JSON.stringify(args)
391
+ });
392
+ if (!res.ok) {
393
+ const text = await res.text().catch(() => res.statusText);
394
+ throw new Error(`tool proxy ${name} ${res.status}: ${text}`);
395
+ }
396
+ return await res.json();
397
+ } : void 0;
398
+ const initialHistory = typeof options.initialHistory === "function" ? options.initialHistory() : options.initialHistory;
399
+ const session = await connectRealtimeSession({
400
+ tokenEndpoint: options.tokenEndpoint,
401
+ headers: options.tokenHeaders,
402
+ body,
403
+ micStream,
404
+ audioContext: audioCtx,
405
+ toolHandlers: handlerMap,
406
+ fallbackToolHandler,
407
+ initialHistory
408
+ }).catch((err) => {
409
+ const msg = err instanceof Error ? err.message : String(err);
410
+ setError(`session failed: ${msg}`);
411
+ setStatus("error");
412
+ return null;
413
+ });
414
+ if (!session) {
415
+ await cleanup();
416
+ return;
417
+ }
418
+ if (cancelledRef.current) {
419
+ await session.close().catch(() => void 0);
420
+ await cleanup();
421
+ return;
422
+ }
423
+ sessionRef.current = session;
424
+ setStatus("active");
425
+ resetIdleTimer();
426
+ setOutputAnalyser(session.outputAnalyser);
427
+ setInputAnalyser(session.inputAnalyser);
428
+ const outBuf = new Uint8Array(session.outputAnalyser.frequencyBinCount);
429
+ const inBuf = new Uint8Array(session.inputAnalyser.frequencyBinCount);
430
+ const tick = () => {
431
+ session.outputAnalyser.getByteFrequencyData(outBuf);
432
+ session.inputAnalyser.getByteFrequencyData(inBuf);
433
+ const half = outBuf.length >> 1;
434
+ let outSum = 0;
435
+ let inSum = 0;
436
+ for (let i = 0; i < half; i++) {
437
+ outSum += outBuf[i] ?? 0;
438
+ inSum += inBuf[i] ?? 0;
439
+ }
440
+ const outAvg = outSum / (half * 255);
441
+ const inAvg = inSum / (half * 255);
442
+ const raw = Math.max(outAvg, inAvg * 0.7);
443
+ const shaped = Math.min(1, Math.pow(raw, 0.7) * 1.4);
444
+ levelRef.current = levelRef.current + (shaped - levelRef.current) * 0.35;
445
+ rafRef.current = requestAnimationFrame(tick);
446
+ };
447
+ rafRef.current = requestAnimationFrame(tick);
448
+ void (async () => {
449
+ for await (const event of session.events) {
450
+ options.onEvent?.(event);
451
+ resetIdleTimer();
452
+ switch (event.type) {
453
+ case "user-transcript-delta":
454
+ setUserTranscript((t) => t + event.text);
455
+ break;
456
+ case "user-transcript-final":
457
+ setUserTranscript("");
458
+ break;
459
+ case "agent-transcript-delta":
460
+ setAgentTranscript((t) => t + event.text);
461
+ break;
462
+ case "agent-transcript-final":
463
+ setAgentTranscript("");
464
+ break;
465
+ case "tool-call":
466
+ setLastToolCall({ name: event.name, args: event.args });
467
+ setToolRunning(true);
468
+ break;
469
+ case "tool-result":
470
+ case "tool-error":
471
+ setToolRunning(false);
472
+ break;
473
+ case "barge-in":
474
+ setAgentTranscript("");
475
+ break;
476
+ case "turn-complete":
477
+ setUserTranscript("");
478
+ setAgentTranscript("");
479
+ break;
480
+ case "error":
481
+ setError(event.message);
482
+ break;
483
+ case "closed":
484
+ setStatus("idle");
485
+ break;
486
+ }
487
+ }
488
+ })();
489
+ }, [cleanup, options, resetIdleTimer, status]);
490
+ const hangup = useCallback(async () => {
491
+ if (status === "idle") return;
492
+ setStatus("ending");
493
+ await cleanup();
494
+ setStatus("idle");
495
+ }, [cleanup, status]);
496
+ const setMuted = useCallback((next) => {
497
+ setMutedState(next);
498
+ sessionRef.current?.mute(next);
499
+ }, []);
500
+ useEffect(
501
+ () => () => {
502
+ void cleanup();
503
+ },
504
+ [cleanup]
505
+ );
506
+ return {
507
+ status,
508
+ error,
509
+ userTranscript,
510
+ agentTranscript,
511
+ lastToolCall,
512
+ toolRunning,
513
+ muted,
514
+ start,
515
+ hangup,
516
+ setMuted,
517
+ levelRef,
518
+ outputAnalyser,
519
+ inputAnalyser
520
+ };
521
+ };
522
+ var SCROLL_PADDING_TOP_PX = 16;
523
+ var useAnchorLatestUser = (containerRef, spacerRef, latestUserId) => {
524
+ const initialIdRef = useRef(null);
525
+ if (initialIdRef.current === null) {
526
+ initialIdRef.current = { value: latestUserId };
527
+ }
528
+ const anchoredIdRef = useRef(initialIdRef.current.value);
529
+ useEffect(() => {
530
+ const container = containerRef.current;
531
+ const spacer = spacerRef.current;
532
+ if (!container || !spacer) return;
533
+ const sync = () => {
534
+ const h = container.clientHeight - SCROLL_PADDING_TOP_PX;
535
+ spacer.style.minHeight = (h > 0 ? h : 0) + "px";
536
+ };
537
+ sync();
538
+ const RO = globalThis.ResizeObserver;
539
+ if (!RO) return;
540
+ const ro = new RO(sync);
541
+ ro.observe(container);
542
+ return () => ro.disconnect();
543
+ }, [containerRef, spacerRef]);
544
+ useLayoutEffect(() => {
545
+ if (latestUserId === null) return;
546
+ const initial = initialIdRef.current;
547
+ if (initial && initial.value !== null && latestUserId === initial.value) {
548
+ anchoredIdRef.current = latestUserId;
549
+ return;
550
+ }
551
+ if (anchoredIdRef.current === latestUserId) return;
552
+ const container = containerRef.current;
553
+ if (!container) return;
554
+ const row = container.querySelector(
555
+ `[data-msg-id="${CSS.escape(latestUserId)}"]`
556
+ );
557
+ if (!row) return;
558
+ const top = row.offsetTop - SCROLL_PADDING_TOP_PX;
559
+ container.scrollTo({ top: top > 0 ? top : 0, behavior: "smooth" });
560
+ anchoredIdRef.current = latestUserId;
561
+ }, [containerRef, latestUserId]);
562
+ };
563
+ var useInitialScrollToEnd = (containerRef, ready) => {
564
+ const doneRef = useRef(false);
565
+ useLayoutEffect(() => {
566
+ if (doneRef.current) return;
567
+ const el = containerRef.current;
568
+ if (!el) return;
569
+ if (el.scrollHeight <= el.clientHeight) return;
570
+ el.scrollTop = el.scrollHeight;
571
+ doneRef.current = true;
572
+ }, [containerRef, ready]);
573
+ };
574
+
575
+ // src/util/tool-labels.ts
576
+ var LABELS = {
577
+ time_now: { icon: "\u{1F552}", verb: "\u0110ang xem gi\u1EDD hi\u1EC7n t\u1EA1i" },
578
+ weather: { icon: "\u26C5", verb: "\u0110ang xem th\u1EDDi ti\u1EBFt" },
579
+ crypto_price: { icon: "\u{1FA99}", verb: "\u0110ang xem gi\xE1 crypto" },
580
+ vn_gold_price: { icon: "\u{1F947}", verb: "\u0110ang xem gi\xE1 v\xE0ng" },
581
+ vn_lottery: { icon: "\u{1F3AB}", verb: "\u0110ang xem k\u1EBFt qu\u1EA3 x\u1ED5 s\u1ED1" },
582
+ perplexity_search: { icon: "\u{1F50E}", verb: "\u0110ang t\xECm ki\u1EBFm v\u1EDBi Perplexity" },
583
+ web_search: { icon: "\u{1F310}", verb: "\u0110ang t\xECm ki\u1EBFm web" },
584
+ web_fetch: { icon: "\u{1F4C4}", verb: "\u0110ang t\u1EA3i n\u1ED9i dung trang" },
585
+ image_generate: { icon: "\u{1F3A8}", verb: "\u0110ang t\u1EA1o \u1EA3nh" },
586
+ image_describe: { icon: "\u{1F5BC}\uFE0F", verb: "\u0110ang m\xF4 t\u1EA3 \u1EA3nh" },
587
+ image_edit: { icon: "\u270F\uFE0F", verb: "\u0110ang ch\u1EC9nh s\u1EEDa \u1EA3nh" },
588
+ file_read: { icon: "\u{1F4C2}", verb: "\u0110ang \u0111\u1ECDc file" },
589
+ file_write: { icon: "\u{1F4BE}", verb: "\u0110ang l\u01B0u file" },
590
+ update_todo_list: { icon: "\u2705", verb: "\u0110ang c\u1EADp nh\u1EADt todo list" }
591
+ };
592
+ var friendlyToolLabel = (toolName) => {
593
+ const hit = LABELS[toolName];
594
+ if (hit) return hit;
595
+ return { icon: "\u{1F527}", verb: `\u0110ang g\u1ECDi c\xF4ng c\u1EE5 ${toolName}` };
596
+ };
597
+ var fmt = (n) => n.toLocaleString();
598
+ var StartContent = (props) => {
599
+ const overflow = props.state.trigger === "overflow-retry";
600
+ const base = overflow ? "Context overflow \u2014 recovering\u2026" : "Condensing context\u2026";
601
+ const stats = typeof props.state.estimatedTokens === "number" && typeof props.state.budgetTokens === "number" ? " (" + fmt(props.state.estimatedTokens) + " tok > " + fmt(props.state.budgetTokens) + " budget)" : "";
602
+ return /* @__PURE__ */ jsx("span", { children: base + stats });
603
+ };
604
+ var SuccessContent = (props) => {
605
+ const [open, setOpen] = useState(false);
606
+ const s = props.state;
607
+ const hasTokens = typeof s.prevTokens === "number" && typeof s.newTokens === "number";
608
+ return /* @__PURE__ */ jsxs(
609
+ "details",
610
+ {
611
+ open,
612
+ onToggle: (e) => setOpen(e.currentTarget.open),
613
+ children: [
614
+ /* @__PURE__ */ jsxs("summary", { children: [
615
+ "Context condensed",
616
+ hasTokens ? /* @__PURE__ */ jsxs(Fragment, { children: [
617
+ /* @__PURE__ */ jsxs("span", { className: "stat", children: [
618
+ " \u2014 ",
619
+ fmt(s.prevTokens ?? 0),
620
+ " "
621
+ ] }),
622
+ /* @__PURE__ */ jsx("span", { className: "arrow", children: "\u2192" }),
623
+ /* @__PURE__ */ jsxs("span", { className: "stat", children: [
624
+ " ",
625
+ fmt(s.newTokens ?? 0),
626
+ " tok"
627
+ ] })
628
+ ] }) : null,
629
+ typeof s.cost === "number" && s.cost > 0 ? /* @__PURE__ */ jsxs("span", { className: "stat", children: [
630
+ " \xB7 $",
631
+ s.cost.toFixed(4)
632
+ ] }) : null,
633
+ s.modelId ? /* @__PURE__ */ jsxs("span", { className: "arrow", children: [
634
+ " \xB7 ",
635
+ s.modelId
636
+ ] }) : null
637
+ ] }),
638
+ /* @__PURE__ */ jsx("div", { className: "summary-body", children: s.summary || "(no summary)" })
639
+ ]
640
+ }
641
+ );
642
+ };
643
+ var ErrorContent = (props) => /* @__PURE__ */ jsx("span", { children: props.state.retryExhausted ? "Compaction retry exhausted \u2014 request can't fit the model context." : "Condense failed: " + (props.state.message || "(unknown)") });
644
+ var CondensePill = (props) => {
645
+ const s = props.state;
646
+ const overflow = s.phase === "start" && s.trigger === "overflow-retry";
647
+ const classes = ["condense"];
648
+ if (overflow) classes.push("overflow");
649
+ if (s.phase === "success") classes.push("done");
650
+ if (s.phase === "error") classes.push("error");
651
+ return /* @__PURE__ */ jsxs("div", { className: classes.join(" "), "data-testid": "tinyweb-condense-pill", "data-phase": s.phase, children: [
652
+ /* @__PURE__ */ jsx("span", { className: "dot" }),
653
+ s.phase === "start" ? /* @__PURE__ */ jsx(StartContent, { state: s }) : null,
654
+ s.phase === "success" ? /* @__PURE__ */ jsx(SuccessContent, { state: s }) : null,
655
+ s.phase === "error" ? /* @__PURE__ */ jsx(ErrorContent, { state: s }) : null
656
+ ] });
657
+ };
658
+
659
+ // src/util/escape.ts
660
+ var REPLACEMENTS = {
661
+ "&": "&amp;",
662
+ "<": "&lt;",
663
+ ">": "&gt;",
664
+ '"': "&quot;",
665
+ "'": "&#39;"
666
+ };
667
+ var escapeHtml = (input) => String(input).replace(/[&<>"']/g, (c) => REPLACEMENTS[c] ?? c);
668
+
669
+ // src/markdown/render.ts
670
+ var renderMarkdown = (src) => {
671
+ if (!src) return "";
672
+ const codeBlocks = [];
673
+ let work = String(src).replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g, (_m, lang, body) => {
674
+ const i2 = codeBlocks.push({ lang, body }) - 1;
675
+ return "\0CODEBLOCK" + i2 + "\0";
676
+ });
677
+ work = escapeHtml(work);
678
+ const inlineCodes = [];
679
+ work = work.replace(/`([^`\n]+)`/g, (_m, body) => {
680
+ const i2 = inlineCodes.push(body) - 1;
681
+ return "\0INLINECODE" + i2 + "\0";
682
+ });
683
+ work = work.replace(
684
+ /\[([^\]]+)\]\(([^)\s]+)\)/g,
685
+ (_m, label, url) => '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + label + "</a>"
686
+ );
687
+ work = work.replace(
688
+ /(?<!["=>])\b(https?:\/\/[^\s<]+[^\s<.,;:!?)\]'"])/g,
689
+ (m) => '<a href="' + m + '" target="_blank" rel="noopener noreferrer">' + m + "</a>"
690
+ );
691
+ work = work.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>");
692
+ work = work.replace(/__([^_\n]+)__/g, "<strong>$1</strong>");
693
+ work = work.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>");
694
+ work = work.replace(/(^|[^_])_([^_\n]+)_(?!_)/g, "$1<em>$2</em>");
695
+ const lines = work.split("\n");
696
+ const out = [];
697
+ let i = 0;
698
+ while (i < lines.length) {
699
+ const line = lines[i] ?? "";
700
+ const h = line.match(/^\s*(#{1,6})\s+(.*?)\s*#*\s*$/);
701
+ if (h) {
702
+ const level = (h[1] ?? "").length;
703
+ out.push("<h" + level + ">" + h[2] + "</h" + level + ">");
704
+ i++;
705
+ continue;
706
+ }
707
+ const ol = line.match(/^\s*\d+\.\s+(.*)$/);
708
+ const ul = line.match(/^\s*[-*]\s+(.*)$/);
709
+ if (ol || ul) {
710
+ const tag = ol ? "ol" : "ul";
711
+ const re = ol ? /^\s*\d+\.\s+(.*)$/ : /^\s*[-*]\s+(.*)$/;
712
+ const items = [];
713
+ while (i < lines.length) {
714
+ const m = (lines[i] ?? "").match(re);
715
+ if (!m) break;
716
+ items.push("<li>" + m[1] + "</li>");
717
+ i++;
718
+ }
719
+ out.push("<" + tag + ">" + items.join("") + "</" + tag + ">");
720
+ continue;
721
+ }
722
+ out.push(line);
723
+ i++;
724
+ }
725
+ work = out.join("\n");
726
+ work = work.split(/\n{2,}/).map((chunk) => {
727
+ const trimmed = chunk.trim();
728
+ if (!trimmed) return "";
729
+ if (/^<(ul|ol|pre|h\d|blockquote)\b/i.test(trimmed)) return trimmed;
730
+ return "<p>" + trimmed.replace(/\n/g, "<br>") + "</p>";
731
+ }).filter(Boolean).join("");
732
+ work = work.replace(/\u0000INLINECODE(\d+)\u0000/g, (_m, idx) => {
733
+ const body = inlineCodes[Number(idx)] ?? "";
734
+ return "<code>" + escapeHtml(body) + "</code>";
735
+ });
736
+ work = work.replace(/\u0000CODEBLOCK(\d+)\u0000/g, (_m, idx) => {
737
+ const block = codeBlocks[Number(idx)];
738
+ if (!block) return "";
739
+ const cls = block.lang ? ' class="lang-' + escapeHtml(block.lang) + '"' : "";
740
+ return "<pre><code" + cls + ">" + escapeHtml(block.body) + "</code></pre>";
741
+ });
742
+ return work;
743
+ };
744
+ var AssistantMessage = (props) => /* @__PURE__ */ jsxs("div", { className: "msg assistant", children: [
745
+ /* @__PURE__ */ jsx("div", { className: "role", children: "assistant" }),
746
+ /* @__PURE__ */ jsx("div", { className: "body", dangerouslySetInnerHTML: { __html: renderMarkdown(props.content) } })
747
+ ] });
748
+ var ErrorMessage = (props) => /* @__PURE__ */ jsxs("div", { className: "msg error", children: [
749
+ /* @__PURE__ */ jsx("div", { className: "role", children: props.label ?? "error" }),
750
+ /* @__PURE__ */ jsx("div", { className: "body", children: props.message })
751
+ ] });
752
+
753
+ // src/util/tool-detect.ts
754
+ var extractToolImage = (result) => {
755
+ if (!result || typeof result !== "object") return void 0;
756
+ const r = result;
757
+ const mime = r.mimeType;
758
+ if (typeof mime !== "string" || !mime.startsWith("image/")) return void 0;
759
+ const b64Raw = r.imageBase64 ?? r.base64;
760
+ if (typeof b64Raw !== "string" || b64Raw.length === 0) return void 0;
761
+ const width = typeof r.width === "number" ? r.width : void 0;
762
+ const height = typeof r.height === "number" ? r.height : void 0;
763
+ return { mime, base64: b64Raw, width, height };
764
+ };
765
+ var extractExec = (result) => {
766
+ if (!result || typeof result !== "object") return void 0;
767
+ const r = result;
768
+ if (typeof r.exitCode !== "number") return void 0;
769
+ if (typeof r.stdout !== "string") return void 0;
770
+ if (typeof r.stderr !== "string") return void 0;
771
+ return {
772
+ exitCode: r.exitCode,
773
+ stdout: r.stdout,
774
+ stderr: r.stderr,
775
+ durationMs: typeof r.durationMs === "number" ? r.durationMs : void 0,
776
+ timedOut: typeof r.timedOut === "boolean" ? r.timedOut : void 0,
777
+ truncated: typeof r.truncated === "boolean" ? r.truncated : void 0
778
+ };
779
+ };
780
+ var truncateBase64InJson = (text) => text.replace(
781
+ /"(imageBase64|base64)":\s*"([^"]{40,})"/g,
782
+ (_m, key, val) => '"' + key + '": "<' + val.length + ' bytes base64 elided>"'
783
+ );
784
+ var ToolCard = (props) => {
785
+ const [showJson, setShowJson] = useState(false);
786
+ return /* @__PURE__ */ jsxs("div", { className: "msg tool-card", children: [
787
+ /* @__PURE__ */ jsxs("div", { className: "tool-card-head", children: [
788
+ /* @__PURE__ */ jsx("span", { className: "tool-card-icon", "aria-hidden": "true", children: props.icon }),
789
+ /* @__PURE__ */ jsxs("div", { className: "tool-card-title-block", children: [
790
+ /* @__PURE__ */ jsx("div", { className: "tool-card-title", children: props.title }),
791
+ props.subtitle ? /* @__PURE__ */ jsx("div", { className: "tool-card-sub", children: props.subtitle }) : null
792
+ ] }),
793
+ /* @__PURE__ */ jsxs("div", { className: "tool-card-head-right", children: [
794
+ props.source ? /* @__PURE__ */ jsx("span", { className: "tool-card-source", children: props.source }) : null,
795
+ props.jsonText ? /* @__PURE__ */ jsx(
796
+ "button",
797
+ {
798
+ type: "button",
799
+ className: "tool-json-toggle",
800
+ onClick: () => setShowJson((v) => !v),
801
+ children: showJson ? "\u1EA8n" : props.jsonLabel ?? "D\u1EEF li\u1EC7u th\xF4"
802
+ }
803
+ ) : null
804
+ ] })
805
+ ] }),
806
+ props.warnings && props.warnings.length > 0 ? /* @__PURE__ */ jsx("div", { className: "tool-card-warnings", children: props.warnings.map((w, i) => /* @__PURE__ */ jsxs("span", { className: "tool-card-warn-chip", children: [
807
+ "\u26A0 ",
808
+ w
809
+ ] }, i)) }) : null,
810
+ /* @__PURE__ */ jsx("div", { className: "tool-card-body", children: props.children }),
811
+ showJson && props.jsonText ? /* @__PURE__ */ jsx("pre", { className: "tool-json", children: props.jsonText }) : null
812
+ ] });
813
+ };
814
+ var safeStringify = (v) => {
815
+ try {
816
+ return JSON.stringify(v, null, 2);
817
+ } catch {
818
+ return String(v);
819
+ }
820
+ };
821
+ var isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
822
+ var asString = (v) => typeof v === "string" ? v : void 0;
823
+ var asNumber = (v) => typeof v === "number" ? v : void 0;
824
+ var asArray = (v) => Array.isArray(v) ? v : void 0;
825
+ var formatVnd = (n) => {
826
+ if (!Number.isFinite(n)) return "\u2014";
827
+ return n.toLocaleString("vi-VN") + " \u20AB";
828
+ };
829
+ var formatNumber = (n, digits = 2) => {
830
+ if (!Number.isFinite(n)) return "\u2014";
831
+ return n.toLocaleString("en-US", { maximumFractionDigits: digits });
832
+ };
833
+ var renderTimeNow = (ctx) => {
834
+ if (!isRecord(ctx.result)) return null;
835
+ const formatted = asString(ctx.result.formatted);
836
+ const tz = asString(ctx.result.timezone);
837
+ const weekday = asString(ctx.result.weekday);
838
+ if (!formatted) return null;
839
+ return /* @__PURE__ */ jsxs(
840
+ ToolCard,
841
+ {
842
+ icon: "\u{1F552}",
843
+ title: "Th\u1EDDi gian hi\u1EC7n t\u1EA1i",
844
+ subtitle: tz,
845
+ source: "System",
846
+ jsonText: safeStringify(ctx.result),
847
+ children: [
848
+ /* @__PURE__ */ jsx("div", { className: "tool-hero-line", children: formatted }),
849
+ weekday ? /* @__PURE__ */ jsx("div", { className: "tool-meta-line", children: weekday }) : null
850
+ ]
851
+ }
852
+ );
853
+ };
854
+ var renderWeather = (ctx) => {
855
+ if (!isRecord(ctx.result)) return null;
856
+ const location = asString(ctx.result.location);
857
+ const temp = asNumber(ctx.result.temperature_c);
858
+ const condition = asString(ctx.result.condition) ?? "\u2014";
859
+ if (!location || temp === void 0) return null;
860
+ const feels = asNumber(ctx.result.feels_like_c);
861
+ const humidity = asNumber(ctx.result.humidity_percent);
862
+ const wind = asNumber(ctx.result.wind_kmh);
863
+ const windDir = asString(ctx.result.wind_direction);
864
+ const uv = asNumber(ctx.result.uv_index);
865
+ const region = asString(ctx.result.region);
866
+ const country = asString(ctx.result.country);
867
+ const place = [location, region, country].filter((s) => Boolean(s)).join(", ");
868
+ return /* @__PURE__ */ jsxs(
869
+ ToolCard,
870
+ {
871
+ icon: "\u26C5",
872
+ title: `Th\u1EDDi ti\u1EBFt \xB7 ${location}`,
873
+ subtitle: place !== location ? place : void 0,
874
+ source: "wttr.in",
875
+ jsonText: safeStringify(ctx.result),
876
+ children: [
877
+ /* @__PURE__ */ jsxs("div", { className: "tool-hero-line", children: [
878
+ formatNumber(temp, 0),
879
+ "\xB0C \u2014 ",
880
+ condition
881
+ ] }),
882
+ /* @__PURE__ */ jsxs("div", { className: "tool-chip-row", children: [
883
+ feels !== void 0 ? /* @__PURE__ */ jsxs("span", { className: "tool-chip", children: [
884
+ "C\u1EA3m gi\xE1c ",
885
+ formatNumber(feels, 0),
886
+ "\xB0C"
887
+ ] }) : null,
888
+ humidity !== void 0 ? /* @__PURE__ */ jsxs("span", { className: "tool-chip", children: [
889
+ "\u0110\u1ED9 \u1EA9m ",
890
+ formatNumber(humidity, 0),
891
+ "%"
892
+ ] }) : null,
893
+ wind !== void 0 ? /* @__PURE__ */ jsxs("span", { className: "tool-chip", children: [
894
+ "Gi\xF3 ",
895
+ formatNumber(wind, 0),
896
+ " km/h",
897
+ windDir ? " " + windDir : ""
898
+ ] }) : null,
899
+ uv !== void 0 ? /* @__PURE__ */ jsxs("span", { className: "tool-chip", children: [
900
+ "UV ",
901
+ formatNumber(uv, 0)
902
+ ] }) : null
903
+ ] })
904
+ ]
905
+ }
906
+ );
907
+ };
908
+ var renderCryptoPrice = (ctx) => {
909
+ if (!isRecord(ctx.result)) return null;
910
+ const prices = asArray(ctx.result.prices);
911
+ if (!prices) return null;
912
+ const rows = [];
913
+ for (const p of prices) {
914
+ if (!isRecord(p)) continue;
915
+ const symbol = asString(p.symbol);
916
+ const quote = asString(p.quote);
917
+ const price = asNumber(p.price);
918
+ const pair = asString(p.pair);
919
+ if (!symbol || !quote || price === void 0) continue;
920
+ rows.push({ symbol, quote, price, pair: pair ?? `${symbol}${quote}` });
921
+ }
922
+ if (rows.length === 0) return null;
923
+ return /* @__PURE__ */ jsx(
924
+ ToolCard,
925
+ {
926
+ icon: "\u{1FA99}",
927
+ title: rows.length === 1 ? `Gi\xE1 crypto \xB7 ${rows[0].symbol}` : `Gi\xE1 crypto (${rows.length})`,
928
+ source: "Binance",
929
+ jsonText: safeStringify(ctx.result),
930
+ children: /* @__PURE__ */ jsx("div", { className: "tool-list", children: rows.map((r) => /* @__PURE__ */ jsxs("div", { className: "tool-row", children: [
931
+ /* @__PURE__ */ jsx("span", { className: "tool-row-label", children: r.symbol }),
932
+ /* @__PURE__ */ jsxs("span", { className: "tool-row-value", children: [
933
+ formatNumber(r.price, r.price >= 1 ? 2 : 6),
934
+ " ",
935
+ r.quote
936
+ ] })
937
+ ] }, r.pair)) })
938
+ }
939
+ );
940
+ };
941
+ var renderVnGold = (ctx) => {
942
+ if (!isRecord(ctx.result)) return null;
943
+ const items = asArray(ctx.result.items);
944
+ if (!items) return null;
945
+ const warnings = (asArray(ctx.result.warnings) ?? []).filter(
946
+ (w) => typeof w === "string"
947
+ );
948
+ const rows = [];
949
+ for (const it of items) {
950
+ if (!isRecord(it)) continue;
951
+ const vendor = asString(it.vendor);
952
+ const vendorFull = asString(it.vendor_full);
953
+ const product = asString(it.product);
954
+ const buy = asNumber(it.buy_vnd);
955
+ const sell = asNumber(it.sell_vnd);
956
+ const unit = asString(it.unit);
957
+ const url = asString(it.source_url);
958
+ if (!vendor || buy === void 0 || sell === void 0) continue;
959
+ rows.push({
960
+ vendor,
961
+ vendor_full: vendorFull ?? vendor,
962
+ product: product ?? "\u2014",
963
+ buy_vnd: buy,
964
+ sell_vnd: sell,
965
+ unit: unit ?? "",
966
+ source_url: url ?? ""
967
+ });
968
+ }
969
+ if (rows.length === 0 && warnings.length === 0) return null;
970
+ return /* @__PURE__ */ jsx(
971
+ ToolCard,
972
+ {
973
+ icon: "\u{1F947}",
974
+ title: "Gi\xE1 v\xE0ng trong n\u01B0\u1EDBc",
975
+ subtitle: "Tham kh\u1EA3o \u2014 bi\u1EBFn \u0111\u1ED9ng theo ph\xFAt",
976
+ source: "BTMC / BTMH",
977
+ warnings,
978
+ jsonText: safeStringify(ctx.result),
979
+ children: rows.length === 0 ? /* @__PURE__ */ jsx("div", { className: "tool-meta-line", children: "Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c gi\xE1. Vui l\xF2ng th\u1EED l\u1EA1i." }) : /* @__PURE__ */ jsx("div", { className: "tool-list", children: rows.map((r, i) => /* @__PURE__ */ jsxs("div", { className: "tool-row tool-row-stacked", children: [
980
+ /* @__PURE__ */ jsxs("div", { className: "tool-row-head", children: [
981
+ /* @__PURE__ */ jsx("span", { className: "tool-row-label", children: r.vendor_full }),
982
+ r.unit ? /* @__PURE__ */ jsx("span", { className: "tool-chip subtle", children: r.unit }) : null
983
+ ] }),
984
+ /* @__PURE__ */ jsx("div", { className: "tool-row-sub", children: r.product }),
985
+ /* @__PURE__ */ jsxs("div", { className: "tool-row-prices", children: [
986
+ /* @__PURE__ */ jsxs("span", { className: "tool-price", children: [
987
+ /* @__PURE__ */ jsx("em", { children: "Mua" }),
988
+ " ",
989
+ formatVnd(r.buy_vnd)
990
+ ] }),
991
+ /* @__PURE__ */ jsxs("span", { className: "tool-price", children: [
992
+ /* @__PURE__ */ jsx("em", { children: "B\xE1n" }),
993
+ " ",
994
+ formatVnd(r.sell_vnd)
995
+ ] })
996
+ ] })
997
+ ] }, i)) })
998
+ }
999
+ );
1000
+ };
1001
+ var renderVnLottery = (ctx) => {
1002
+ if (!isRecord(ctx.result)) return null;
1003
+ const regionLabel = asString(ctx.result.region_label) ?? asString(ctx.result.region);
1004
+ const date = asString(ctx.result.date);
1005
+ const prizesRaw = asArray(ctx.result.prizes);
1006
+ const warnings = (asArray(ctx.result.warnings) ?? []).filter(
1007
+ (w) => typeof w === "string"
1008
+ );
1009
+ if (!regionLabel || !prizesRaw) return null;
1010
+ const prizes = [];
1011
+ for (const p of prizesRaw) {
1012
+ if (!isRecord(p)) continue;
1013
+ const name = asString(p.name);
1014
+ const numbers = asArray(p.numbers);
1015
+ if (!name || !numbers) continue;
1016
+ prizes.push({
1017
+ name,
1018
+ numbers: numbers.filter((n) => typeof n === "string")
1019
+ });
1020
+ }
1021
+ return /* @__PURE__ */ jsx(
1022
+ ToolCard,
1023
+ {
1024
+ icon: "\u{1F3AB}",
1025
+ title: `K\u1EBFt qu\u1EA3 x\u1ED5 s\u1ED1 \xB7 ${regionLabel}`,
1026
+ subtitle: date ? `Ng\xE0y ${date}` : void 0,
1027
+ source: "xoso.com.vn",
1028
+ warnings,
1029
+ jsonText: safeStringify(ctx.result),
1030
+ children: prizes.length === 0 ? /* @__PURE__ */ jsx("div", { className: "tool-meta-line", children: "Ch\u01B0a c\xF3 k\u1EBFt qu\u1EA3." }) : /* @__PURE__ */ jsx("div", { className: "tool-list", children: prizes.map((p, i) => /* @__PURE__ */ jsxs("div", { className: "tool-row tool-row-stacked", children: [
1031
+ /* @__PURE__ */ jsx("div", { className: "tool-row-head", children: /* @__PURE__ */ jsx("span", { className: "tool-row-label", children: p.name }) }),
1032
+ /* @__PURE__ */ jsx("div", { className: "tool-lottery-numbers", children: p.numbers.map((n, j) => /* @__PURE__ */ jsx("span", { className: "tool-lottery-num", children: n }, j)) })
1033
+ ] }, i)) })
1034
+ }
1035
+ );
1036
+ };
1037
+ var hostOf = (url) => {
1038
+ try {
1039
+ return new URL(url).hostname.replace(/^www\./, "");
1040
+ } catch {
1041
+ return url;
1042
+ }
1043
+ };
1044
+ var renderPerplexity = (ctx) => {
1045
+ if (!isRecord(ctx.result)) return null;
1046
+ const query = asString(ctx.result.query);
1047
+ const answer = asString(ctx.result.answer);
1048
+ const citationsRaw = asArray(ctx.result.citations);
1049
+ if (!answer) return null;
1050
+ const citations = [];
1051
+ for (const c of citationsRaw ?? []) {
1052
+ if (!isRecord(c)) continue;
1053
+ const url = asString(c.url);
1054
+ if (!url) continue;
1055
+ const title = asString(c.title);
1056
+ citations.push(title ? { url, title } : { url });
1057
+ }
1058
+ return /* @__PURE__ */ jsxs(
1059
+ ToolCard,
1060
+ {
1061
+ icon: "\u{1F50E}",
1062
+ title: "T\xECm ki\u1EBFm v\u1EDBi Perplexity",
1063
+ subtitle: query,
1064
+ source: "Perplexity",
1065
+ jsonText: safeStringify(ctx.result),
1066
+ children: [
1067
+ /* @__PURE__ */ jsx(
1068
+ "div",
1069
+ {
1070
+ className: "tool-answer tool-answer-md",
1071
+ dangerouslySetInnerHTML: { __html: renderMarkdown(answer) }
1072
+ }
1073
+ ),
1074
+ citations.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "tool-citations", children: [
1075
+ /* @__PURE__ */ jsx("div", { className: "tool-section-label", children: "Ngu\u1ED3n" }),
1076
+ /* @__PURE__ */ jsx("ol", { className: "tool-citations-list", children: citations.map((c, i) => /* @__PURE__ */ jsxs("li", { children: [
1077
+ /* @__PURE__ */ jsx("a", { href: c.url, target: "_blank", rel: "noopener noreferrer", children: c.title ?? hostOf(c.url) }),
1078
+ " ",
1079
+ /* @__PURE__ */ jsx("span", { className: "tool-cite-host", children: hostOf(c.url) })
1080
+ ] }, i)) })
1081
+ ] }) : null
1082
+ ]
1083
+ }
1084
+ );
1085
+ };
1086
+ var renderWebSearch = (ctx) => {
1087
+ if (!isRecord(ctx.result)) return null;
1088
+ const resultsRaw = asArray(ctx.result.results);
1089
+ if (!resultsRaw) return null;
1090
+ const hits = [];
1091
+ for (const r of resultsRaw) {
1092
+ if (!isRecord(r)) continue;
1093
+ const title = asString(r.title);
1094
+ const url = asString(r.url);
1095
+ const snippet = asString(r.snippet) ?? "";
1096
+ if (!title || !url) continue;
1097
+ hits.push({ title, url, snippet });
1098
+ }
1099
+ if (hits.length === 0) return null;
1100
+ return /* @__PURE__ */ jsx(
1101
+ ToolCard,
1102
+ {
1103
+ icon: "\u{1F310}",
1104
+ title: "T\xECm ki\u1EBFm web",
1105
+ subtitle: `${hits.length} k\u1EBFt qu\u1EA3`,
1106
+ jsonText: safeStringify(ctx.result),
1107
+ children: /* @__PURE__ */ jsx("ol", { className: "tool-search-list", children: hits.map((h, i) => /* @__PURE__ */ jsxs("li", { className: "tool-search-item", children: [
1108
+ /* @__PURE__ */ jsx("a", { href: h.url, target: "_blank", rel: "noopener noreferrer", className: "tool-search-title", children: h.title }),
1109
+ /* @__PURE__ */ jsx("div", { className: "tool-search-host", children: hostOf(h.url) }),
1110
+ h.snippet ? /* @__PURE__ */ jsx("div", { className: "tool-search-snippet", children: h.snippet }) : null
1111
+ ] }, i)) })
1112
+ }
1113
+ );
1114
+ };
1115
+ var renderWebFetch = (ctx) => {
1116
+ if (!isRecord(ctx.result)) return null;
1117
+ const url = asString(ctx.result.url);
1118
+ const title = asString(ctx.result.title);
1119
+ const content = asString(ctx.result.content) ?? asString(ctx.result.text);
1120
+ if (!url) return null;
1121
+ const preview = content ? content.length > 800 ? content.slice(0, 800) + "\u2026" : content : void 0;
1122
+ return /* @__PURE__ */ jsxs(
1123
+ ToolCard,
1124
+ {
1125
+ icon: "\u{1F4C4}",
1126
+ title: title ?? "\u0110\xE3 t\u1EA3i trang",
1127
+ subtitle: hostOf(url),
1128
+ jsonText: safeStringify(ctx.result),
1129
+ children: [
1130
+ /* @__PURE__ */ jsx("div", { className: "tool-meta-line", children: /* @__PURE__ */ jsx("a", { href: url, target: "_blank", rel: "noopener noreferrer", children: url }) }),
1131
+ preview ? /* @__PURE__ */ jsx("div", { className: "tool-fetch-preview", children: preview }) : null
1132
+ ]
1133
+ }
1134
+ );
1135
+ };
1136
+ var asTodoStatus = (v) => {
1137
+ if (v === "completed" || v === "in_progress" || v === "pending") return v;
1138
+ return "pending";
1139
+ };
1140
+ var todoIcon = (status) => {
1141
+ if (status === "completed") return "\u2713";
1142
+ if (status === "in_progress") return "\u2192";
1143
+ return "\u25A1";
1144
+ };
1145
+ var parseTodosFromResult = (result, raw) => {
1146
+ const fromRecord = (v) => {
1147
+ if (!isRecord(v)) return null;
1148
+ const arr = asArray(v.todos);
1149
+ if (!arr || arr.length === 0) return null;
1150
+ const rows = [];
1151
+ for (const item of arr) {
1152
+ if (!isRecord(item)) continue;
1153
+ const content = asString(item.content);
1154
+ if (!content) continue;
1155
+ rows.push({
1156
+ id: asString(item.id),
1157
+ content,
1158
+ status: asTodoStatus(item.status)
1159
+ });
1160
+ }
1161
+ return rows.length > 0 ? rows : null;
1162
+ };
1163
+ const fromResult = fromRecord(result);
1164
+ if (fromResult) return fromResult;
1165
+ if (isRecord(raw) && isRecord(raw.input)) {
1166
+ const inputTodos = raw.input.todos;
1167
+ if (typeof inputTodos === "string") {
1168
+ const lines = inputTodos.replace(/\\n/g, "\n").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
1169
+ const rows = [];
1170
+ for (const line of lines) {
1171
+ const m = line.match(/^(?:-\s*)?\[\s*([ xX\-~])\s*\]\s+(.+)$/);
1172
+ if (!m) continue;
1173
+ const mark = m[1];
1174
+ let status = "pending";
1175
+ if (mark === "x" || mark === "X") status = "completed";
1176
+ else if (mark === "-" || mark === "~") status = "in_progress";
1177
+ rows.push({ content: m[2], status });
1178
+ }
1179
+ return rows.length > 0 ? rows : null;
1180
+ }
1181
+ return fromRecord(raw.input);
1182
+ }
1183
+ return null;
1184
+ };
1185
+ var renderUpdateTodoList = (ctx) => {
1186
+ const todos = parseTodosFromResult(ctx.result, ctx.raw);
1187
+ if (!todos) return null;
1188
+ const total = todos.length;
1189
+ const completed = todos.filter((t) => t.status === "completed").length;
1190
+ const allDone = completed === total && total > 0;
1191
+ const inProgress = todos.find((t) => t.status === "in_progress");
1192
+ const nextOpen = todos.find((t) => t.status !== "completed");
1193
+ const focus = inProgress ?? nextOpen;
1194
+ const subtitle = allDone ? `Ho\xE0n th\xE0nh ${completed}/${total}` : focus ? focus.content : `${completed}/${total}`;
1195
+ return /* @__PURE__ */ jsx(
1196
+ ToolCard,
1197
+ {
1198
+ icon: "\u2705",
1199
+ title: "Todo list",
1200
+ subtitle,
1201
+ source: `${completed}/${total}`,
1202
+ jsonText: safeStringify(ctx.result),
1203
+ children: /* @__PURE__ */ jsx("ul", { className: "tool-todo-list", "data-todo-list": true, children: todos.map((todo, idx) => /* @__PURE__ */ jsxs(
1204
+ "li",
1205
+ {
1206
+ className: `tool-todo-item tool-todo-${todo.status}`,
1207
+ children: [
1208
+ /* @__PURE__ */ jsx("span", { className: "tool-todo-icon", "aria-hidden": "true", children: todoIcon(todo.status) }),
1209
+ /* @__PURE__ */ jsx("span", { className: "tool-todo-content", children: todo.content })
1210
+ ]
1211
+ },
1212
+ todo.id ?? `${todo.content}-${idx}`
1213
+ )) })
1214
+ }
1215
+ );
1216
+ };
1217
+ var renderDisplayResponse = (ctx) => {
1218
+ const message = isRecord(ctx.result) && asString(ctx.result.response) || isRecord(ctx.raw) && isRecord(ctx.raw.input) && asString(ctx.raw.input.response);
1219
+ if (!message) return null;
1220
+ return /* @__PURE__ */ jsxs("div", { className: "msg assistant", children: [
1221
+ /* @__PURE__ */ jsx("div", { className: "role", children: "assistant" }),
1222
+ /* @__PURE__ */ jsx("div", { className: "body", dangerouslySetInnerHTML: { __html: renderMarkdown(message) } })
1223
+ ] });
1224
+ };
1225
+ var byName = (names, render) => ({
1226
+ match: (toolName) => names.includes(toolName),
1227
+ render
1228
+ });
1229
+ var defaultToolRenderers = [
1230
+ byName(["time_now"], renderTimeNow),
1231
+ byName(["weather"], renderWeather),
1232
+ byName(["crypto_price"], renderCryptoPrice),
1233
+ byName(["vn_gold_price"], renderVnGold),
1234
+ byName(["vn_lottery"], renderVnLottery),
1235
+ byName(["perplexity_search"], renderPerplexity),
1236
+ byName(["web_search"], renderWebSearch),
1237
+ byName(["web_fetch"], renderWebFetch),
1238
+ byName(["update_todo_list"], renderUpdateTodoList),
1239
+ byName(["display_response"], renderDisplayResponse)
1240
+ ];
1241
+ var COLLAPSE_LINES = 20;
1242
+ var CollapsibleBlock = (props) => {
1243
+ const [open, setOpen] = useState(false);
1244
+ if (!props.text) return null;
1245
+ const lines = props.text.split("\n");
1246
+ const collapsed = lines.length > COLLAPSE_LINES;
1247
+ const display = collapsed && !open ? lines.slice(0, COLLAPSE_LINES).join("\n") + "\n\u2026" : props.text;
1248
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1249
+ props.label ? /* @__PURE__ */ jsx("div", { className: "exec-section-label", children: props.label }) : null,
1250
+ /* @__PURE__ */ jsx("pre", { className: props.klass, children: display }),
1251
+ collapsed ? /* @__PURE__ */ jsx(
1252
+ "button",
1253
+ {
1254
+ type: "button",
1255
+ className: "exec-show-more",
1256
+ onClick: () => setOpen((v) => !v),
1257
+ children: open ? "Collapse" : "Show all " + lines.length + " lines"
1258
+ }
1259
+ ) : null
1260
+ ] });
1261
+ };
1262
+ var ExecRenderer = (props) => {
1263
+ const [showJson, setShowJson] = useState(false);
1264
+ const exitClass = props.exec.exitCode === 0 ? "ok" : "fail";
1265
+ return /* @__PURE__ */ jsxs("div", { className: "msg tool", children: [
1266
+ /* @__PURE__ */ jsxs("div", { className: "role-row", children: [
1267
+ /* @__PURE__ */ jsxs("div", { className: "role", children: [
1268
+ props.toolName,
1269
+ " \u2190"
1270
+ ] }),
1271
+ /* @__PURE__ */ jsx(
1272
+ "button",
1273
+ {
1274
+ type: "button",
1275
+ className: "tool-json-toggle",
1276
+ onClick: () => setShowJson((v) => !v),
1277
+ children: showJson ? "Hide JSON" : "View JSON"
1278
+ }
1279
+ )
1280
+ ] }),
1281
+ /* @__PURE__ */ jsxs("div", { className: "body has-exec", children: [
1282
+ /* @__PURE__ */ jsxs("div", { className: "exec-meta", children: [
1283
+ /* @__PURE__ */ jsxs("span", { className: "exec-chip " + exitClass, children: [
1284
+ "exit ",
1285
+ props.exec.exitCode
1286
+ ] }),
1287
+ typeof props.exec.durationMs === "number" ? /* @__PURE__ */ jsxs("span", { className: "exec-chip", children: [
1288
+ props.exec.durationMs,
1289
+ " ms"
1290
+ ] }) : null,
1291
+ props.exec.timedOut ? /* @__PURE__ */ jsx("span", { className: "exec-chip warn", children: "timed out" }) : null,
1292
+ props.exec.truncated ? /* @__PURE__ */ jsx("span", { className: "exec-chip warn", children: "truncated" }) : null
1293
+ ] }),
1294
+ /* @__PURE__ */ jsx(CollapsibleBlock, { text: props.exec.stdout, klass: "exec-stdout" }),
1295
+ /* @__PURE__ */ jsx(CollapsibleBlock, { text: props.exec.stderr, klass: "exec-stderr", label: "stderr" }),
1296
+ showJson ? /* @__PURE__ */ jsx("pre", { className: "tool-json", children: props.jsonText }) : null
1297
+ ] })
1298
+ ] });
1299
+ };
1300
+ var ImageRenderer = (props) => {
1301
+ const [showJson, setShowJson] = useState(false);
1302
+ const src = "data:" + props.image.mime + ";base64," + props.image.base64;
1303
+ const sizeText = props.image.width && props.image.height ? props.image.width + "\xD7" + props.image.height + " \xB7 " + props.image.mime : void 0;
1304
+ return /* @__PURE__ */ jsxs("div", { className: "msg tool", children: [
1305
+ /* @__PURE__ */ jsxs("div", { className: "role-row", children: [
1306
+ /* @__PURE__ */ jsxs("div", { className: "role", children: [
1307
+ props.toolName,
1308
+ " \u2190"
1309
+ ] }),
1310
+ /* @__PURE__ */ jsx(
1311
+ "button",
1312
+ {
1313
+ type: "button",
1314
+ className: "tool-json-toggle",
1315
+ onClick: () => setShowJson((v) => !v),
1316
+ children: showJson ? "Hide JSON" : "View JSON"
1317
+ }
1318
+ )
1319
+ ] }),
1320
+ /* @__PURE__ */ jsxs("div", { className: "body has-image", children: [
1321
+ /* @__PURE__ */ jsx("img", { className: "tool-image", src, alt: props.toolName + " result" }),
1322
+ sizeText ? /* @__PURE__ */ jsx("div", { className: "tool-image-meta", children: sizeText }) : null,
1323
+ showJson ? /* @__PURE__ */ jsx("pre", { className: "tool-json", children: truncateBase64InJson(props.jsonText) }) : null
1324
+ ] })
1325
+ ] });
1326
+ };
1327
+ var MAX_PREVIEW = 1e3;
1328
+ var JsonRenderer = (props) => {
1329
+ const preview = props.jsonText.length > MAX_PREVIEW ? props.jsonText.slice(0, MAX_PREVIEW) : props.jsonText;
1330
+ return /* @__PURE__ */ jsxs("div", { className: "msg tool", children: [
1331
+ /* @__PURE__ */ jsx("div", { className: "role-row", children: /* @__PURE__ */ jsxs("div", { className: "role", children: [
1332
+ props.toolName,
1333
+ " \u2190"
1334
+ ] }) }),
1335
+ /* @__PURE__ */ jsx("div", { className: "body", children: preview })
1336
+ ] });
1337
+ };
1338
+ var safeStringify2 = (v) => {
1339
+ try {
1340
+ return JSON.stringify(v, null, 2);
1341
+ } catch {
1342
+ return String(v);
1343
+ }
1344
+ };
1345
+ var ToolMessage = (props) => {
1346
+ const userRenderers = props.toolRenderers ?? [];
1347
+ const all = [...userRenderers, ...defaultToolRenderers];
1348
+ for (const r of all) {
1349
+ if (!r.match(props.toolName, props.result)) continue;
1350
+ const node = r.render({ toolName: props.toolName, result: props.result, raw: props.raw });
1351
+ if (node !== null && node !== void 0) return /* @__PURE__ */ jsx(Fragment, { children: node });
1352
+ }
1353
+ const jsonText = safeStringify2(props.result);
1354
+ const exec = extractExec(props.result);
1355
+ if (exec) {
1356
+ return /* @__PURE__ */ jsx(ExecRenderer, { toolName: props.toolName, exec, jsonText });
1357
+ }
1358
+ const image = extractToolImage(props.result);
1359
+ if (image) {
1360
+ return /* @__PURE__ */ jsx(ImageRenderer, { toolName: props.toolName, image, jsonText });
1361
+ }
1362
+ return /* @__PURE__ */ jsx(JsonRenderer, { toolName: props.toolName, jsonText });
1363
+ };
1364
+ var renderSrc = (img) => {
1365
+ if (img.previewUrl) return img.previewUrl;
1366
+ if (img.url) return img.url;
1367
+ if (img.data) return `data:${img.mediaType};base64,${img.data}`;
1368
+ return void 0;
1369
+ };
1370
+ var UserMessage = (props) => /* @__PURE__ */ jsxs("div", { className: "msg user", children: [
1371
+ /* @__PURE__ */ jsx("div", { className: "role", children: "user" }),
1372
+ props.images && props.images.length > 0 && /* @__PURE__ */ jsx("div", { className: "msg-images", "data-testid": "tinyweb-user-images", children: props.images.map((img, i) => {
1373
+ const src = renderSrc(img);
1374
+ if (!src)
1375
+ return /* @__PURE__ */ jsx("span", { className: "msg-image-fallback", children: img.filename ?? "image" }, i);
1376
+ return (
1377
+ // eslint-disable-next-line @next/next/no-img-element
1378
+ /* @__PURE__ */ jsx("img", { src, alt: img.filename ?? `image ${i + 1}`, className: "msg-image" }, i)
1379
+ );
1380
+ }) }),
1381
+ props.content && /* @__PURE__ */ jsx("div", { className: "body", children: props.content })
1382
+ ] });
1383
+ var NOISE_GLSL = (
1384
+ /* glsl */
1385
+ `
1386
+ vec3 mod289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;}
1387
+ vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}
1388
+ vec4 permute(vec4 x){return mod289(((x*34.0)+1.0)*x);}
1389
+ vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}
1390
+ float snoise(vec3 v){
1391
+ const vec2 C = vec2(1.0/6.0, 1.0/3.0);
1392
+ const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
1393
+ vec3 i = floor(v + dot(v, C.yyy));
1394
+ vec3 x0 = v - i + dot(i, C.xxx);
1395
+ vec3 g = step(x0.yzx, x0.xyz);
1396
+ vec3 l = 1.0 - g;
1397
+ vec3 i1 = min(g.xyz, l.zxy);
1398
+ vec3 i2 = max(g.xyz, l.zxy);
1399
+ vec3 x1 = x0 - i1 + C.xxx;
1400
+ vec3 x2 = x0 - i2 + C.yyy;
1401
+ vec3 x3 = x0 - D.yyy;
1402
+ i = mod289(i);
1403
+ vec4 p = permute( permute( permute(
1404
+ i.z + vec4(0.0, i1.z, i2.z, 1.0))
1405
+ + i.y + vec4(0.0, i1.y, i2.y, 1.0))
1406
+ + i.x + vec4(0.0, i1.x, i2.x, 1.0));
1407
+ float n_ = 0.142857142857;
1408
+ vec3 ns = n_ * D.wyz - D.xzx;
1409
+ vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
1410
+ vec4 x_ = floor(j * ns.z);
1411
+ vec4 y_ = floor(j - 7.0 * x_);
1412
+ vec4 x = x_ *ns.x + ns.yyyy;
1413
+ vec4 y = y_ *ns.x + ns.yyyy;
1414
+ vec4 h = 1.0 - abs(x) - abs(y);
1415
+ vec4 b0 = vec4(x.xy, y.xy);
1416
+ vec4 b1 = vec4(x.zw, y.zw);
1417
+ vec4 s0 = floor(b0)*2.0 + 1.0;
1418
+ vec4 s1 = floor(b1)*2.0 + 1.0;
1419
+ vec4 sh = -step(h, vec4(0.0));
1420
+ vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy;
1421
+ vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww;
1422
+ vec3 p0 = vec3(a0.xy, h.x);
1423
+ vec3 p1 = vec3(a0.zw, h.y);
1424
+ vec3 p2 = vec3(a1.xy, h.z);
1425
+ vec3 p3 = vec3(a1.zw, h.w);
1426
+ vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2,p2), dot(p3,p3)));
1427
+ p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;
1428
+ vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
1429
+ m = m*m;
1430
+ return 42.0 * dot(m*m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));
1431
+ }
1432
+ float hash13(vec3 p){
1433
+ return fract(sin(dot(p, vec3(12.9898, 78.233, 45.164))) * 43758.5453);
1434
+ }
1435
+ `
1436
+ );
1437
+ var STATE_UNIFORMS = (
1438
+ /* glsl */
1439
+ `
1440
+ uniform float wIdle;
1441
+ uniform float wListen;
1442
+ uniform float wThink;
1443
+ uniform float wSpeak;
1444
+ uniform float uTime;
1445
+ uniform float uFreq;
1446
+ uniform float uDistortBase;
1447
+ uniform float uLevel; // 0..1 external audio level
1448
+ uniform vec3 uMouseDir;
1449
+ uniform float uMouseStrength;
1450
+ `
1451
+ );
1452
+ var WIRE_VERT = (
1453
+ /* glsl */
1454
+ `
1455
+ ${NOISE_GLSL}
1456
+ ${STATE_UNIFORMS}
1457
+ varying float vDist;
1458
+ varying float vGlow;
1459
+ void main(){
1460
+ vec3 p = position;
1461
+ vec3 nrm = normalize(p);
1462
+ float t = uTime * 0.55;
1463
+ float n = snoise(p * uFreq + vec3(0.0, t, 0.0)) * 0.6
1464
+ + snoise(p * uFreq * 2.1 + vec3(t*0.7, 0.0, t)) * 0.4;
1465
+
1466
+ float idleD = 0.08 * sin(uTime * 1.1) + n * 0.10;
1467
+ float lat = nrm.y;
1468
+ float listenD = 0.05 + (0.10 + uLevel * 0.30) * sin(uTime * 2.8 - lat * 4.0) + n * 0.12;
1469
+ float hh = hash13(floor(p * 1.6));
1470
+ float gph = fract(hh + uTime * 0.30);
1471
+ float glitch = smoothstep(0.55, 0.85, gph) * smoothstep(1.00, 0.85, gph) * 0.04;
1472
+ float thinkD = n * 0.09 + glitch;
1473
+ // speaking: rhythmic radial heartbeat. Baseline matches the gallery
1474
+ // sample (beat * 0.14); uLevel adds a small audio-reactive lift but
1475
+ // capped low to avoid the orb ballooning past the viewport.
1476
+ float beat = pow(0.5 + 0.5 * sin(uTime * 5.5), 5.0);
1477
+ float speakD = beat * (0.14 + uLevel * 0.10) + n * 0.14;
1478
+
1479
+ float d = uDistortBase
1480
+ + idleD * wIdle
1481
+ + listenD * wListen
1482
+ + thinkD * wThink
1483
+ + speakD * wSpeak;
1484
+
1485
+ vec3 tang = normalize(cross(nrm, vec3(0.0, 1.0, 0.0001)));
1486
+ vec3 streak = tang * (wSpeak * 0.08 * sin(uTime * 4.0 + n * 3.0));
1487
+
1488
+ float mDot = clamp(dot(nrm, uMouseDir), -1.0, 1.0);
1489
+ float mFall = pow(max(mDot, 0.0), 6.0);
1490
+ float mouseBump = uMouseStrength * mFall * 0.35;
1491
+ d += mouseBump;
1492
+
1493
+ vec3 np = p + nrm * d + streak;
1494
+
1495
+ vDist = d;
1496
+ vGlow = wThink * glitch * 0.5 + wSpeak * beat * 0.5 + wListen * 0.2
1497
+ + uMouseStrength * mFall * 0.6;
1498
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(np, 1.0);
1499
+ }
1500
+ `
1501
+ );
1502
+ var WIRE_FRAG = (
1503
+ /* glsl */
1504
+ `
1505
+ uniform vec3 uColor;
1506
+ uniform float uIntensity;
1507
+ varying float vDist;
1508
+ varying float vGlow;
1509
+ void main(){
1510
+ float k = 0.45 + 0.25 * (vDist + 0.5);
1511
+ vec3 col = uColor * k * uIntensity;
1512
+ gl_FragColor = vec4(min(col, vec3(0.85)), 1.0);
1513
+ }
1514
+ `
1515
+ );
1516
+ var DUST_VERT = (
1517
+ /* glsl */
1518
+ `
1519
+ ${NOISE_GLSL}
1520
+ ${STATE_UNIFORMS}
1521
+ uniform float uResHeight;
1522
+ attribute float aSize;
1523
+ attribute float aOffset;
1524
+ attribute float aPhase;
1525
+ varying float vAlpha;
1526
+ varying float vBoost;
1527
+
1528
+ mat3 rotY(float a){ return mat3(cos(a),0.,-sin(a), 0.,1.,0., sin(a),0.,cos(a)); }
1529
+
1530
+ void main(){
1531
+ vec3 p = position;
1532
+ vec3 nrm = normalize(p);
1533
+ float t = uTime * 0.55;
1534
+ float n = snoise(p * uFreq + vec3(0.0, t, 0.0)) * 0.6
1535
+ + snoise(p * uFreq * 2.1 + vec3(t*0.7, 0.0, t)) * 0.4;
1536
+ float d = uDistortBase + n * 0.12;
1537
+
1538
+ float idleR = 0.05 + 0.55 * aOffset * (0.6 + 0.4 * sin(uTime * 0.6 + aPhase * 6.28));
1539
+ float pull = mix(1.0, 0.05, aOffset);
1540
+ float sonar = 0.12 * sin(uTime * 3.5 - aOffset * 8.0);
1541
+ float listenR = 0.02 + pull * 0.08 + sonar * aOffset;
1542
+
1543
+ float angle = uTime * (0.8 + aPhase * 2.5);
1544
+ vec3 pSpiral = rotY(angle) * p;
1545
+ float thinkR = 0.18 * aOffset + 0.08 * sin(uTime * 1.6 + aPhase * 6.28);
1546
+
1547
+ // speaking: heartbeat radial BURST outward. Sample baseline is
1548
+ // aOffset * (0.25 + 0.40 * beat); we keep that and only let uLevel
1549
+ // add a gentle extra burst so loud audio doesn't blow the dust shell
1550
+ // way past the wireframe.
1551
+ float beat = pow(0.5 + 0.5 * sin(uTime * 5.5), 4.0);
1552
+ float speakR = aOffset * (0.25 + 0.40 * beat + uLevel * 0.20);
1553
+
1554
+ float radial = idleR * wIdle
1555
+ + listenR * wListen
1556
+ + thinkR * wThink
1557
+ + speakR * wSpeak;
1558
+
1559
+ vec3 pBase = mix(p, pSpiral, wThink);
1560
+ vec3 nrmB = normalize(pBase);
1561
+
1562
+ float mDotD = clamp(dot(nrmB, uMouseDir), -1.0, 1.0);
1563
+ float mFallD = pow(max(mDotD, 0.0), 4.0);
1564
+ float mouseAttract = uMouseStrength * mFallD * aOffset * 0.55;
1565
+ float sparkle = uMouseStrength * pow(max(mDotD, 0.0), 24.0) * 0.4;
1566
+
1567
+ vec3 np = pBase + nrmB * (d + radial - mouseAttract + sparkle);
1568
+
1569
+ // Dust point-size boost. Sample uses wSpeak * beat * 1.0; we add a
1570
+ // small uLevel contribution for liveliness but clamp it well below
1571
+ // the radial burst so loud audio doesn't make every dust point huge.
1572
+ float boost = 1.0
1573
+ + wSpeak * (beat + uLevel * 0.4) * 1.0
1574
+ + wListen * max(0.0, sonar) * 1.5
1575
+ + wThink * step(0.9, fract(aPhase + uTime * 0.3)) * 1.2
1576
+ + uMouseStrength * mFallD * 2.5;
1577
+
1578
+ vec4 mv = modelViewMatrix * vec4(np, 1.0);
1579
+ gl_Position = projectionMatrix * mv;
1580
+ // Point size is normalised by canvas height (uResHeight) against a 680px
1581
+ // reference (the orb max CSS size) and then hard-clamped. Without the
1582
+ // normalisation the raw 140.0 / -mv.z term yields a fixed pixel size
1583
+ // regardless of resolution, so on large / high-DPI canvases the additive
1584
+ // dust points overlap far more per output pixel and bloom into a blown-out
1585
+ // glare. Normalising + clamping keeps the dust coverage \u2014 and therefore the
1586
+ // additive brightness \u2014 visually constant on every screen. This is the only
1587
+ // change needed for the large-screen blow-out; density/alpha stay original.
1588
+ float sizeScale = uResHeight / 680.0;
1589
+ float ps = aSize * boost * (140.0 / -mv.z) * sizeScale;
1590
+ gl_PointSize = clamp(ps, 1.0, 12.0);
1591
+
1592
+ vAlpha = 1.0 - aOffset * 0.5;
1593
+ vBoost = boost;
1594
+ }
1595
+ `
1596
+ );
1597
+ var DUST_FRAG = (
1598
+ /* glsl */
1599
+ `
1600
+ uniform vec3 uColor;
1601
+ uniform float uIntensity;
1602
+ varying float vAlpha;
1603
+ varying float vBoost;
1604
+ void main(){
1605
+ vec2 c = gl_PointCoord - 0.5;
1606
+ float d = length(c);
1607
+ float a = pow(smoothstep(0.5, 0.0, d), 1.6);
1608
+ vec3 col = uColor * uIntensity * 0.55;
1609
+ gl_FragColor = vec4(col, a * vAlpha * 0.7);
1610
+ }
1611
+ `
1612
+ );
1613
+ var COLOR_MONO = [0.92, 0.95, 1];
1614
+ var COLOR_LISTEN = [0.35, 1, 0.6];
1615
+ var COLOR_SPEAK = [0.2, 0.55, 1];
1616
+ var COLOR_THINK = [1, 0.75, 0.2];
1617
+ var mapState = (s) => {
1618
+ if (s === "connecting") return "idle";
1619
+ return s;
1620
+ };
1621
+ var WireOrbEffect = (props) => {
1622
+ const { state, levelRef, mouseEnabled = false } = props;
1623
+ const mountRef = useRef(null);
1624
+ const stateRef = useRef(state);
1625
+ stateRef.current = state;
1626
+ const mouseEnabledRef = useRef(mouseEnabled);
1627
+ mouseEnabledRef.current = mouseEnabled;
1628
+ const externalLevelRef = levelRef;
1629
+ useEffect(() => {
1630
+ const mount = mountRef.current;
1631
+ if (!mount) return;
1632
+ const W = mount.clientWidth || 320;
1633
+ const H = mount.clientHeight || 320;
1634
+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
1635
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
1636
+ renderer.setSize(W, H);
1637
+ renderer.setClearColor(0, 0);
1638
+ mount.appendChild(renderer.domElement);
1639
+ const scene = new THREE.Scene();
1640
+ const cam = new THREE.PerspectiveCamera(45, W / H, 0.1, 100);
1641
+ cam.position.set(0, 0, 5);
1642
+ const sphereGeo = new THREE.IcosahedronGeometry(1, 12);
1643
+ const wireGeo = new THREE.WireframeGeometry(sphereGeo);
1644
+ const sharedUniforms = {
1645
+ wIdle: { value: 1 },
1646
+ wListen: { value: 0 },
1647
+ wThink: { value: 0 },
1648
+ wSpeak: { value: 0 },
1649
+ uTime: { value: 0 },
1650
+ uFreq: { value: 1.6 },
1651
+ uDistortBase: { value: 0.08 },
1652
+ uLevel: { value: 0 },
1653
+ uMouseDir: { value: new THREE.Vector3(0, 0, 1) },
1654
+ uMouseStrength: { value: 0 }
1655
+ };
1656
+ const wireMat = new THREE.ShaderMaterial({
1657
+ vertexShader: WIRE_VERT,
1658
+ fragmentShader: WIRE_FRAG,
1659
+ uniforms: {
1660
+ ...sharedUniforms,
1661
+ uColor: { value: new THREE.Color().fromArray(COLOR_MONO) },
1662
+ uIntensity: { value: 0.7 }
1663
+ },
1664
+ transparent: true
1665
+ });
1666
+ const wire = new THREE.LineSegments(wireGeo, wireMat);
1667
+ scene.add(wire);
1668
+ const COUNT = 4500;
1669
+ const positions = new Float32Array(COUNT * 3);
1670
+ const sizes = new Float32Array(COUNT);
1671
+ const offsets = new Float32Array(COUNT);
1672
+ const phases = new Float32Array(COUNT);
1673
+ for (let i = 0; i < COUNT; i++) {
1674
+ const th = Math.acos(2 * Math.random() - 1);
1675
+ const ph = Math.random() * Math.PI * 2;
1676
+ positions[i * 3 + 0] = Math.sin(th) * Math.cos(ph);
1677
+ positions[i * 3 + 1] = Math.cos(th);
1678
+ positions[i * 3 + 2] = Math.sin(th) * Math.sin(ph);
1679
+ sizes[i] = 0.35 + Math.random() * 0.9;
1680
+ offsets[i] = Math.random() < 0.3 ? Math.random() * 0.08 : 0.1 + Math.random() * 0.95;
1681
+ phases[i] = Math.random();
1682
+ }
1683
+ const dustGeo = new THREE.BufferGeometry();
1684
+ dustGeo.setAttribute("position", new THREE.BufferAttribute(positions, 3));
1685
+ dustGeo.setAttribute("aSize", new THREE.BufferAttribute(sizes, 1));
1686
+ dustGeo.setAttribute("aOffset", new THREE.BufferAttribute(offsets, 1));
1687
+ dustGeo.setAttribute("aPhase", new THREE.BufferAttribute(phases, 1));
1688
+ const dustUniforms = {
1689
+ wIdle: sharedUniforms.wIdle,
1690
+ wListen: sharedUniforms.wListen,
1691
+ wThink: sharedUniforms.wThink,
1692
+ wSpeak: sharedUniforms.wSpeak,
1693
+ uTime: sharedUniforms.uTime,
1694
+ uFreq: sharedUniforms.uFreq,
1695
+ uDistortBase: sharedUniforms.uDistortBase,
1696
+ uLevel: sharedUniforms.uLevel,
1697
+ uMouseDir: sharedUniforms.uMouseDir,
1698
+ uMouseStrength: sharedUniforms.uMouseStrength,
1699
+ uColor: { value: new THREE.Color().fromArray(COLOR_MONO) },
1700
+ uIntensity: { value: 0.65 },
1701
+ uResHeight: { value: H }
1702
+ };
1703
+ const dustMat = new THREE.ShaderMaterial({
1704
+ vertexShader: DUST_VERT,
1705
+ fragmentShader: DUST_FRAG,
1706
+ uniforms: dustUniforms,
1707
+ transparent: true,
1708
+ depthWrite: false,
1709
+ blending: THREE.AdditiveBlending
1710
+ });
1711
+ const dust = new THREE.Points(dustGeo, dustMat);
1712
+ scene.add(dust);
1713
+ const clock = new THREE.Clock();
1714
+ let raf = 0;
1715
+ const lerp = (a, b, t) => a + (b - a) * t;
1716
+ const lerpCol = (c, t, k) => {
1717
+ c.r = lerp(c.r, t[0], k);
1718
+ c.g = lerp(c.g, t[1], k);
1719
+ c.b = lerp(c.b, t[2], k);
1720
+ };
1721
+ const ndc = new THREE.Vector2(0, 0);
1722
+ const ndcSmooth = new THREE.Vector2(0, 0);
1723
+ let mouseInside = false;
1724
+ const raycaster = new THREE.Raycaster();
1725
+ const sphereForHit = new THREE.Sphere(new THREE.Vector3(0, 0, 0), 1);
1726
+ const tmpHit = new THREE.Vector3();
1727
+ const mouseDirTarget = new THREE.Vector3(0, 0, 1);
1728
+ const onMouseMove = (e) => {
1729
+ const rect = renderer.domElement.getBoundingClientRect();
1730
+ ndc.x = (e.clientX - rect.left) / rect.width * 2 - 1;
1731
+ ndc.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
1732
+ mouseInside = true;
1733
+ };
1734
+ const onMouseLeave = () => {
1735
+ mouseInside = false;
1736
+ };
1737
+ renderer.domElement.addEventListener("mousemove", onMouseMove);
1738
+ renderer.domElement.addEventListener("mouseleave", onMouseLeave);
1739
+ function tick() {
1740
+ const dt = clock.getDelta();
1741
+ const t = clock.getElapsedTime();
1742
+ sharedUniforms.uTime.value = t;
1743
+ const s = mapState(stateRef.current);
1744
+ const tgI = s === "idle" || s === "listening" ? 1 : 0;
1745
+ const tgL = 0;
1746
+ const tgT = s === "thinking" ? 1 : 0;
1747
+ const tgS = s === "speaking" ? 1 : 0;
1748
+ const k = Math.min(dt * 3, 1);
1749
+ sharedUniforms.wIdle.value = lerp(sharedUniforms.wIdle.value, tgI, k);
1750
+ sharedUniforms.wListen.value = lerp(sharedUniforms.wListen.value, tgL, k);
1751
+ sharedUniforms.wThink.value = lerp(sharedUniforms.wThink.value, tgT, k);
1752
+ sharedUniforms.wSpeak.value = lerp(sharedUniforms.wSpeak.value, tgS, k);
1753
+ const tgFreq = s === "thinking" ? 1.5 : s === "speaking" ? 1.8 : 1.5;
1754
+ sharedUniforms.uFreq.value = lerp(sharedUniforms.uFreq.value, tgFreq, k);
1755
+ const rawLvl = externalLevelRef ? Math.max(0, Math.min(1, externalLevelRef.current || 0)) : 0;
1756
+ sharedUniforms.uLevel.value = lerp(
1757
+ sharedUniforms.uLevel.value,
1758
+ rawLvl,
1759
+ Math.min(dt * 8, 1)
1760
+ );
1761
+ const tgColor = s === "listening" ? COLOR_LISTEN : s === "speaking" ? COLOR_SPEAK : s === "thinking" ? COLOR_THINK : COLOR_MONO;
1762
+ lerpCol(wireMat.uniforms.uColor.value, tgColor, k);
1763
+ lerpCol(dustUniforms.uColor.value, tgColor, k);
1764
+ const tgIntWire = s === "speaking" ? 0.78 : 0.7;
1765
+ const tgIntDust = s === "speaking" ? 0.72 : 0.65;
1766
+ wireMat.uniforms.uIntensity.value = lerp(
1767
+ wireMat.uniforms.uIntensity.value,
1768
+ tgIntWire,
1769
+ k
1770
+ );
1771
+ dustUniforms.uIntensity.value = lerp(
1772
+ dustUniforms.uIntensity.value,
1773
+ tgIntDust,
1774
+ k
1775
+ );
1776
+ const mk = Math.min(dt * 6, 1);
1777
+ ndcSmooth.x = lerp(ndcSmooth.x, ndc.x, mk);
1778
+ ndcSmooth.y = lerp(ndcSmooth.y, ndc.y, mk);
1779
+ const wantMouse = mouseEnabledRef.current && mouseInside ? 1 : 0;
1780
+ sharedUniforms.uMouseStrength.value = lerp(
1781
+ sharedUniforms.uMouseStrength.value,
1782
+ wantMouse,
1783
+ Math.min(dt * 4, 1)
1784
+ );
1785
+ if (mouseEnabledRef.current) {
1786
+ raycaster.setFromCamera(ndcSmooth, cam);
1787
+ const hit = raycaster.ray.intersectSphere(sphereForHit, tmpHit);
1788
+ if (hit) {
1789
+ mouseDirTarget.copy(hit).normalize();
1790
+ } else {
1791
+ raycaster.ray.at(4, tmpHit);
1792
+ mouseDirTarget.copy(tmpHit).normalize();
1793
+ }
1794
+ const inv = new THREE.Matrix4().copy(wire.matrixWorld).invert();
1795
+ const localDir = mouseDirTarget.clone().applyMatrix4(inv).normalize();
1796
+ const cur = sharedUniforms.uMouseDir.value;
1797
+ cur.lerp(localDir, Math.min(dt * 5, 1)).normalize();
1798
+ }
1799
+ const tgZ = s === "listening" ? 4.2 : s === "speaking" ? 4.6 : 5;
1800
+ cam.position.z = lerp(cam.position.z, tgZ, dt * 1.5);
1801
+ const shake = s === "speaking" ? Math.sin(t * 30) * 0.025 : 0;
1802
+ const ms = sharedUniforms.uMouseStrength.value;
1803
+ const targetX = shake + ndcSmooth.x * 0.35 * ms;
1804
+ const targetY = (s === "speaking" ? Math.cos(t * 28) * 0.02 : 0) + ndcSmooth.y * 0.25 * ms;
1805
+ cam.position.x = lerp(cam.position.x, targetX, 0.4);
1806
+ cam.position.y = lerp(cam.position.y, targetY, 0.4);
1807
+ cam.lookAt(0, 0, 0);
1808
+ const rotSpeed = s === "thinking" ? 0.6 : s === "speaking" ? 0.35 : s === "listening" ? 0.12 : 0.18;
1809
+ wire.rotation.y += dt * rotSpeed;
1810
+ const tiltY = ndcSmooth.x * 0.35 * ms;
1811
+ const tiltX = -ndcSmooth.y * 0.25 * ms + Math.sin(t * 0.3) * (s === "thinking" ? 0.25 : 0.1);
1812
+ wire.rotation.x = lerp(wire.rotation.x, tiltX, 0.2);
1813
+ wire.rotation.z = lerp(wire.rotation.z, tiltY, 0.2);
1814
+ wire.updateMatrixWorld(true);
1815
+ dust.rotation.copy(wire.rotation);
1816
+ renderer.render(scene, cam);
1817
+ raf = requestAnimationFrame(tick);
1818
+ }
1819
+ tick();
1820
+ const onResize = () => {
1821
+ const Wn = mount.clientWidth || W;
1822
+ const Hn = mount.clientHeight || H;
1823
+ renderer.setSize(Wn, Hn);
1824
+ cam.aspect = Wn / Hn;
1825
+ cam.updateProjectionMatrix();
1826
+ dustUniforms.uResHeight.value = Hn;
1827
+ };
1828
+ window.addEventListener("resize", onResize);
1829
+ const ro = new ResizeObserver(onResize);
1830
+ ro.observe(mount);
1831
+ return () => {
1832
+ cancelAnimationFrame(raf);
1833
+ window.removeEventListener("resize", onResize);
1834
+ ro.disconnect();
1835
+ renderer.domElement.removeEventListener("mousemove", onMouseMove);
1836
+ renderer.domElement.removeEventListener("mouseleave", onMouseLeave);
1837
+ renderer.dispose();
1838
+ sphereGeo.dispose();
1839
+ wireGeo.dispose();
1840
+ wireMat.dispose();
1841
+ dustGeo.dispose();
1842
+ dustMat.dispose();
1843
+ if (renderer.domElement.parentElement === mount) {
1844
+ mount.removeChild(renderer.domElement);
1845
+ }
1846
+ };
1847
+ }, []);
1848
+ return /* @__PURE__ */ jsx("div", { ref: mountRef, className: "wire-orb-effect" });
1849
+ };
1850
+ var Hero = (props) => /* @__PURE__ */ jsxs("div", { className: "hero", children: [
1851
+ /* @__PURE__ */ jsx("div", { className: "hero-orb", "aria-hidden": "true", children: /* @__PURE__ */ jsx(WireOrbEffect, { state: "idle" }) }),
1852
+ /* @__PURE__ */ jsx("h2", { className: "hero-title", children: props.title ?? "Good to see you." }),
1853
+ /* @__PURE__ */ jsx("p", { className: "hero-sub", children: props.subtitle ?? "Ask me anything." })
1854
+ ] });
1855
+ var renderNode = (node, toolRenderers) => {
1856
+ if (node.kind === "user") return /* @__PURE__ */ jsx(UserMessage, { content: node.content, images: node.images });
1857
+ if (node.kind === "assistant") return /* @__PURE__ */ jsx(AssistantMessage, { content: node.content });
1858
+ if (node.kind === "tool-call") {
1859
+ const label = friendlyToolLabel(node.name);
1860
+ let rawArgs;
1861
+ try {
1862
+ rawArgs = JSON.stringify(node.input ?? {}, null, 2);
1863
+ } catch {
1864
+ rawArgs = "(unserialisable)";
1865
+ }
1866
+ return /* @__PURE__ */ jsxs("div", { className: "msg tool-pending", children: [
1867
+ /* @__PURE__ */ jsx("span", { className: "tool-pending-icon", "aria-hidden": "true", children: label.icon }),
1868
+ /* @__PURE__ */ jsxs("span", { className: "tool-pending-text", children: [
1869
+ label.verb,
1870
+ "\u2026"
1871
+ ] }),
1872
+ /* @__PURE__ */ jsxs("span", { className: "tool-pending-dots", "aria-hidden": "true", children: [
1873
+ /* @__PURE__ */ jsx("span", {}),
1874
+ /* @__PURE__ */ jsx("span", {}),
1875
+ /* @__PURE__ */ jsx("span", {})
1876
+ ] }),
1877
+ /* @__PURE__ */ jsxs("details", { className: "tool-pending-details", children: [
1878
+ /* @__PURE__ */ jsx("summary", { children: "chi ti\u1EBFt" }),
1879
+ /* @__PURE__ */ jsx("pre", { children: rawArgs })
1880
+ ] })
1881
+ ] });
1882
+ }
1883
+ if (node.kind === "tool-result") {
1884
+ return /* @__PURE__ */ jsx(
1885
+ ToolMessage,
1886
+ {
1887
+ toolName: node.name,
1888
+ result: node.result,
1889
+ raw: node.raw,
1890
+ toolRenderers
1891
+ }
1892
+ );
1893
+ }
1894
+ if (node.kind === "tool-error") {
1895
+ return /* @__PURE__ */ jsx(ErrorMessage, { label: "tool-error", message: node.name + ": " + node.message });
1896
+ }
1897
+ if (node.kind === "error") return /* @__PURE__ */ jsx(ErrorMessage, { message: node.message });
1898
+ if (node.kind === "condense") return /* @__PURE__ */ jsx(CondensePill, { state: node.state });
1899
+ return null;
1900
+ };
1901
+ var ThinkingPill = () => /* @__PURE__ */ jsxs("span", { className: "tool-pending thinking-pill", "data-testid": "tinyweb-thinking", children: [
1902
+ /* @__PURE__ */ jsx("span", { className: "tool-pending-icon", "aria-hidden": "true", children: "\u{1F4AD}" }),
1903
+ /* @__PURE__ */ jsx("span", { className: "tool-pending-text", children: "\u0110ang suy ngh\u0129" }),
1904
+ /* @__PURE__ */ jsxs("span", { className: "tool-pending-dots", "aria-hidden": "true", children: [
1905
+ /* @__PURE__ */ jsx("span", {}),
1906
+ /* @__PURE__ */ jsx("span", {}),
1907
+ /* @__PURE__ */ jsx("span", {})
1908
+ ] })
1909
+ ] });
1910
+ var shouldShowThinking = (status, nodes) => {
1911
+ if (status !== "requesting" && status !== "streaming") return false;
1912
+ const last = nodes[nodes.length - 1];
1913
+ if (!last) return false;
1914
+ if (last.kind === "user") return true;
1915
+ if (last.kind === "tool-result") return true;
1916
+ return false;
1917
+ };
1918
+ var latestUserTailId = (nodes) => {
1919
+ const last = nodes[nodes.length - 1];
1920
+ if (!last) return null;
1921
+ if (last.kind === "user") return last.id;
1922
+ return null;
1923
+ };
1924
+ var Transcript = (props) => {
1925
+ const ref = useRef(null);
1926
+ const spacerRef = useRef(null);
1927
+ useInitialScrollToEnd(ref, props.nodes.length > 0);
1928
+ useAnchorLatestUser(ref, spacerRef, latestUserTailId(props.nodes));
1929
+ const empty = props.nodes.length === 0;
1930
+ const showHero = empty && props.hero !== null;
1931
+ const showThinking = shouldShowThinking(props.status, props.nodes);
1932
+ return /* @__PURE__ */ jsxs("div", { className: "messages", ref, "data-testid": "tinyweb-transcript", children: [
1933
+ showHero ? /* @__PURE__ */ jsx(Hero, { title: props.hero?.title, subtitle: props.hero?.subtitle }) : null,
1934
+ /* @__PURE__ */ jsxs("div", { className: "messages-inner", children: [
1935
+ props.nodes.map((node) => /* @__PURE__ */ jsx("div", { className: "msg-row", "data-msg-id": node.id, children: renderNode(node, props.toolRenderers) }, node.id)),
1936
+ showThinking ? /* @__PURE__ */ jsx(ThinkingPill, {}) : null,
1937
+ /* @__PURE__ */ jsx("div", { ref: spacerRef, className: "msg-spacer", "aria-hidden": "true" })
1938
+ ] })
1939
+ ] });
1940
+ };
1941
+ var DEFAULT_HERO = "How can I help you today?";
1942
+ var KeyboardIcon = () => /* @__PURE__ */ jsxs(
1943
+ "svg",
1944
+ {
1945
+ viewBox: "0 0 24 24",
1946
+ width: "22",
1947
+ height: "22",
1948
+ fill: "none",
1949
+ stroke: "currentColor",
1950
+ strokeWidth: "1.6",
1951
+ strokeLinecap: "round",
1952
+ strokeLinejoin: "round",
1953
+ "aria-hidden": "true",
1954
+ children: [
1955
+ /* @__PURE__ */ jsx("rect", { x: "2.5", y: "6", width: "19", height: "12", rx: "2" }),
1956
+ /* @__PURE__ */ jsx("path", { d: "M6.5 10h.01M10 10h.01M13.5 10h.01M17 10h.01M6.5 14h11" })
1957
+ ]
1958
+ }
1959
+ );
1960
+ var MicIcon = () => /* @__PURE__ */ jsxs(
1961
+ "svg",
1962
+ {
1963
+ viewBox: "0 0 24 24",
1964
+ width: "26",
1965
+ height: "26",
1966
+ fill: "none",
1967
+ stroke: "currentColor",
1968
+ strokeWidth: "1.8",
1969
+ strokeLinecap: "round",
1970
+ strokeLinejoin: "round",
1971
+ "aria-hidden": "true",
1972
+ children: [
1973
+ /* @__PURE__ */ jsx("rect", { x: "9", y: "3", width: "6", height: "12", rx: "3" }),
1974
+ /* @__PURE__ */ jsx("path", { d: "M5 11a7 7 0 0 0 14 0" }),
1975
+ /* @__PURE__ */ jsx("path", { d: "M12 18v3" })
1976
+ ]
1977
+ }
1978
+ );
1979
+ var MicOffIcon = () => /* @__PURE__ */ jsxs(
1980
+ "svg",
1981
+ {
1982
+ viewBox: "0 0 24 24",
1983
+ width: "26",
1984
+ height: "26",
1985
+ fill: "none",
1986
+ stroke: "currentColor",
1987
+ strokeWidth: "1.8",
1988
+ strokeLinecap: "round",
1989
+ strokeLinejoin: "round",
1990
+ "aria-hidden": "true",
1991
+ children: [
1992
+ /* @__PURE__ */ jsx("path", { d: "M3 3l18 18" }),
1993
+ /* @__PURE__ */ jsx("path", { d: "M9 9v3a3 3 0 0 0 5.12 2.12" }),
1994
+ /* @__PURE__ */ jsx("path", { d: "M15 11.34V6a3 3 0 0 0-6-.34" }),
1995
+ /* @__PURE__ */ jsx("path", { d: "M5 11a7 7 0 0 0 11.27 5.5" }),
1996
+ /* @__PURE__ */ jsx("path", { d: "M19 11a7 7 0 0 0-.18-1.59" }),
1997
+ /* @__PURE__ */ jsx("path", { d: "M12 18v3" })
1998
+ ]
1999
+ }
2000
+ );
2001
+ var BugIcon = () => /* @__PURE__ */ jsxs(
2002
+ "svg",
2003
+ {
2004
+ viewBox: "0 0 24 24",
2005
+ width: "18",
2006
+ height: "18",
2007
+ fill: "none",
2008
+ stroke: "currentColor",
2009
+ strokeWidth: "1.7",
2010
+ strokeLinecap: "round",
2011
+ strokeLinejoin: "round",
2012
+ "aria-hidden": "true",
2013
+ children: [
2014
+ /* @__PURE__ */ jsx("path", { d: "M8 6a4 4 0 1 1 8 0" }),
2015
+ /* @__PURE__ */ jsx("rect", { x: "6", y: "8", width: "12", height: "11", rx: "5" }),
2016
+ /* @__PURE__ */ jsx("path", { d: "M12 19v-9M4 12h3M17 12h3M5 7l2 1M19 7l-2 1M5 17l2-1M19 17l-2-1" })
2017
+ ]
2018
+ }
2019
+ );
2020
+ var ChevronUpIcon = () => /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("polyline", { points: "6 15 12 9 18 15" }) });
2021
+ var ChevronDownIcon = () => /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("polyline", { points: "6 9 12 15 18 9" }) });
2022
+ var CloseIcon = () => /* @__PURE__ */ jsx(
2023
+ "svg",
2024
+ {
2025
+ viewBox: "0 0 24 24",
2026
+ width: "22",
2027
+ height: "22",
2028
+ fill: "none",
2029
+ stroke: "currentColor",
2030
+ strokeWidth: "1.8",
2031
+ strokeLinecap: "round",
2032
+ strokeLinejoin: "round",
2033
+ "aria-hidden": "true",
2034
+ children: /* @__PURE__ */ jsx("path", { d: "M6 6l12 12M18 6L6 18" })
2035
+ }
2036
+ );
2037
+ var resolveStatusLabel = (status, subState, overrides) => {
2038
+ if (status === "active" && subState !== null) {
2039
+ const richKey = subState === "listening" ? "active-listening" : subState === "speaking" ? "active-speaking" : "active-muted";
2040
+ const rich = overrides?.[richKey];
2041
+ if (rich) return rich;
2042
+ const bucket = overrides?.active;
2043
+ if (bucket) return bucket;
2044
+ if (subState === "listening") return "I'm listening";
2045
+ if (subState === "speaking") return "Speaking\u2026";
2046
+ return "Muted";
2047
+ }
2048
+ const override = overrides?.[status];
2049
+ if (override) return override;
2050
+ if (status === "connecting") return "Connecting\u2026";
2051
+ if (status === "ending") return "Ending\u2026";
2052
+ if (status === "error") return "Error";
2053
+ if (status === "active") return "Connected";
2054
+ return "Idle";
2055
+ };
2056
+ var MAX_RECENT_TURNS = 5;
2057
+ var buildRecentTurns = (nodes) => {
2058
+ if (!nodes || nodes.length === 0) return [];
2059
+ const turns = [];
2060
+ let pendingAssistant = null;
2061
+ let pendingTool = null;
2062
+ for (let i = nodes.length - 1; i >= 0; i--) {
2063
+ const n = nodes[i];
2064
+ if (n.kind === "tool-call" && !pendingTool) {
2065
+ pendingTool = { name: n.name, args: n.input ?? {} };
2066
+ continue;
2067
+ }
2068
+ if (n.kind === "assistant") {
2069
+ pendingAssistant = n.content;
2070
+ continue;
2071
+ }
2072
+ if (n.kind === "user") {
2073
+ turns.unshift({
2074
+ key: n.id,
2075
+ user: n.content,
2076
+ assistant: pendingAssistant,
2077
+ tool: pendingTool,
2078
+ live: false
2079
+ });
2080
+ pendingAssistant = null;
2081
+ pendingTool = null;
2082
+ if (turns.length >= MAX_RECENT_TURNS) break;
2083
+ continue;
2084
+ }
2085
+ }
2086
+ if (pendingAssistant !== null && turns.length < MAX_RECENT_TURNS) {
2087
+ turns.unshift({
2088
+ key: `lead-${turns[0]?.key ?? "0"}`,
2089
+ user: null,
2090
+ assistant: pendingAssistant,
2091
+ tool: pendingTool,
2092
+ live: false
2093
+ });
2094
+ }
2095
+ return turns;
2096
+ };
2097
+ var RECENTS_EXPANDED_STORAGE_KEY = "tinyweb.realtime.recents.expanded";
2098
+ var RealtimeRecents = (props) => {
2099
+ const [expanded, setExpanded] = useState(() => {
2100
+ if (typeof window === "undefined") return false;
2101
+ try {
2102
+ const raw = window.localStorage.getItem(RECENTS_EXPANDED_STORAGE_KEY);
2103
+ if (raw === null) return false;
2104
+ return JSON.parse(raw) === true;
2105
+ } catch {
2106
+ return false;
2107
+ }
2108
+ });
2109
+ useEffect(() => {
2110
+ if (typeof window === "undefined") return;
2111
+ try {
2112
+ window.localStorage.setItem(
2113
+ RECENTS_EXPANDED_STORAGE_KEY,
2114
+ JSON.stringify(expanded)
2115
+ );
2116
+ } catch {
2117
+ }
2118
+ }, [expanded]);
2119
+ const turns = useMemo(() => buildRecentTurns(props.nodes), [props.nodes]);
2120
+ const liveUserNew = !!props.liveUser && !turns.some((t) => t.user && t.user === props.liveUser);
2121
+ const liveAgentNew = !!props.liveAgent && !turns.some((t) => t.assistant && t.assistant === props.liveAgent);
2122
+ const liveRow = liveUserNew || liveAgentNew ? {
2123
+ key: "__live__",
2124
+ user: liveUserNew ? props.liveUser : null,
2125
+ assistant: liveAgentNew ? props.liveAgent : null,
2126
+ tool: props.lastToolCall,
2127
+ live: true
2128
+ } : null;
2129
+ const rows = liveRow ? [...turns.slice(-4), liveRow] : turns;
2130
+ const latestRow = rows[rows.length - 1];
2131
+ const compactAgentLine = latestRow?.assistant ?? null;
2132
+ const compactUserLine = latestRow?.user ?? null;
2133
+ const compactTool = latestRow?.tool ?? null;
2134
+ const compactLive = latestRow?.live ?? false;
2135
+ const hasContent = rows.length > 0;
2136
+ const showError = Boolean(props.error);
2137
+ if (!hasContent && !showError && !expanded) return null;
2138
+ const toggleBtn = hasContent || expanded ? /* @__PURE__ */ jsx(
2139
+ "button",
2140
+ {
2141
+ type: "button",
2142
+ className: "realtime-recents-toggle",
2143
+ "aria-label": expanded ? "Collapse transcript" : "Expand transcript",
2144
+ "aria-expanded": expanded,
2145
+ title: expanded ? "Collapse" : "Expand to see recent turns",
2146
+ onClick: () => setExpanded((v) => !v),
2147
+ children: expanded ? /* @__PURE__ */ jsx(ChevronDownIcon, {}) : /* @__PURE__ */ jsx(ChevronUpIcon, {})
2148
+ }
2149
+ ) : null;
2150
+ return /* @__PURE__ */ jsxs(
2151
+ "div",
2152
+ {
2153
+ className: `realtime-recents${expanded ? " is-expanded" : " is-compact"}`,
2154
+ "aria-label": "Recent conversation",
2155
+ children: [
2156
+ toggleBtn,
2157
+ expanded ? /* @__PURE__ */ jsx("div", { className: "realtime-recents-list", children: rows.map((t) => /* @__PURE__ */ jsxs(
2158
+ "div",
2159
+ {
2160
+ className: `realtime-recent-turn${t.live ? " is-live" : ""}`,
2161
+ children: [
2162
+ t.user ? /* @__PURE__ */ jsx("div", { className: "realtime-recent-row realtime-recent-row--user", children: /* @__PURE__ */ jsx("span", { className: "realtime-recent-bubble realtime-recent-bubble--user", children: t.user }) }) : null,
2163
+ t.assistant ? /* @__PURE__ */ jsx("div", { className: "realtime-recent-row realtime-recent-row--agent", children: /* @__PURE__ */ jsx("span", { className: "realtime-recent-bubble realtime-recent-bubble--agent", children: t.assistant }) }) : null,
2164
+ t.tool ? /* @__PURE__ */ jsx("div", { className: "realtime-recent-row realtime-recent-row--agent", children: /* @__PURE__ */ jsxs(
2165
+ "span",
2166
+ {
2167
+ className: "realtime-recent-tool",
2168
+ title: JSON.stringify(t.tool.args),
2169
+ children: [
2170
+ /* @__PURE__ */ jsx("span", { className: "realtime-recent-tool-dot", "aria-hidden": "true" }),
2171
+ t.tool.name
2172
+ ]
2173
+ }
2174
+ ) }) : null
2175
+ ]
2176
+ },
2177
+ t.key
2178
+ )) }) : /* @__PURE__ */ jsxs("div", { className: `realtime-recents-compact${compactLive ? " is-live" : ""}`, children: [
2179
+ compactAgentLine ? /* @__PURE__ */ jsx("p", { className: "realtime-recents-compact-line realtime-recents-compact-line--agent", children: compactAgentLine }) : compactUserLine ? /* @__PURE__ */ jsx("p", { className: "realtime-recents-compact-line realtime-recents-compact-line--user", children: compactUserLine }) : null,
2180
+ compactTool ? /* @__PURE__ */ jsxs(
2181
+ "span",
2182
+ {
2183
+ className: "realtime-recent-tool",
2184
+ title: JSON.stringify(compactTool.args),
2185
+ children: [
2186
+ /* @__PURE__ */ jsx("span", { className: "realtime-recent-tool-dot", "aria-hidden": "true" }),
2187
+ compactTool.name
2188
+ ]
2189
+ }
2190
+ ) : null
2191
+ ] }),
2192
+ showError ? /* @__PURE__ */ jsx("div", { className: "realtime-recent-error", role: "alert", children: props.error }) : null
2193
+ ]
2194
+ }
2195
+ );
2196
+ };
2197
+ var RealtimeCallOverlay = (props) => {
2198
+ const chat = props.chat;
2199
+ const agentTurnRef = useRef("");
2200
+ const onUserTurnRef = useRef(props.onUserTurn);
2201
+ const onAssistantTurnRef = useRef(props.onAssistantTurn);
2202
+ onUserTurnRef.current = props.onUserTurn;
2203
+ onAssistantTurnRef.current = props.onAssistantTurn;
2204
+ const flushAssistantTurn = useCallback(() => {
2205
+ const text = agentTurnRef.current;
2206
+ agentTurnRef.current = "";
2207
+ if (!text) return;
2208
+ const cb = onAssistantTurnRef.current;
2209
+ if (!cb) return;
2210
+ try {
2211
+ const r = cb(text);
2212
+ if (r && typeof r.catch === "function") {
2213
+ ;
2214
+ r.catch(() => {
2215
+ });
2216
+ }
2217
+ } catch {
2218
+ }
2219
+ }, []);
2220
+ const fireUserTurn = useCallback((text) => {
2221
+ const trimmed = text.trim();
2222
+ if (!trimmed) return;
2223
+ const cb = onUserTurnRef.current;
2224
+ if (!cb) return;
2225
+ try {
2226
+ const r = cb(trimmed);
2227
+ if (r && typeof r.catch === "function") {
2228
+ ;
2229
+ r.catch(() => {
2230
+ });
2231
+ }
2232
+ } catch {
2233
+ }
2234
+ }, []);
2235
+ const onRealtimeEvent = useCallback(
2236
+ (event) => {
2237
+ switch (event.type) {
2238
+ case "user-transcript-final":
2239
+ if (event.text.trim()) {
2240
+ chat?.appendUserMessage(event.text);
2241
+ fireUserTurn(event.text);
2242
+ }
2243
+ return;
2244
+ case "agent-transcript-delta":
2245
+ if (agentTurnRef.current === "") {
2246
+ chat?.applyEvent({ type: "text-end" });
2247
+ }
2248
+ agentTurnRef.current += event.text;
2249
+ chat?.applyEvent({ type: "text-delta", text: event.text });
2250
+ return;
2251
+ case "agent-transcript-final":
2252
+ if (event.text && !agentTurnRef.current) {
2253
+ agentTurnRef.current = event.text;
2254
+ chat?.applyEvent({ type: "text-delta", text: event.text });
2255
+ }
2256
+ chat?.applyEvent({ type: "text-end" });
2257
+ flushAssistantTurn();
2258
+ return;
2259
+ case "turn-complete":
2260
+ chat?.applyEvent({ type: "text-end" });
2261
+ flushAssistantTurn();
2262
+ return;
2263
+ case "tool-call":
2264
+ chat?.applyEvent({
2265
+ type: "tool-call",
2266
+ id: event.id,
2267
+ name: event.name,
2268
+ input: event.args
2269
+ });
2270
+ return;
2271
+ case "tool-result":
2272
+ chat?.applyEvent({
2273
+ type: "tool-result",
2274
+ id: event.id,
2275
+ name: event.name,
2276
+ result: event.result
2277
+ });
2278
+ return;
2279
+ case "tool-error":
2280
+ chat?.applyEvent({
2281
+ type: "tool-error",
2282
+ id: event.id,
2283
+ name: event.name,
2284
+ message: event.message
2285
+ });
2286
+ return;
2287
+ default:
2288
+ return;
2289
+ }
2290
+ },
2291
+ [chat]
2292
+ );
2293
+ const chatNodesRef = useRef(void 0);
2294
+ chatNodesRef.current = chat?.nodes;
2295
+ const getInitialHistory = useCallback(() => {
2296
+ const nodes = chatNodesRef.current;
2297
+ if (!nodes || nodes.length === 0) return void 0;
2298
+ const turns = [];
2299
+ for (const n of nodes) {
2300
+ if (n.kind === "user" || n.kind === "assistant") {
2301
+ const raw = n.content;
2302
+ const text = typeof raw === "string" ? raw.trim() : String(raw ?? "").trim();
2303
+ if (!text) continue;
2304
+ turns.push({ role: n.kind === "user" ? "user" : "model", text });
2305
+ }
2306
+ }
2307
+ return turns.length > 0 ? turns : void 0;
2308
+ }, []);
2309
+ const call = useRealtimeCall({
2310
+ tokenEndpoint: props.tokenEndpoint,
2311
+ tokenHeaders: props.tokenHeaders,
2312
+ tokenBody: props.tokenBody,
2313
+ toolHandlers: props.toolHandlers,
2314
+ toolProxyPath: props.toolProxyPath,
2315
+ toolProxyHeaders: props.toolProxyHeaders,
2316
+ idleTimeoutMs: props.idleTimeoutMs,
2317
+ onEvent: onRealtimeEvent,
2318
+ initialHistory: getInitialHistory
2319
+ });
2320
+ const [debugOpen, setDebugOpen] = useState(false);
2321
+ useEffect(() => {
2322
+ void call.start();
2323
+ }, []);
2324
+ useEffect(() => {
2325
+ const onKey = async (e) => {
2326
+ if (e.key === "Escape") {
2327
+ await call.hangup();
2328
+ props.onClose();
2329
+ }
2330
+ };
2331
+ window.addEventListener("keydown", onKey);
2332
+ return () => window.removeEventListener("keydown", onKey);
2333
+ }, [call, props]);
2334
+ const handleHangup = async () => {
2335
+ await call.hangup();
2336
+ props.onClose();
2337
+ };
2338
+ const [agentSpeaking, setAgentSpeaking] = useState(false);
2339
+ useEffect(() => {
2340
+ const analyser = call.outputAnalyser;
2341
+ if (!analyser || call.status !== "active") {
2342
+ setAgentSpeaking(false);
2343
+ return;
2344
+ }
2345
+ const buf = new Uint8Array(analyser.frequencyBinCount);
2346
+ let raf = 0;
2347
+ let lastActiveAt = 0;
2348
+ const tick = () => {
2349
+ analyser.getByteFrequencyData(buf);
2350
+ const half = buf.length >> 1;
2351
+ let sum = 0;
2352
+ for (let i = 0; i < half; i++) sum += buf[i] ?? 0;
2353
+ const avg = sum / (half * 255);
2354
+ const now = performance.now();
2355
+ if (avg > 0.02) {
2356
+ lastActiveAt = now;
2357
+ setAgentSpeaking(true);
2358
+ } else if (now - lastActiveAt > 350) {
2359
+ setAgentSpeaking(false);
2360
+ }
2361
+ raf = requestAnimationFrame(tick);
2362
+ };
2363
+ raf = requestAnimationFrame(tick);
2364
+ return () => cancelAnimationFrame(raf);
2365
+ }, [call.outputAnalyser, call.status]);
2366
+ const orbState = call.status === "active" ? call.toolRunning ? "thinking" : call.muted ? "idle" : agentSpeaking ? "speaking" : "listening" : call.status === "connecting" ? "connecting" : "idle";
2367
+ const subState = call.status === "active" ? call.muted ? "muted" : agentSpeaking ? "speaking" : "listening" : null;
2368
+ const statusLabel = resolveStatusLabel(call.status, subState, props.statusLabels);
2369
+ const hero = props.hero === void 0 ? DEFAULT_HERO : props.hero;
2370
+ const rippleActive = call.status === "active" && !call.muted;
2371
+ const showDebug = Boolean(chat) && debugOpen;
2372
+ return /* @__PURE__ */ jsxs(
2373
+ "div",
2374
+ {
2375
+ className: `realtime-stage-wrap${showDebug ? " realtime-stage-wrap--debug" : ""}`,
2376
+ children: [
2377
+ /* @__PURE__ */ jsxs(
2378
+ "section",
2379
+ {
2380
+ className: "realtime-inline-panel realtime-inline-panel--wire",
2381
+ "aria-label": "Realtime call",
2382
+ children: [
2383
+ /* @__PURE__ */ jsx("div", { className: "realtime-orb-wrap realtime-orb-wrap--wire", children: /* @__PURE__ */ jsx(
2384
+ WireOrbEffect,
2385
+ {
2386
+ state: orbState,
2387
+ levelRef: call.levelRef,
2388
+ inputAnalyser: call.inputAnalyser,
2389
+ outputAnalyser: call.outputAnalyser
2390
+ }
2391
+ ) }),
2392
+ /* @__PURE__ */ jsx(
2393
+ "div",
2394
+ {
2395
+ className: `realtime-status realtime-status-${call.status}`,
2396
+ role: "status",
2397
+ "aria-live": "polite",
2398
+ children: statusLabel
2399
+ }
2400
+ ),
2401
+ /* @__PURE__ */ jsx("div", { className: "realtime-stage realtime-stage--wire", "aria-hidden": "true" }),
2402
+ hero ? /* @__PURE__ */ jsx("p", { className: "realtime-hero", children: hero }) : null,
2403
+ /* @__PURE__ */ jsx(
2404
+ RealtimeRecents,
2405
+ {
2406
+ nodes: chat?.nodes,
2407
+ liveUser: call.userTranscript,
2408
+ liveAgent: call.agentTranscript,
2409
+ lastToolCall: call.lastToolCall,
2410
+ error: call.error
2411
+ }
2412
+ ),
2413
+ /* @__PURE__ */ jsxs("footer", { className: "realtime-inline-footer", children: [
2414
+ /* @__PURE__ */ jsx(
2415
+ "button",
2416
+ {
2417
+ type: "button",
2418
+ className: "realtime-icon-btn",
2419
+ "aria-label": "Switch to text",
2420
+ title: "Switch to text",
2421
+ onClick: handleHangup,
2422
+ children: /* @__PURE__ */ jsx(KeyboardIcon, {})
2423
+ }
2424
+ ),
2425
+ /* @__PURE__ */ jsxs(
2426
+ "div",
2427
+ {
2428
+ className: "realtime-mic-stack",
2429
+ "data-active": rippleActive ? "true" : "false",
2430
+ children: [
2431
+ /* @__PURE__ */ jsx("span", { className: "realtime-mic-ripple realtime-mic-ripple--1", "aria-hidden": "true" }),
2432
+ /* @__PURE__ */ jsx("span", { className: "realtime-mic-ripple realtime-mic-ripple--2", "aria-hidden": "true" }),
2433
+ /* @__PURE__ */ jsx("span", { className: "realtime-mic-ripple realtime-mic-ripple--3", "aria-hidden": "true" }),
2434
+ /* @__PURE__ */ jsx(
2435
+ "button",
2436
+ {
2437
+ type: "button",
2438
+ className: "realtime-mic-fab",
2439
+ "aria-label": call.muted ? "Unmute microphone" : "Mute microphone",
2440
+ "aria-pressed": call.muted,
2441
+ title: call.muted ? "Unmute" : "Mute",
2442
+ onClick: () => call.setMuted(!call.muted),
2443
+ disabled: call.status !== "active",
2444
+ children: call.muted ? /* @__PURE__ */ jsx(MicOffIcon, {}) : /* @__PURE__ */ jsx(MicIcon, {})
2445
+ }
2446
+ )
2447
+ ]
2448
+ }
2449
+ ),
2450
+ /* @__PURE__ */ jsx(
2451
+ "button",
2452
+ {
2453
+ type: "button",
2454
+ className: "realtime-icon-btn realtime-icon-btn--close",
2455
+ "aria-label": "Hang up",
2456
+ title: "Hang up",
2457
+ onClick: handleHangup,
2458
+ children: /* @__PURE__ */ jsx(CloseIcon, {})
2459
+ }
2460
+ )
2461
+ ] }),
2462
+ chat ? /* @__PURE__ */ jsx(
2463
+ "button",
2464
+ {
2465
+ type: "button",
2466
+ className: `realtime-debug-toggle${showDebug ? " is-open" : ""}`,
2467
+ "aria-label": showDebug ? "Hide debug log" : "Show debug log",
2468
+ "aria-pressed": showDebug,
2469
+ title: showDebug ? "Hide debug log" : "Show debug log",
2470
+ onClick: () => setDebugOpen((v) => !v),
2471
+ children: /* @__PURE__ */ jsx(BugIcon, {})
2472
+ }
2473
+ ) : null
2474
+ ]
2475
+ }
2476
+ ),
2477
+ showDebug && chat ? /* @__PURE__ */ jsxs("aside", { className: "realtime-debug-side", "aria-label": "Realtime debug log", children: [
2478
+ /* @__PURE__ */ jsx("div", { className: "realtime-debug-head", children: "Debug log" }),
2479
+ /* @__PURE__ */ jsx(
2480
+ Transcript,
2481
+ {
2482
+ nodes: chat.nodes,
2483
+ hero: {},
2484
+ toolRenderers: props.toolRenderers,
2485
+ status: chat.status
2486
+ }
2487
+ )
2488
+ ] }) : null
2489
+ ]
2490
+ }
2491
+ );
2492
+ };
2493
+ var Sidebar = (props) => {
2494
+ if (!props.children) return null;
2495
+ return /* @__PURE__ */ jsx("aside", { className: "sidebar", children: props.children });
2496
+ };
2497
+ async function* parseNdjsonStream(stream) {
2498
+ const reader = stream.getReader();
2499
+ const decoder = new TextDecoder();
2500
+ let buf = "";
2501
+ while (true) {
2502
+ const chunk = await reader.read();
2503
+ if (chunk.done) break;
2504
+ buf += decoder.decode(chunk.value, { stream: true });
2505
+ let idx = buf.indexOf("\n");
2506
+ while (idx >= 0) {
2507
+ const line = buf.slice(0, idx).trim();
2508
+ buf = buf.slice(idx + 1);
2509
+ idx = buf.indexOf("\n");
2510
+ if (!line) continue;
2511
+ if (line.startsWith(":")) continue;
2512
+ const parsed = safeParse(line);
2513
+ if (parsed === void 0) continue;
2514
+ if (!isAgentEvent(parsed)) {
2515
+ console.warn("[tinyweb-chat] dropping non-AgentEvent line", parsed);
2516
+ continue;
2517
+ }
2518
+ yield parsed;
2519
+ }
2520
+ }
2521
+ const tail = buf.trim();
2522
+ if (tail && !tail.startsWith(":")) {
2523
+ const parsed = safeParse(tail);
2524
+ if (parsed !== void 0 && isAgentEvent(parsed)) yield parsed;
2525
+ }
2526
+ }
2527
+ var safeParse = (line) => {
2528
+ try {
2529
+ return JSON.parse(line);
2530
+ } catch {
2531
+ return void 0;
2532
+ }
2533
+ };
2534
+
2535
+ // src/hooks/useAgentChat.ts
2536
+ var stripPreview = (img) => ({
2537
+ type: img.type,
2538
+ mediaType: img.mediaType,
2539
+ data: img.data,
2540
+ url: img.url,
2541
+ filename: img.filename
2542
+ });
2543
+ var nodeCounter = 0;
2544
+ var nextNodeId = () => {
2545
+ nodeCounter += 1;
2546
+ return "n" + nodeCounter;
2547
+ };
2548
+ var initialNodes = (msgs) => {
2549
+ if (!msgs) return [];
2550
+ return msgs.map(
2551
+ (m) => m.role === "user" ? { kind: "user", id: nextNodeId(), content: m.content, images: m.images } : { kind: "assistant", id: nextNodeId(), content: m.content }
2552
+ );
2553
+ };
2554
+ var resolveBody = (extra) => {
2555
+ if (typeof extra === "function") return extra();
2556
+ if (extra) return extra;
2557
+ return {};
2558
+ };
2559
+ var resolveHeaders = (h) => {
2560
+ if (typeof h === "function") return h();
2561
+ return h;
2562
+ };
2563
+ var useAgentChat = (opts) => {
2564
+ const [nodes, setNodes] = useState(() => initialNodes(opts.initialMessages));
2565
+ const [status, setStatus] = useState("idle");
2566
+ const [errorMessage, setErrorMessage] = useState(void 0);
2567
+ const abortRef = useRef(null);
2568
+ const openAssistantRef = useRef(null);
2569
+ const onEventRef = useRef(opts.onEvent);
2570
+ const onFinishRef = useRef(opts.onFinish);
2571
+ onEventRef.current = opts.onEvent;
2572
+ onFinishRef.current = opts.onFinish;
2573
+ const extraBodyRef = useRef(opts.extraBody);
2574
+ const headersRef = useRef(opts.headers);
2575
+ extraBodyRef.current = opts.extraBody;
2576
+ headersRef.current = opts.headers;
2577
+ const endpointRef = useRef(opts.endpoint);
2578
+ endpointRef.current = opts.endpoint;
2579
+ useEffect(
2580
+ () => () => {
2581
+ abortRef.current?.abort();
2582
+ },
2583
+ []
2584
+ );
2585
+ const applyEvent = useCallback((ev) => {
2586
+ onEventRef.current?.(ev);
2587
+ if (ev.type === "text-delta") {
2588
+ setNodes((prev) => {
2589
+ const openId = openAssistantRef.current;
2590
+ if (openId) {
2591
+ return prev.map(
2592
+ (n) => n.id === openId && n.kind === "assistant" ? { ...n, content: n.content + ev.text } : n
2593
+ );
2594
+ }
2595
+ const id = nextNodeId();
2596
+ openAssistantRef.current = id;
2597
+ return prev.concat({ kind: "assistant", id, content: ev.text });
2598
+ });
2599
+ return;
2600
+ }
2601
+ if (ev.type === "text-end") {
2602
+ openAssistantRef.current = null;
2603
+ return;
2604
+ }
2605
+ if (ev.type === "reasoning-delta") {
2606
+ return;
2607
+ }
2608
+ if (ev.type === "tool-call") {
2609
+ openAssistantRef.current = null;
2610
+ setNodes(
2611
+ (prev) => prev.concat({
2612
+ kind: "tool-call",
2613
+ id: nextNodeId(),
2614
+ callId: ev.id,
2615
+ name: ev.name,
2616
+ input: ev.input
2617
+ })
2618
+ );
2619
+ return;
2620
+ }
2621
+ if (ev.type === "tool-result") {
2622
+ openAssistantRef.current = null;
2623
+ setNodes(
2624
+ (prev) => (
2625
+ // Drop the matching pending `tool-call` row so the result card
2626
+ // replaces it inline instead of stacking a stale "Đang …" pill above.
2627
+ prev.filter((n) => !(n.kind === "tool-call" && n.callId === ev.id)).concat({
2628
+ kind: "tool-result",
2629
+ id: nextNodeId(),
2630
+ name: ev.name,
2631
+ result: ev.result,
2632
+ raw: ev
2633
+ })
2634
+ )
2635
+ );
2636
+ return;
2637
+ }
2638
+ if (ev.type === "tool-error") {
2639
+ openAssistantRef.current = null;
2640
+ setNodes(
2641
+ (prev) => prev.filter((n) => !(n.kind === "tool-call" && n.callId === ev.id)).concat({
2642
+ kind: "tool-error",
2643
+ id: nextNodeId(),
2644
+ name: ev.name,
2645
+ message: ev.message
2646
+ })
2647
+ );
2648
+ return;
2649
+ }
2650
+ if (ev.type === "context-condense-start") {
2651
+ openAssistantRef.current = null;
2652
+ setNodes(
2653
+ (prev) => prev.concat({
2654
+ kind: "condense",
2655
+ id: nextNodeId(),
2656
+ trigger: ev.trigger,
2657
+ state: {
2658
+ phase: "start",
2659
+ trigger: ev.trigger,
2660
+ estimatedTokens: ev.estimatedTokens,
2661
+ budgetTokens: ev.budgetTokens
2662
+ }
2663
+ })
2664
+ );
2665
+ return;
2666
+ }
2667
+ if (ev.type === "context-condense") {
2668
+ openAssistantRef.current = null;
2669
+ setNodes((prev) => updateCondense(prev, ev.trigger, {
2670
+ phase: "success",
2671
+ trigger: ev.trigger,
2672
+ summary: ev.summary,
2673
+ prevTokens: ev.prevTokens,
2674
+ newTokens: ev.newTokens,
2675
+ cost: ev.cost,
2676
+ modelId: ev.modelId
2677
+ }));
2678
+ return;
2679
+ }
2680
+ if (ev.type === "context-condense-error") {
2681
+ openAssistantRef.current = null;
2682
+ setNodes((prev) => updateCondense(prev, ev.trigger, {
2683
+ phase: "error",
2684
+ trigger: ev.trigger,
2685
+ message: ev.message,
2686
+ retryExhausted: ev.retryExhausted
2687
+ }));
2688
+ return;
2689
+ }
2690
+ if (ev.type === "error") {
2691
+ openAssistantRef.current = null;
2692
+ setNodes(
2693
+ (prev) => prev.concat({ kind: "error", id: nextNodeId(), message: ev.message })
2694
+ );
2695
+ return;
2696
+ }
2697
+ if (ev.type === "finish") {
2698
+ onFinishRef.current?.(ev);
2699
+ return;
2700
+ }
2701
+ }, []);
2702
+ const send = useCallback(
2703
+ (rawPrompt, options) => {
2704
+ const prompt = rawPrompt.trim();
2705
+ const images = options?.images ?? [];
2706
+ if (!prompt && images.length === 0) return;
2707
+ if (status === "requesting" || status === "streaming") {
2708
+ console.warn("[tinyweb-chat] send() called while a request is in flight \u2014 ignored");
2709
+ return;
2710
+ }
2711
+ setErrorMessage(void 0);
2712
+ openAssistantRef.current = null;
2713
+ setNodes(
2714
+ (prev) => prev.concat({
2715
+ kind: "user",
2716
+ id: nextNodeId(),
2717
+ content: prompt,
2718
+ images: images.length > 0 ? images : void 0
2719
+ })
2720
+ );
2721
+ const ctrl = new AbortController();
2722
+ abortRef.current = ctrl;
2723
+ setStatus("requesting");
2724
+ const wireAttachments = images.map(stripPreview);
2725
+ const body = JSON.stringify({
2726
+ prompt,
2727
+ ...wireAttachments.length > 0 ? { attachments: wireAttachments } : {},
2728
+ ...resolveBody(extraBodyRef.current)
2729
+ });
2730
+ const baseHeaders = { "content-type": "application/json" };
2731
+ const merged = new Headers(baseHeaders);
2732
+ const extra = resolveHeaders(headersRef.current);
2733
+ if (extra) {
2734
+ new Headers(extra).forEach((v, k) => merged.set(k, v));
2735
+ }
2736
+ const run = async () => {
2737
+ try {
2738
+ const res = await fetch(endpointRef.current, {
2739
+ method: "POST",
2740
+ headers: merged,
2741
+ body,
2742
+ signal: ctrl.signal
2743
+ });
2744
+ if (!res.ok || !res.body) {
2745
+ const txt = await res.text().catch(() => "");
2746
+ throw new Error("chat failed: " + res.status + " " + txt);
2747
+ }
2748
+ setStatus("streaming");
2749
+ for await (const ev of parseNdjsonStream(res.body)) {
2750
+ if (ctrl.signal.aborted) break;
2751
+ applyEvent(ev);
2752
+ }
2753
+ setStatus("finished");
2754
+ } catch (err) {
2755
+ if (ctrl.signal.aborted) {
2756
+ setStatus("idle");
2757
+ return;
2758
+ }
2759
+ const msg = err instanceof Error ? err.message : String(err);
2760
+ setErrorMessage(msg);
2761
+ setNodes((prev) => prev.concat({ kind: "error", id: nextNodeId(), message: msg }));
2762
+ setStatus("error");
2763
+ } finally {
2764
+ openAssistantRef.current = null;
2765
+ if (abortRef.current === ctrl) abortRef.current = null;
2766
+ }
2767
+ };
2768
+ void run();
2769
+ },
2770
+ [applyEvent, status]
2771
+ );
2772
+ const abort = useCallback(() => {
2773
+ abortRef.current?.abort();
2774
+ }, []);
2775
+ const reset = useCallback(() => {
2776
+ abortRef.current?.abort();
2777
+ openAssistantRef.current = null;
2778
+ setNodes(initialNodes(opts.initialMessages));
2779
+ setStatus("idle");
2780
+ setErrorMessage(void 0);
2781
+ }, [opts.initialMessages]);
2782
+ const appendUserMessage = useCallback(
2783
+ (content, images) => {
2784
+ const openId = openAssistantRef.current;
2785
+ const isReactionKind = (k) => k === "assistant" || k === "tool-call" || k === "tool-result" || k === "tool-error";
2786
+ setNodes((prev) => {
2787
+ const userNode = {
2788
+ kind: "user",
2789
+ id: nextNodeId(),
2790
+ content,
2791
+ images: images && images.length > 0 ? images : void 0
2792
+ };
2793
+ let insertAt = prev.length;
2794
+ for (let i = prev.length - 1; i >= 0; i--) {
2795
+ const n = prev[i];
2796
+ if (!n || !isReactionKind(n.kind)) break;
2797
+ const prevNode = i > 0 ? prev[i - 1] : void 0;
2798
+ if (n.kind === "assistant" && prevNode && prevNode.kind === "user") break;
2799
+ insertAt = i;
2800
+ }
2801
+ if (openId) {
2802
+ const cursorIdx = prev.findIndex(
2803
+ (n) => n.id === openId && n.kind === "assistant"
2804
+ );
2805
+ if (cursorIdx >= 0 && cursorIdx < insertAt) insertAt = cursorIdx;
2806
+ }
2807
+ if (insertAt < prev.length) {
2808
+ const next = prev.slice();
2809
+ next.splice(insertAt, 0, userNode);
2810
+ return next;
2811
+ }
2812
+ return prev.concat(userNode);
2813
+ });
2814
+ },
2815
+ []
2816
+ );
2817
+ return { nodes, status, errorMessage, send, abort, reset, applyEvent, appendUserMessage };
2818
+ };
2819
+ var updateCondense = (prev, trigger, next) => {
2820
+ const existingIdx = prev.findIndex(
2821
+ (n) => n.kind === "condense" && n.trigger === trigger
2822
+ );
2823
+ if (existingIdx >= 0) {
2824
+ const copy = prev.slice();
2825
+ const node = copy[existingIdx];
2826
+ if (node && node.kind === "condense") {
2827
+ copy[existingIdx] = { ...node, state: next };
2828
+ }
2829
+ return copy;
2830
+ }
2831
+ return prev.concat({ kind: "condense", id: nextNodeId(), trigger, state: next });
2832
+ };
2833
+
2834
+ // src/util/theme.ts
2835
+ var themeToStyle = (theme) => {
2836
+ if (!theme) return {};
2837
+ const style = {};
2838
+ if (theme.bg) style["--bg"] = theme.bg;
2839
+ if (theme.panel) style["--panel"] = theme.panel;
2840
+ if (theme.border) style["--border"] = theme.border;
2841
+ if (theme.text) style["--text"] = theme.text;
2842
+ if (theme.muted) style["--muted"] = theme.muted;
2843
+ if (theme.accent) style["--accent"] = theme.accent;
2844
+ if (theme.accent2) style["--accent-2"] = theme.accent2;
2845
+ if (theme.warn) style["--warn"] = theme.warn;
2846
+ if (theme.err) style["--err"] = theme.err;
2847
+ const rt = theme.realtime;
2848
+ if (rt) {
2849
+ if (rt.bgFrom) style["--rt-bg-from"] = rt.bgFrom;
2850
+ if (rt.bgTo) style["--rt-bg-to"] = rt.bgTo;
2851
+ if (rt.halo1) style["--rt-halo-1"] = rt.halo1;
2852
+ if (rt.halo2) style["--rt-halo-2"] = rt.halo2;
2853
+ if (rt.halo3) style["--rt-halo-3"] = rt.halo3;
2854
+ if (rt.core) style["--rt-core"] = rt.core;
2855
+ if (rt.accent) style["--rt-accent"] = rt.accent;
2856
+ if (rt.micBg) style["--rt-mic-bg"] = rt.micBg;
2857
+ if (rt.micFg) style["--rt-mic-fg"] = rt.micFg;
2858
+ }
2859
+ return style;
2860
+ };
2861
+ var TinywebChat = (props) => {
2862
+ const chat = useAgentChat({
2863
+ endpoint: props.endpoint,
2864
+ extraBody: props.extraBody,
2865
+ headers: props.headers,
2866
+ initialMessages: props.initialMessages,
2867
+ onEvent: props.onEvent,
2868
+ onFinish: props.onFinish
2869
+ });
2870
+ const hasSidebar = Boolean(props.sidebar);
2871
+ const mainClass = hasSidebar ? "main" : "main no-sidebar";
2872
+ const busy = chat.status === "requesting" || chat.status === "streaming";
2873
+ const composerDisabled = props.disabled === true;
2874
+ const [callOpen, setCallOpen] = useState(false);
2875
+ const realtime = props.realtime;
2876
+ const inCall = Boolean(realtime && callOpen);
2877
+ return /* @__PURE__ */ jsxs("div", { className: "tinyweb-chat", style: themeToStyle(props.theme), children: [
2878
+ /* @__PURE__ */ jsx(Header, { title: props.title ?? "Tinyweb Agent" }),
2879
+ /* @__PURE__ */ jsxs("main", { className: mainClass, children: [
2880
+ /* @__PURE__ */ jsx(Sidebar, { children: props.sidebar }),
2881
+ /* @__PURE__ */ jsx("section", { className: "chat", children: inCall && realtime ? /* @__PURE__ */ jsx(
2882
+ RealtimeCallOverlay,
2883
+ {
2884
+ tokenEndpoint: realtime.tokenEndpoint,
2885
+ tokenHeaders: realtime.tokenHeaders,
2886
+ tokenBody: realtime.tokenBody,
2887
+ toolHandlers: realtime.toolHandlers,
2888
+ toolProxyPath: realtime.toolProxyPath,
2889
+ toolProxyHeaders: realtime.toolProxyHeaders,
2890
+ idleTimeoutMs: realtime.idleTimeoutMs,
2891
+ title: realtime.title ?? props.title,
2892
+ onUserTurn: realtime.onUserTurn,
2893
+ onAssistantTurn: realtime.onAssistantTurn,
2894
+ onClose: () => setCallOpen(false),
2895
+ chat,
2896
+ toolRenderers: props.toolRenderers
2897
+ }
2898
+ ) : /* @__PURE__ */ jsxs(Fragment, { children: [
2899
+ /* @__PURE__ */ jsx(
2900
+ Transcript,
2901
+ {
2902
+ nodes: chat.nodes,
2903
+ hero: props.hero === void 0 ? {} : props.hero,
2904
+ toolRenderers: props.toolRenderers,
2905
+ status: chat.status
2906
+ }
2907
+ ),
2908
+ /* @__PURE__ */ jsx(
2909
+ Composer,
2910
+ {
2911
+ onSend: chat.send,
2912
+ disabled: composerDisabled,
2913
+ placeholder: props.placeholder,
2914
+ attachmentLimits: props.attachmentLimits,
2915
+ busy,
2916
+ onStop: chat.abort,
2917
+ onStartCall: realtime ? () => setCallOpen(true) : void 0
2918
+ }
2919
+ )
2920
+ ] }) })
2921
+ ] })
2922
+ ] });
2923
+ };
2924
+ var toCssSize = (size) => {
2925
+ if (size === void 0) return void 0;
2926
+ return typeof size === "number" ? `${size}px` : size;
2927
+ };
2928
+ var avgBand = (buf, lo, hi) => {
2929
+ const lim = Math.min(hi, buf.length);
2930
+ if (lim <= lo) return 0;
2931
+ let sum = 0;
2932
+ for (let i = lo; i < lim; i++) sum += buf[i] ?? 0;
2933
+ return sum / (lim - lo);
2934
+ };
2935
+ var SPEAKER_FLIP_MIN_MS = 300;
2936
+ var SPEAKER_DELTA_THRESHOLD = 0.03;
2937
+ var PALETTES = {
2938
+ idle: { inner: new THREE.Color("#9282dc"), outer: new THREE.Color("#1e1640") },
2939
+ user: { inner: new THREE.Color("#a8b8ff"), outer: new THREE.Color("#1d2a55") },
2940
+ agent: { inner: new THREE.Color("#b9aef0"), outer: new THREE.Color("#2a1a55") }
2941
+ };
2942
+ var VERTEX_SHADER = (
2943
+ /* glsl */
2944
+ `
2945
+ uniform float uAmp;
2946
+ uniform float uFreq;
2947
+ uniform float uPhase;
2948
+ uniform float uSize;
2949
+
2950
+ varying float vRadial;
2951
+
2952
+ void main() {
2953
+ vec3 p = position;
2954
+ float r = length(p.xz);
2955
+ p.y = uAmp * sin(uFreq * r + uPhase);
2956
+
2957
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
2958
+ gl_Position = projectionMatrix * mv;
2959
+ gl_PointSize = uSize * (1.0 / max(-mv.z, 0.001));
2960
+ vRadial = r;
2961
+ }
2962
+ `
2963
+ );
2964
+ var FRAGMENT_SHADER = (
2965
+ /* glsl */
2966
+ `
2967
+ uniform vec3 uColorA;
2968
+ uniform vec3 uColorB;
2969
+ uniform float uOpacity;
2970
+
2971
+ varying float vRadial;
2972
+
2973
+ void main() {
2974
+ vec2 uv = gl_PointCoord - 0.5;
2975
+ float d = length(uv);
2976
+ float alpha = smoothstep(0.5, 0.0, d);
2977
+ if (alpha < 0.02) discard;
2978
+ vec3 col = mix(uColorA, uColorB, smoothstep(0.0, 1.2, vRadial));
2979
+ gl_FragColor = vec4(col, alpha * uOpacity);
2980
+ }
2981
+ `
2982
+ );
2983
+ var RipplePoints = (props) => {
2984
+ const geometry = useMemo(() => {
2985
+ const total = props.count * props.count;
2986
+ const positions = new Float32Array(total * 3);
2987
+ const half = props.count / 2;
2988
+ let p = 0;
2989
+ for (let xi = 0; xi < props.count; xi++) {
2990
+ for (let zi = 0; zi < props.count; zi++) {
2991
+ positions[p++] = (xi - half) * props.separation;
2992
+ positions[p++] = 0;
2993
+ positions[p++] = (zi - half) * props.separation;
2994
+ }
2995
+ }
2996
+ const g = new THREE.BufferGeometry();
2997
+ g.setAttribute("position", new THREE.BufferAttribute(positions, 3));
2998
+ g.computeBoundingSphere();
2999
+ return g;
3000
+ }, [props.count, props.separation]);
3001
+ const material = useMemo(() => {
3002
+ const uniforms = {
3003
+ uAmp: { value: 0.12 },
3004
+ uFreq: { value: 7.5 },
3005
+ uPhase: { value: 0 },
3006
+ uSize: { value: 14 },
3007
+ uOpacity: { value: 0.85 },
3008
+ uColorA: { value: PALETTES.idle.inner.clone() },
3009
+ uColorB: { value: PALETTES.idle.outer.clone() }
3010
+ };
3011
+ const mat = new THREE.ShaderMaterial({
3012
+ vertexShader: VERTEX_SHADER,
3013
+ fragmentShader: FRAGMENT_SHADER,
3014
+ uniforms,
3015
+ transparent: true,
3016
+ depthWrite: false,
3017
+ blending: THREE.AdditiveBlending
3018
+ });
3019
+ return mat;
3020
+ }, []);
3021
+ const smoothLevelRef = useRef(0);
3022
+ const currentSpeakerRef = useRef("idle");
3023
+ const tmpColorA = useMemo(() => new THREE.Color(), []);
3024
+ const tmpColorB = useMemo(() => new THREE.Color(), []);
3025
+ useFrame((_state, dt) => {
3026
+ const safeDt = Math.min(dt, 1 / 30);
3027
+ const target = Math.max(0, Math.min(1, props.levelRef.current || 0));
3028
+ smoothLevelRef.current += (target - smoothLevelRef.current) * 0.18;
3029
+ const lvl = smoothLevelRef.current;
3030
+ if (props.reducedMotion) {
3031
+ material.uniforms.uAmp.value = 0.18;
3032
+ material.uniforms.uFreq.value = 7.5;
3033
+ material.uniforms.uPhase.value = 0;
3034
+ material.uniforms.uSize.value = 14;
3035
+ material.uniforms.uOpacity.value = 0.85;
3036
+ return;
3037
+ }
3038
+ material.uniforms.uAmp.value = 0.1 + lvl * 0.55;
3039
+ material.uniforms.uFreq.value = 7.5 + lvl * 4;
3040
+ material.uniforms.uPhase.value += safeDt * (1.4 + lvl * 2.2);
3041
+ material.uniforms.uSize.value = 14 + lvl * 22;
3042
+ material.uniforms.uOpacity.value = 0.7 + lvl * 0.3;
3043
+ const nextSpeaker = props.speakerRef.current;
3044
+ if (nextSpeaker !== currentSpeakerRef.current) {
3045
+ currentSpeakerRef.current = nextSpeaker;
3046
+ }
3047
+ const palette = PALETTES[currentSpeakerRef.current];
3048
+ tmpColorA.copy(palette.inner);
3049
+ tmpColorB.copy(palette.outer);
3050
+ material.uniforms.uColorA.value.lerp(tmpColorA, 0.08);
3051
+ material.uniforms.uColorB.value.lerp(tmpColorB, 0.08);
3052
+ });
3053
+ useEffect(() => {
3054
+ return () => {
3055
+ geometry.dispose();
3056
+ material.dispose();
3057
+ };
3058
+ }, [geometry, material]);
3059
+ const args = [geometry, material];
3060
+ return /* @__PURE__ */ jsx("points", { args, rotation: [-Math.PI / 7, 0, 0] });
3061
+ };
3062
+ var RealtimeOrb = (props) => {
3063
+ const hostRef = useRef(null);
3064
+ const rafRef = useRef(null);
3065
+ const stateRef = useRef(props.state ?? "idle");
3066
+ const speakerOverrideRef = useRef(props.speaker);
3067
+ const inputAnalyserRef = useRef(props.inputAnalyser ?? null);
3068
+ const outputAnalyserRef = useRef(props.outputAnalyser ?? null);
3069
+ const externalLevelRef = props.levelRef;
3070
+ const currentLevelRef = useRef(0);
3071
+ const currentSpeakerRef = useRef("idle");
3072
+ stateRef.current = props.state ?? "idle";
3073
+ speakerOverrideRef.current = props.speaker;
3074
+ inputAnalyserRef.current = props.inputAnalyser ?? null;
3075
+ outputAnalyserRef.current = props.outputAnalyser ?? null;
3076
+ const reducedMotion = useMemo(() => {
3077
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
3078
+ return false;
3079
+ }
3080
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
3081
+ }, []);
3082
+ useEffect(() => {
3083
+ const host = hostRef.current;
3084
+ if (!host) return;
3085
+ if (reducedMotion) {
3086
+ host.style.setProperty("--rt-level", "0.25");
3087
+ host.setAttribute("data-speaker", speakerOverrideRef.current ?? "idle");
3088
+ currentLevelRef.current = 0.25;
3089
+ currentSpeakerRef.current = speakerOverrideRef.current ?? "idle";
3090
+ return;
3091
+ }
3092
+ const inBuf = new Uint8Array(64);
3093
+ const outBuf = new Uint8Array(64);
3094
+ let smoothed = 0;
3095
+ let speaker = speakerOverrideRef.current ?? "idle";
3096
+ let lastFlipAt = 0;
3097
+ const tick = () => {
3098
+ const inA = inputAnalyserRef.current;
3099
+ const outA = outputAnalyserRef.current;
3100
+ let userBand = 0;
3101
+ let agentBand = 0;
3102
+ if (inA && typeof inA.getByteFrequencyData === "function") {
3103
+ inA.getByteFrequencyData(inBuf);
3104
+ userBand = avgBand(inBuf, 2, 8) / 255;
3105
+ }
3106
+ if (outA && typeof outA.getByteFrequencyData === "function") {
3107
+ outA.getByteFrequencyData(outBuf);
3108
+ agentBand = avgBand(outBuf, 4, 32) / 255;
3109
+ }
3110
+ if (!inA && !outA) {
3111
+ const fallback = externalLevelRef ? Math.max(0, Math.min(1, externalLevelRef.current || 0)) : 0;
3112
+ userBand = fallback;
3113
+ agentBand = fallback;
3114
+ }
3115
+ const raw = Math.max(userBand, agentBand);
3116
+ smoothed = smoothed * 0.82 + raw * 0.18;
3117
+ currentLevelRef.current = smoothed;
3118
+ host.style.setProperty("--rt-level", smoothed.toFixed(3));
3119
+ const stateNow = stateRef.current;
3120
+ const override = speakerOverrideRef.current;
3121
+ if (override !== void 0) {
3122
+ if (override !== speaker) {
3123
+ speaker = override;
3124
+ host.setAttribute("data-speaker", speaker);
3125
+ currentSpeakerRef.current = speaker;
3126
+ }
3127
+ rafRef.current = requestAnimationFrame(tick);
3128
+ return;
3129
+ }
3130
+ const isActive = stateNow === "listening" || stateNow === "speaking";
3131
+ if (!isActive) {
3132
+ if (speaker !== "idle") {
3133
+ speaker = "idle";
3134
+ host.setAttribute("data-speaker", speaker);
3135
+ currentSpeakerRef.current = speaker;
3136
+ }
3137
+ rafRef.current = requestAnimationFrame(tick);
3138
+ return;
3139
+ }
3140
+ const now = performance.now();
3141
+ const delta = userBand - agentBand;
3142
+ const absDelta = Math.abs(delta);
3143
+ const canFlip = now - lastFlipAt >= SPEAKER_FLIP_MIN_MS;
3144
+ if (absDelta > SPEAKER_DELTA_THRESHOLD && canFlip) {
3145
+ const next = delta > 0 ? "user" : "agent";
3146
+ if (next !== speaker) {
3147
+ speaker = next;
3148
+ lastFlipAt = now;
3149
+ host.setAttribute("data-speaker", speaker);
3150
+ currentSpeakerRef.current = speaker;
3151
+ }
3152
+ }
3153
+ rafRef.current = requestAnimationFrame(tick);
3154
+ };
3155
+ host.setAttribute("data-speaker", speaker);
3156
+ currentSpeakerRef.current = speaker;
3157
+ rafRef.current = requestAnimationFrame(tick);
3158
+ return () => {
3159
+ if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
3160
+ rafRef.current = null;
3161
+ };
3162
+ }, [externalLevelRef, reducedMotion]);
3163
+ const cssSize = toCssSize(props.size);
3164
+ const style = cssSize ? { width: cssSize, height: cssSize } : void 0;
3165
+ const speakerAttr = props.speaker ?? "idle";
3166
+ const count = reducedMotion ? 38 : 80;
3167
+ return /* @__PURE__ */ jsxs(
3168
+ "div",
3169
+ {
3170
+ ref: hostRef,
3171
+ className: `realtime-orb realtime-orb--${props.state ?? "idle"} realtime-orb--r3f`,
3172
+ "data-speaker": speakerAttr,
3173
+ style,
3174
+ "aria-hidden": true,
3175
+ children: [
3176
+ /* @__PURE__ */ jsx("span", { className: "realtime-orb__halo realtime-orb__halo--3" }),
3177
+ /* @__PURE__ */ jsx("span", { className: "realtime-orb__halo realtime-orb__halo--2" }),
3178
+ /* @__PURE__ */ jsx("span", { className: "realtime-orb__core" }),
3179
+ /* @__PURE__ */ jsx("div", { className: "realtime-orb__canvas", children: /* @__PURE__ */ jsxs(
3180
+ Canvas,
3181
+ {
3182
+ dpr: [1, 2],
3183
+ camera: { position: [0, 0.85, 1.6], fov: 32 },
3184
+ gl: { antialias: false, alpha: true, premultipliedAlpha: false },
3185
+ style: { width: "100%", height: "100%" },
3186
+ children: [
3187
+ /* @__PURE__ */ jsx("ambientLight", { intensity: 0.6 }),
3188
+ /* @__PURE__ */ jsx(
3189
+ RipplePoints,
3190
+ {
3191
+ count,
3192
+ separation: 0.024,
3193
+ reducedMotion,
3194
+ levelRef: currentLevelRef,
3195
+ speakerRef: currentSpeakerRef
3196
+ }
3197
+ )
3198
+ ]
3199
+ }
3200
+ ) }),
3201
+ /* @__PURE__ */ jsx("span", { className: "realtime-orb__specular" })
3202
+ ]
3203
+ }
3204
+ );
3205
+ };
3206
+
3207
+ export { RealtimeCallOverlay, RealtimeOrb, TinywebChat, ToolCard, WireOrbEffect, defaultToolRenderers, extractExec, extractToolImage, friendlyToolLabel, renderMarkdown, truncateBase64InJson, useAgentChat, useRealtimeCall };
3208
+ //# sourceMappingURL=index.js.map
3209
+ //# sourceMappingURL=index.js.map