@cheerlyai/agentlib-react 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,723 @@
1
+ // src/AgentChat.tsx
2
+ import { splitReply } from "@cheerlyai/agentlib-protocol";
3
+ import { useChat } from "@ai-sdk/react";
4
+ import { DefaultChatTransport } from "ai";
5
+ import {
6
+ useEffect,
7
+ useLayoutEffect,
8
+ useRef,
9
+ useState as useState2
10
+ } from "react";
11
+ import { isValidElement } from "react";
12
+ import ReactMarkdown from "react-markdown";
13
+ import rehypeRaw from "rehype-raw";
14
+ import rehypeSanitize from "rehype-sanitize";
15
+ import remarkGfm from "remark-gfm";
16
+
17
+ // src/Chart.tsx
18
+ import { parseChartSpec } from "@cheerlyai/agentlib-protocol";
19
+ import { useId, useState } from "react";
20
+ import { jsx, jsxs } from "react/jsx-runtime";
21
+ var MAX_SERIES = 8;
22
+ var W = 720;
23
+ var H = 300;
24
+ var PAD = { top: 16, right: 16, bottom: 34, left: 52 };
25
+ var PLOT = { w: W - PAD.left - PAD.right, h: H - PAD.top - PAD.bottom };
26
+ function ticks(min, max, count = 4) {
27
+ if (min === max) return [min];
28
+ const raw = (max - min) / count;
29
+ const mag = 10 ** Math.floor(Math.log10(raw));
30
+ const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? mag * 10;
31
+ const out = [];
32
+ for (let t = Math.floor(min / step) * step; t <= max + step / 2; t += step) {
33
+ out.push(Number(t.toFixed(10)));
34
+ }
35
+ return out;
36
+ }
37
+ function barPath(x, y, w, h, round) {
38
+ const r = round ? Math.max(0, Math.min(4, w / 2, h)) : 0;
39
+ if (r === 0) return `M${x},${y} h${w} v${h} h${-w} Z`;
40
+ return `M${x},${y + h} L${x},${y + r} Q${x},${y} ${x + r},${y} L${x + w - r},${y} Q${x + w},${y} ${x + w},${y + r} L${x + w},${y + h} Z`;
41
+ }
42
+ var fmt = (n) => Math.abs(n) >= 1e3 ? n.toLocaleString("en-US") : String(Number(n.toFixed(2)));
43
+ function Chart({ spec }) {
44
+ const [showTable, setShowTable] = useState(false);
45
+ const id = useId();
46
+ const { type, x, series, unit, title } = spec;
47
+ const stacked = type === "stacked_bar";
48
+ const multi = series.length > 1;
49
+ const totals = x.map((_, i) => series.reduce((sum, s) => sum + s.values[i], 0));
50
+ const flat = series.flatMap((s) => s.values);
51
+ const hi = Math.max(0, ...stacked ? totals : flat);
52
+ const lo = Math.min(0, ...stacked ? totals : flat);
53
+ const tickValues = ticks(lo, hi);
54
+ const yMax = Math.max(...tickValues, hi);
55
+ const yMin = Math.min(...tickValues, lo);
56
+ const yOf = (v) => PAD.top + PLOT.h - (v - yMin) / (yMax - yMin || 1) * PLOT.h;
57
+ const band = PLOT.w / x.length;
58
+ const centre = (i) => PAD.left + band * i + band / 2;
59
+ const label = (i) => `var(--alx-s${i % MAX_SERIES + 1})`;
60
+ return /* @__PURE__ */ jsxs("figure", { className: "alx-chart my-3 first:mt-0 last:mb-0", children: [
61
+ /* @__PURE__ */ jsx("style", { children: CSS }),
62
+ title ? /* @__PURE__ */ jsx("figcaption", { className: "alx-chart-title", children: title }) : null,
63
+ /* @__PURE__ */ jsxs(
64
+ "svg",
65
+ {
66
+ viewBox: `0 0 ${W} ${H}`,
67
+ className: "alx-chart-svg",
68
+ role: "img",
69
+ "aria-labelledby": `${id}-t`,
70
+ preserveAspectRatio: "xMidYMid meet",
71
+ children: [
72
+ /* @__PURE__ */ jsxs("title", { id: `${id}-t`, children: [
73
+ title ?? `${type} chart`,
74
+ multi ? ` \u2014 ${series.map((s) => s.label).join(", ")}` : ""
75
+ ] }),
76
+ tickValues.map((t) => /* @__PURE__ */ jsxs("g", { children: [
77
+ /* @__PURE__ */ jsx(
78
+ "line",
79
+ {
80
+ x1: PAD.left,
81
+ x2: W - PAD.right,
82
+ y1: yOf(t),
83
+ y2: yOf(t),
84
+ className: "alx-grid"
85
+ }
86
+ ),
87
+ /* @__PURE__ */ jsx("text", { x: PAD.left - 8, y: yOf(t), className: "alx-tick", textAnchor: "end", children: fmt(t) })
88
+ ] }, t)),
89
+ (type === "bar" || stacked) && x.map((_, i) => {
90
+ const groupW = Math.min(band * 0.7, stacked ? 24 : 24 * series.length);
91
+ const barW = stacked ? groupW : groupW / series.length;
92
+ let stackTop = yOf(0);
93
+ return /* @__PURE__ */ jsx("g", { children: series.map((s, si) => {
94
+ const v = s.values[i];
95
+ if (stacked) {
96
+ const h = Math.abs(yOf(v) - yOf(0));
97
+ stackTop -= h;
98
+ return /* @__PURE__ */ jsx(
99
+ "path",
100
+ {
101
+ d: barPath(
102
+ centre(i) - groupW / 2,
103
+ // 2px surface gap does the separating, not a stroke.
104
+ stackTop + (si > 0 ? 2 : 0),
105
+ groupW,
106
+ Math.max(0, h - (si > 0 ? 2 : 0)),
107
+ si === series.length - 1
108
+ ),
109
+ fill: label(si)
110
+ },
111
+ si
112
+ );
113
+ }
114
+ const top = Math.min(yOf(v), yOf(0));
115
+ return /* @__PURE__ */ jsx(
116
+ "path",
117
+ {
118
+ d: barPath(
119
+ centre(i) - groupW / 2 + si * barW + (si > 0 ? 1 : 0),
120
+ top,
121
+ Math.max(0, barW - (multi ? 2 : 0)),
122
+ Math.abs(yOf(v) - yOf(0)),
123
+ true
124
+ ),
125
+ fill: label(si)
126
+ },
127
+ si
128
+ );
129
+ }) }, i);
130
+ }),
131
+ (type === "line" || type === "area") && series.map((s, si) => {
132
+ const pts = s.values.map((v, i) => `${centre(i)},${yOf(v)}`).join(" ");
133
+ return /* @__PURE__ */ jsxs("g", { children: [
134
+ type === "area" && /* @__PURE__ */ jsx(
135
+ "polygon",
136
+ {
137
+ points: `${centre(0)},${yOf(Math.max(0, yMin))} ${pts} ${centre(
138
+ x.length - 1
139
+ )},${yOf(Math.max(0, yMin))}`,
140
+ fill: label(si),
141
+ fillOpacity: 0.1
142
+ }
143
+ ),
144
+ /* @__PURE__ */ jsx("polyline", { points: pts, className: "alx-line", stroke: label(si) }),
145
+ s.values.map((v, i) => (
146
+ // 2px surface ring keeps markers legible where lines cross.
147
+ /* @__PURE__ */ jsx(
148
+ "circle",
149
+ {
150
+ cx: centre(i),
151
+ cy: yOf(v),
152
+ r: 4,
153
+ fill: label(si),
154
+ className: "alx-dot"
155
+ },
156
+ i
157
+ )
158
+ ))
159
+ ] }, si);
160
+ }),
161
+ x.map((lab, i) => /* @__PURE__ */ jsx("text", { x: centre(i), y: H - 12, className: "alx-tick", textAnchor: "middle", children: lab.length > 12 ? `${lab.slice(0, 11)}\u2026` : lab }, i))
162
+ ]
163
+ }
164
+ ),
165
+ multi && /* @__PURE__ */ jsx("ul", { className: "alx-legend", children: series.map((s, si) => /* @__PURE__ */ jsxs("li", { children: [
166
+ /* @__PURE__ */ jsx("span", { className: "alx-swatch", style: { background: label(si) } }),
167
+ s.label || `Series ${si + 1}`
168
+ ] }, si)) }),
169
+ /* @__PURE__ */ jsx(
170
+ "button",
171
+ {
172
+ type: "button",
173
+ className: "alx-table-toggle",
174
+ onClick: () => setShowTable((v) => !v),
175
+ "aria-expanded": showTable,
176
+ children: showTable ? "Hide data" : "Show data"
177
+ }
178
+ ),
179
+ showTable && /* @__PURE__ */ jsx("div", { className: "alx-table-wrap", children: /* @__PURE__ */ jsxs("table", { className: "alx-table", children: [
180
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
181
+ /* @__PURE__ */ jsx("th", {}),
182
+ x.map((lab) => /* @__PURE__ */ jsx("th", { children: lab }, lab))
183
+ ] }) }),
184
+ /* @__PURE__ */ jsx("tbody", { children: series.map((s, si) => /* @__PURE__ */ jsxs("tr", { children: [
185
+ /* @__PURE__ */ jsxs("th", { scope: "row", children: [
186
+ /* @__PURE__ */ jsx("span", { className: "alx-swatch", style: { background: label(si) } }),
187
+ s.label || `Series ${si + 1}`
188
+ ] }),
189
+ s.values.map((v, i) => /* @__PURE__ */ jsxs("td", { children: [
190
+ fmt(v),
191
+ unit ? ` ${unit}` : ""
192
+ ] }, i))
193
+ ] }, si)) })
194
+ ] }) })
195
+ ] });
196
+ }
197
+ var CSS = `
198
+ .alx-chart{--alx-surface:#fcfcfb;--alx-ink:#0b0b0b;--alx-ink-2:#52514e;--alx-grid:#e7e7e4;
199
+ --alx-s1:#2a78d6;--alx-s2:#eb6834;--alx-s3:#1baf7a;--alx-s4:#eda100;
200
+ --alx-s5:#e87ba4;--alx-s6:#008300;--alx-s7:#4a3aa7;--alx-s8:#e34948;}
201
+ @media (prefers-color-scheme:dark){:root:where(:not([data-theme="light"])) .alx-chart{
202
+ --alx-surface:#1a1a19;--alx-ink:#fff;--alx-ink-2:#c3c2b7;--alx-grid:#333331;
203
+ --alx-s1:#3987e5;--alx-s2:#d95926;--alx-s3:#199e70;--alx-s4:#c98500;
204
+ --alx-s5:#d55181;--alx-s6:#008300;--alx-s7:#9085e9;--alx-s8:#e66767;}}
205
+ :root[data-theme="dark"] .alx-chart{--alx-surface:#1a1a19;--alx-ink:#fff;--alx-ink-2:#c3c2b7;
206
+ --alx-grid:#333331;--alx-s1:#3987e5;--alx-s2:#d95926;--alx-s3:#199e70;--alx-s4:#c98500;
207
+ --alx-s5:#d55181;--alx-s6:#008300;--alx-s7:#9085e9;--alx-s8:#e66767;}
208
+ .alx-chart-title{font-size:13px;font-weight:600;color:var(--alx-ink);margin:0 0 6px}
209
+ .alx-chart-svg{width:100%;height:auto;display:block;overflow:visible}
210
+ .alx-grid{stroke:var(--alx-grid);stroke-width:1}
211
+ .alx-tick{font-size:11px;fill:var(--alx-ink-2);dominant-baseline:middle}
212
+ .alx-line{fill:none;stroke-width:2;stroke-linejoin:round;stroke-linecap:round}
213
+ .alx-dot{stroke:var(--alx-surface);stroke-width:2}
214
+ .alx-legend{display:flex;flex-wrap:wrap;gap:4px 14px;list-style:none;margin:8px 0 0;padding:0;
215
+ font-size:12px;color:var(--alx-ink-2)}
216
+ .alx-legend li{display:flex;align-items:center;gap:6px}
217
+ .alx-swatch{width:9px;height:9px;border-radius:2px;display:inline-block;flex:none}
218
+ .alx-table-toggle{margin-top:6px;font-size:11px;color:var(--alx-ink-2);background:none;
219
+ border:0;padding:0;cursor:pointer;text-decoration:underline;text-underline-offset:2px}
220
+ .alx-table-wrap{overflow-x:auto;margin-top:6px}
221
+ .alx-table{border-collapse:collapse;font-size:12px;color:var(--alx-ink)}
222
+ .alx-table th,.alx-table td{border-bottom:1px solid var(--alx-grid);padding:3px 8px;text-align:right;
223
+ white-space:nowrap}
224
+ .alx-table th[scope=row]{text-align:left;font-weight:500;display:flex;align-items:center;gap:6px}
225
+ .alx-table thead th{color:var(--alx-ink-2);font-weight:500}
226
+ `;
227
+
228
+ // src/identity.ts
229
+ var VISITOR_STORAGE_KEY = "agentlib:visitor";
230
+ function randomId() {
231
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
232
+ return crypto.randomUUID();
233
+ }
234
+ return `v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
235
+ }
236
+ function getOrCreateVisitorId() {
237
+ try {
238
+ const existing = localStorage.getItem(VISITOR_STORAGE_KEY);
239
+ if (existing) return existing;
240
+ const minted = randomId();
241
+ localStorage.setItem(VISITOR_STORAGE_KEY, minted);
242
+ return minted;
243
+ } catch {
244
+ return randomId();
245
+ }
246
+ }
247
+ function identityHeaders(user) {
248
+ if (user) {
249
+ return {
250
+ "X-Agentlib-User": user.id,
251
+ "X-Agentlib-User-Signature": user.signature,
252
+ ...user.data ? { "X-Agentlib-User-Data": user.data } : {}
253
+ };
254
+ }
255
+ return { "X-Agentlib-Visitor": getOrCreateVisitorId() };
256
+ }
257
+ function conversationStorageKey(agentId, user) {
258
+ return `agentlib:conversation:${agentId}:${user ? `u:${user.id}` : "visitor"}`;
259
+ }
260
+
261
+ // src/styles.ts
262
+ var AGENT_CHAT_CSS = `
263
+ .alw-root {
264
+ --alw-accent: #171717;
265
+ --alw-bg: #ffffff;
266
+ --alw-border: #e5e5e5;
267
+ --alw-text: #171717;
268
+ --alw-muted: #737373;
269
+ display: flex;
270
+ flex-direction: column;
271
+ height: 100%;
272
+ min-height: 0;
273
+ background: var(--alw-bg);
274
+ color: var(--alw-text);
275
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
276
+ "Helvetica Neue", Arial, sans-serif;
277
+ font-size: 14px;
278
+ line-height: 1.55;
279
+ border: 1px solid var(--alw-border);
280
+ border-radius: 14px;
281
+ overflow: hidden;
282
+ box-sizing: border-box;
283
+ }
284
+ .alw-root *, .alw-root *::before, .alw-root *::after { box-sizing: border-box; }
285
+
286
+ .alw-header {
287
+ display: flex;
288
+ align-items: center;
289
+ justify-content: space-between;
290
+ gap: 8px;
291
+ padding: 10px 14px;
292
+ border-bottom: 1px solid var(--alw-border);
293
+ flex: none;
294
+ }
295
+ .alw-title { font-weight: 600; font-size: 14px; margin: 0; }
296
+ .alw-new {
297
+ border: 0;
298
+ background: none;
299
+ color: var(--alw-muted);
300
+ font: inherit;
301
+ font-size: 12px;
302
+ cursor: pointer;
303
+ padding: 4px 8px;
304
+ border-radius: 8px;
305
+ }
306
+ .alw-new:hover { background: #f5f5f5; color: var(--alw-text); }
307
+ .alw-new:disabled { opacity: 0; pointer-events: none; }
308
+
309
+ .alw-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 16px 14px; }
310
+ .alw-empty { text-align: center; color: var(--alw-muted); padding: 40px 12px; }
311
+ .alw-empty-title { color: var(--alw-text); font-weight: 500; font-size: 15px; margin: 0 0 4px; }
312
+ .alw-empty-sub { font-size: 13px; margin: 0; }
313
+
314
+ .alw-messages { display: flex; flex-direction: column; gap: 12px; }
315
+ .alw-msg { display: flex; }
316
+ .alw-msg-user { justify-content: flex-end; }
317
+ .alw-bubble {
318
+ max-width: 85%;
319
+ padding: 8px 12px;
320
+ border-radius: 16px;
321
+ white-space: pre-wrap;
322
+ overflow-wrap: anywhere;
323
+ }
324
+ .alw-msg-user .alw-bubble {
325
+ background: var(--alw-accent);
326
+ color: #fff;
327
+ border-bottom-right-radius: 4px;
328
+ }
329
+ .alw-msg-assistant .alw-bubble {
330
+ background: #f5f5f5;
331
+ border-bottom-left-radius: 4px;
332
+ white-space: normal;
333
+ }
334
+ .alw-md p { margin: 0 0 8px; }
335
+ .alw-md p:last-child { margin-bottom: 0; }
336
+ .alw-md pre {
337
+ background: #171717;
338
+ color: #f5f5f5;
339
+ padding: 10px 12px;
340
+ border-radius: 8px;
341
+ overflow-x: auto;
342
+ font-size: 12.5px;
343
+ }
344
+ .alw-md code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }
345
+ .alw-md :not(pre) > code { background: #e8e8e8; padding: 1px 5px; border-radius: 4px; }
346
+ .alw-md a { color: inherit; text-decoration: underline; }
347
+ .alw-md ul, .alw-md ol { margin: 0 0 8px; padding-left: 20px; }
348
+ .alw-md table { border-collapse: collapse; margin: 0 0 8px; display: block; overflow-x: auto; }
349
+ .alw-md th, .alw-md td { border: 1px solid var(--alw-border); padding: 4px 8px; }
350
+
351
+ .alw-thinking { display: inline-flex; gap: 4px; padding: 10px 12px; }
352
+ .alw-thinking span {
353
+ width: 6px; height: 6px; border-radius: 50%;
354
+ background: var(--alw-muted);
355
+ animation: alw-pulse 1.2s ease-in-out infinite;
356
+ }
357
+ .alw-thinking span:nth-child(2) { animation-delay: 0.15s; }
358
+ .alw-thinking span:nth-child(3) { animation-delay: 0.3s; }
359
+ @keyframes alw-pulse {
360
+ 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
361
+ 30% { opacity: 1; transform: translateY(-3px); }
362
+ }
363
+
364
+ .alw-error { color: #dc2626; font-size: 13px; margin: 4px 0 0; }
365
+ .alw-error button {
366
+ border: 0; background: none; color: inherit; font: inherit;
367
+ text-decoration: underline; cursor: pointer; padding: 0; margin-left: 4px;
368
+ }
369
+
370
+ .alw-composer { flex: none; padding: 10px 12px 12px; }
371
+ .alw-inputrow {
372
+ display: flex;
373
+ align-items: flex-end;
374
+ gap: 8px;
375
+ border: 1px solid var(--alw-border);
376
+ border-radius: 22px;
377
+ padding: 6px 6px 6px 14px;
378
+ background: var(--alw-bg);
379
+ transition: border-color 0.15s;
380
+ }
381
+ .alw-inputrow:focus-within { border-color: #a3a3a3; }
382
+ .alw-input {
383
+ flex: 1;
384
+ border: 0;
385
+ outline: none;
386
+ resize: none;
387
+ background: none;
388
+ font: inherit;
389
+ color: inherit;
390
+ max-height: 140px;
391
+ padding: 4px 0;
392
+ }
393
+ .alw-send {
394
+ flex: none;
395
+ width: 32px; height: 32px;
396
+ border: 0;
397
+ border-radius: 50%;
398
+ background: var(--alw-accent);
399
+ color: #fff;
400
+ cursor: pointer;
401
+ display: inline-flex;
402
+ align-items: center;
403
+ justify-content: center;
404
+ }
405
+ .alw-send:disabled { opacity: 0.35; cursor: default; }
406
+ .alw-powered {
407
+ text-align: center;
408
+ font-size: 11px;
409
+ color: var(--alw-muted);
410
+ margin: 8px 0 0;
411
+ }
412
+ .alw-powered a { color: inherit; text-decoration: none; }
413
+ `;
414
+ var STYLE_ATTR = "data-agentlib-styles";
415
+ function injectStyles(root) {
416
+ const target = root instanceof ShadowRoot ? root : (root?.ownerDocument ?? document).head;
417
+ const holder = target;
418
+ if (holder.querySelector?.(`style[${STYLE_ATTR}]
419
+ .alw-sources {
420
+ margin-top: 10px;
421
+ padding: 8px 11px;
422
+ border: 1px solid var(--alw-border);
423
+ border-radius: 9px;
424
+ background: #f5f5f5;
425
+ }
426
+ .alw-sources-label {
427
+ margin: 0 0 2px;
428
+ font-size: 10px;
429
+ font-weight: 600;
430
+ letter-spacing: 0.06em;
431
+ text-transform: uppercase;
432
+ color: var(--alw-muted);
433
+ }
434
+ .alw-sources p,
435
+ .alw-sources ul,
436
+ .alw-sources ol {
437
+ margin: 2px 0;
438
+ font-size: 12.5px;
439
+ line-height: 1.55;
440
+ color: var(--alw-muted);
441
+ }
442
+ .alw-sources ul,
443
+ .alw-sources ol {
444
+ padding-left: 18px;
445
+ }
446
+ `)) return;
447
+ const style = document.createElement("style");
448
+ style.setAttribute(STYLE_ATTR, "");
449
+ style.textContent = AGENT_CHAT_CSS;
450
+ holder.appendChild(style);
451
+ }
452
+
453
+ // src/AgentChat.tsx
454
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
455
+ function readStored(key) {
456
+ try {
457
+ return localStorage.getItem(key);
458
+ } catch {
459
+ return null;
460
+ }
461
+ }
462
+ function writeStored(key, value) {
463
+ try {
464
+ if (value === null) localStorage.removeItem(key);
465
+ else localStorage.setItem(key, value);
466
+ } catch {
467
+ }
468
+ }
469
+ function messageText(message) {
470
+ return message.parts.map((p) => p.type === "text" ? p.text : "").join("");
471
+ }
472
+ function ThinkingDots() {
473
+ return /* @__PURE__ */ jsx2("div", { className: "alw-msg alw-msg-assistant", children: /* @__PURE__ */ jsxs2("div", { className: "alw-bubble alw-thinking", "aria-label": "Thinking", children: [
474
+ /* @__PURE__ */ jsx2("span", {}),
475
+ /* @__PURE__ */ jsx2("span", {}),
476
+ /* @__PURE__ */ jsx2("span", {})
477
+ ] }) });
478
+ }
479
+ function SendIcon() {
480
+ return /* @__PURE__ */ jsx2("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx2(
481
+ "path",
482
+ {
483
+ d: "M12 19V5m0 0-6 6m6-6 6 6",
484
+ stroke: "currentColor",
485
+ strokeWidth: "2.2",
486
+ strokeLinecap: "round",
487
+ strokeLinejoin: "round"
488
+ }
489
+ ) });
490
+ }
491
+ function fencedChart(children) {
492
+ if (!isValidElement(children)) return null;
493
+ const props = children.props;
494
+ if (!props.className?.split(/\s+/).includes("language-chart")) return null;
495
+ const source = typeof props.children === "string" ? props.children : null;
496
+ return source ? parseChartSpec(source) : null;
497
+ }
498
+ function AgentChat({
499
+ baseUrl,
500
+ agentId,
501
+ publishableKey,
502
+ user,
503
+ title,
504
+ placeholder = "Ask anything\u2026",
505
+ welcomeTitle = "How can I help?",
506
+ welcomeSubtitle = "Replies stream in as the agent works.",
507
+ accentColor,
508
+ persistConversation = true,
509
+ className
510
+ }) {
511
+ const api = `${baseUrl.replace(/\/$/, "")}/v1/embed`;
512
+ const headers = {
513
+ Authorization: `Bearer ${publishableKey}`,
514
+ ...identityHeaders(user)
515
+ };
516
+ const storageKey = conversationStorageKey(agentId, user);
517
+ const rootRef = useRef(null);
518
+ const scrollRef = useRef(null);
519
+ const inputRef = useRef(null);
520
+ const stickToBottomRef = useRef(true);
521
+ const conversationIdRef = useRef(
522
+ persistConversation ? readStored(storageKey) : null
523
+ );
524
+ const [prompt, setPrompt] = useState2("");
525
+ const [agentName, setAgentName] = useState2(null);
526
+ const { messages, sendMessage, status, error, setMessages, clearError, stop } = useChat({
527
+ transport: new DefaultChatTransport({
528
+ api: `${api}/agents/${encodeURIComponent(agentId)}/chat`,
529
+ headers,
530
+ prepareSendMessagesRequest: ({ api: api2, id, messages: messages2, body, trigger, messageId }) => ({
531
+ api: conversationIdRef.current ? `${api2}?conversation_id=${conversationIdRef.current}` : api2,
532
+ body: { ...body, id, messages: messages2, trigger, messageId }
533
+ })
534
+ }),
535
+ onData: (part) => {
536
+ if (part.type === "data-run-info") {
537
+ const info = part.data;
538
+ if (info.conversation_id) {
539
+ conversationIdRef.current = info.conversation_id;
540
+ if (persistConversation) writeStored(storageKey, info.conversation_id);
541
+ }
542
+ }
543
+ }
544
+ });
545
+ useLayoutEffect(() => {
546
+ injectStyles(rootRef.current?.getRootNode());
547
+ }, []);
548
+ useEffect(() => {
549
+ if (title) return;
550
+ let cancelled = false;
551
+ fetch(`${api}/agents/${encodeURIComponent(agentId)}`, { headers }).then((r) => r.ok ? r.json() : null).then((info) => {
552
+ if (!cancelled && info?.name) setAgentName(info.name);
553
+ }).catch(() => {
554
+ });
555
+ return () => {
556
+ cancelled = true;
557
+ };
558
+ }, [agentId, baseUrl, title]);
559
+ useEffect(() => {
560
+ const stored = conversationIdRef.current;
561
+ if (!persistConversation || !stored) return;
562
+ let cancelled = false;
563
+ fetch(`${api}/conversations/${stored}/ui-messages`, { headers }).then((r) => r.ok ? r.json() : null).then((uiMessages) => {
564
+ if (cancelled) return;
565
+ if (uiMessages) setMessages(uiMessages);
566
+ else {
567
+ conversationIdRef.current = null;
568
+ writeStored(storageKey, null);
569
+ }
570
+ }).catch(() => {
571
+ });
572
+ return () => {
573
+ cancelled = true;
574
+ };
575
+ }, []);
576
+ function onScroll() {
577
+ const el = scrollRef.current;
578
+ if (!el) return;
579
+ stickToBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
580
+ }
581
+ useEffect(() => {
582
+ const el = scrollRef.current;
583
+ if (el && stickToBottomRef.current) el.scrollTop = el.scrollHeight;
584
+ }, [messages, status]);
585
+ const busy = status === "submitted" || status === "streaming";
586
+ function autoGrow() {
587
+ const el = inputRef.current;
588
+ if (!el) return;
589
+ el.style.height = "auto";
590
+ el.style.height = `${Math.min(el.scrollHeight, 140)}px`;
591
+ }
592
+ function send() {
593
+ const p = prompt.trim();
594
+ if (!p || busy) return;
595
+ setPrompt("");
596
+ requestAnimationFrame(autoGrow);
597
+ void sendMessage({ text: p });
598
+ }
599
+ function reset() {
600
+ stop();
601
+ setMessages([]);
602
+ clearError();
603
+ conversationIdRef.current = null;
604
+ writeStored(storageKey, null);
605
+ inputRef.current?.focus();
606
+ }
607
+ return /* @__PURE__ */ jsxs2(
608
+ "div",
609
+ {
610
+ ref: rootRef,
611
+ className: className ? `alw-root ${className}` : "alw-root",
612
+ style: accentColor ? { "--alw-accent": accentColor } : void 0,
613
+ children: [
614
+ /* @__PURE__ */ jsxs2("div", { className: "alw-header", children: [
615
+ /* @__PURE__ */ jsx2("p", { className: "alw-title", children: title ?? agentName ?? "Chat" }),
616
+ /* @__PURE__ */ jsx2(
617
+ "button",
618
+ {
619
+ type: "button",
620
+ className: "alw-new",
621
+ onClick: reset,
622
+ disabled: messages.length === 0 && !error,
623
+ children: "New chat"
624
+ }
625
+ )
626
+ ] }),
627
+ /* @__PURE__ */ jsx2("div", { className: "alw-scroll", ref: scrollRef, onScroll, children: messages.length === 0 && !busy ? /* @__PURE__ */ jsxs2("div", { className: "alw-empty", children: [
628
+ /* @__PURE__ */ jsx2("p", { className: "alw-empty-title", children: welcomeTitle }),
629
+ /* @__PURE__ */ jsx2("p", { className: "alw-empty-sub", children: welcomeSubtitle })
630
+ ] }) : /* @__PURE__ */ jsxs2("div", { className: "alw-messages", children: [
631
+ messages.map((m) => {
632
+ const text = messageText(m);
633
+ if (!text && m.role === "assistant") return null;
634
+ const { body, sources } = m.role === "assistant" ? splitReply(text) : { body: text, sources: null };
635
+ return /* @__PURE__ */ jsx2(
636
+ "div",
637
+ {
638
+ className: `alw-msg ${m.role === "user" ? "alw-msg-user" : "alw-msg-assistant"}`,
639
+ children: /* @__PURE__ */ jsx2("div", { className: "alw-bubble", children: m.role === "assistant" ? /* @__PURE__ */ jsxs2("div", { className: "alw-md", children: [
640
+ /* @__PURE__ */ jsx2(
641
+ ReactMarkdown,
642
+ {
643
+ remarkPlugins: [remarkGfm],
644
+ rehypePlugins: [rehypeRaw, rehypeSanitize],
645
+ components: {
646
+ pre: ({ children }) => {
647
+ const spec = fencedChart(children);
648
+ return spec ? /* @__PURE__ */ jsx2(Chart, { spec }) : /* @__PURE__ */ jsx2("pre", { children });
649
+ }
650
+ },
651
+ children: body
652
+ }
653
+ ),
654
+ sources && /* @__PURE__ */ jsxs2("div", { className: "alw-sources", children: [
655
+ /* @__PURE__ */ jsx2("p", { className: "alw-sources-label", children: "Sources" }),
656
+ /* @__PURE__ */ jsx2(
657
+ ReactMarkdown,
658
+ {
659
+ remarkPlugins: [remarkGfm],
660
+ rehypePlugins: [rehypeRaw, rehypeSanitize],
661
+ children: sources
662
+ }
663
+ )
664
+ ] })
665
+ ] }) : text })
666
+ },
667
+ m.id
668
+ );
669
+ }),
670
+ status === "submitted" && /* @__PURE__ */ jsx2(ThinkingDots, {}),
671
+ error && /* @__PURE__ */ jsxs2("p", { className: "alw-error", children: [
672
+ error.message || "Something went wrong.",
673
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: clearError, children: "Dismiss" })
674
+ ] })
675
+ ] }) }),
676
+ /* @__PURE__ */ jsxs2("div", { className: "alw-composer", children: [
677
+ /* @__PURE__ */ jsxs2("div", { className: "alw-inputrow", children: [
678
+ /* @__PURE__ */ jsx2(
679
+ "textarea",
680
+ {
681
+ ref: inputRef,
682
+ className: "alw-input",
683
+ rows: 1,
684
+ value: prompt,
685
+ placeholder,
686
+ onChange: (e) => {
687
+ setPrompt(e.target.value);
688
+ autoGrow();
689
+ },
690
+ onKeyDown: (e) => {
691
+ if (e.key === "Enter" && !e.shiftKey) {
692
+ e.preventDefault();
693
+ send();
694
+ }
695
+ }
696
+ }
697
+ ),
698
+ /* @__PURE__ */ jsx2(
699
+ "button",
700
+ {
701
+ type: "button",
702
+ className: "alw-send",
703
+ onClick: send,
704
+ disabled: !prompt.trim() || busy,
705
+ "aria-label": "Send",
706
+ children: /* @__PURE__ */ jsx2(SendIcon, {})
707
+ }
708
+ )
709
+ ] }),
710
+ /* @__PURE__ */ jsx2("p", { className: "alw-powered", children: "Powered by agentlib" })
711
+ ] })
712
+ ]
713
+ }
714
+ );
715
+ }
716
+ export {
717
+ AGENT_CHAT_CSS,
718
+ AgentChat,
719
+ getOrCreateVisitorId,
720
+ identityHeaders,
721
+ injectStyles
722
+ };
723
+ //# sourceMappingURL=index.js.map