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