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