@aegishex/chatbot 0.0.0-stage → 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,821 @@
1
+ // src/sse.ts
2
+ var SseParser = class {
3
+ constructor() {
4
+ this.buffer = "";
5
+ }
6
+ push(chunk) {
7
+ this.buffer += chunk.replace(/\r\n?/g, "\n");
8
+ const events = [];
9
+ let boundary = this.buffer.indexOf("\n\n");
10
+ while (boundary !== -1) {
11
+ const block = this.buffer.slice(0, boundary);
12
+ this.buffer = this.buffer.slice(boundary + 2);
13
+ const parsed = parseBlock(block);
14
+ if (parsed) events.push(parsed);
15
+ boundary = this.buffer.indexOf("\n\n");
16
+ }
17
+ return events;
18
+ }
19
+ };
20
+ function parseBlock(block) {
21
+ let event = "message";
22
+ const data = [];
23
+ let id;
24
+ let retry;
25
+ for (const line of block.split("\n")) {
26
+ if (!line || line.startsWith(":")) continue;
27
+ const colon = line.indexOf(":");
28
+ const field = colon === -1 ? line : line.slice(0, colon);
29
+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
30
+ if (field === "event") event = value;
31
+ else if (field === "data") data.push(value);
32
+ else if (field === "id") id = value;
33
+ else if (field === "retry" && /^\d+$/.test(value)) retry = Number(value);
34
+ }
35
+ if (!data.length && retry === void 0) return null;
36
+ return { event, data: data.join("\n"), id, retry };
37
+ }
38
+
39
+ // src/types.ts
40
+ var FINAL_PHASES = /* @__PURE__ */ new Set(["completed", "failed", "denied", "cancelled"]);
41
+
42
+ // src/client.ts
43
+ var ChatbotError = class extends Error {
44
+ constructor(message, status, retryAfterS = null) {
45
+ super(message);
46
+ this.name = "ChatbotError";
47
+ this.status = status;
48
+ this.retryAfterS = retryAfterS;
49
+ }
50
+ /** True when retrying the same request can succeed (network trouble, rate limits, server errors). */
51
+ get retryable() {
52
+ return this.status === 0 || this.status === 429 || this.status >= 500;
53
+ }
54
+ };
55
+ var STREAM_FAILURES_BEFORE_POLLING = 3;
56
+ var POLL_INTERVAL_MS = 2e3;
57
+ var MAX_BACKOFF_MS = 15e3;
58
+ var VISITOR_STORAGE_KEY = "aegishex:visitor-id";
59
+ function newIdempotencyKey() {
60
+ const random = globalThis.crypto?.randomUUID?.();
61
+ return random ?? `msg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
62
+ }
63
+ function getOrCreateVisitorId() {
64
+ try {
65
+ const existing = globalThis.sessionStorage?.getItem(VISITOR_STORAGE_KEY);
66
+ if (existing && existing.length >= 16) return existing;
67
+ const generated = newIdempotencyKey();
68
+ globalThis.sessionStorage?.setItem(VISITOR_STORAGE_KEY, generated);
69
+ return generated;
70
+ } catch {
71
+ return newIdempotencyKey();
72
+ }
73
+ }
74
+ function sleep(ms, signal) {
75
+ return new Promise((resolve, reject) => {
76
+ if (signal?.aborted) return reject(abortError());
77
+ const timer = setTimeout(() => {
78
+ signal?.removeEventListener("abort", onAbort);
79
+ resolve();
80
+ }, ms);
81
+ const onAbort = () => {
82
+ clearTimeout(timer);
83
+ reject(abortError());
84
+ };
85
+ signal?.addEventListener("abort", onAbort, { once: true });
86
+ });
87
+ }
88
+ function abortError() {
89
+ const error = new Error("Stopped following the run.");
90
+ error.name = "AbortError";
91
+ return error;
92
+ }
93
+ var AegisHexClient = class {
94
+ constructor(options) {
95
+ if (!options.publishableKey?.startsWith("ahx_pk_")) {
96
+ throw new ChatbotError("A publishable widget key (ahx_pk_\u2026) is required.", 0);
97
+ }
98
+ this.base = options.apiBaseUrl.replace(/\/+$/, "");
99
+ this.key = options.publishableKey;
100
+ this.visitorId = getOrCreateVisitorId();
101
+ const fetchImpl = options.fetch ?? globalThis.fetch;
102
+ if (!fetchImpl) throw new ChatbotError("fetch is not available in this environment.", 0);
103
+ this.fetchImpl = fetchImpl.bind(globalThis);
104
+ }
105
+ /** Assistant name, greeting, accent colour and message limits configured for this key. */
106
+ getConfig() {
107
+ return this.json("GET", "/api/client/v1/config");
108
+ }
109
+ /** Send a message. It starts one agent run; keep `runToken` to follow it. */
110
+ sendMessage(message, options = {}) {
111
+ return this.json(
112
+ "POST",
113
+ "/api/client/v1/runs",
114
+ { message },
115
+ { "Idempotency-Key": options.idempotencyKey ?? newIdempotencyKey(), "X-Visitor-Id": this.visitorId }
116
+ );
117
+ }
118
+ /** Current view of a run (the polling fallback). */
119
+ getRun(runId, runToken) {
120
+ return this.json(
121
+ "GET",
122
+ `/api/client/v1/runs/${encodeURIComponent(runId)}`,
123
+ void 0,
124
+ { "X-Run-Token": runToken }
125
+ );
126
+ }
127
+ /** Stop an unfinished run; a pending approval is withdrawn and nothing is executed. */
128
+ cancelRun(runId, runToken) {
129
+ return this.json(
130
+ "POST",
131
+ `/api/client/v1/runs/${encodeURIComponent(runId)}/cancel`,
132
+ void 0,
133
+ { "X-Run-Token": runToken, "Idempotency-Key": newIdempotencyKey() }
134
+ );
135
+ }
136
+ /**
137
+ * Follow a run until it finishes and resolve with the final view.
138
+ *
139
+ * Uses the Server-Sent Events stream and reconnects after network drops (the first event after a reconnect
140
+ * is always the current state, so nothing is missed). After repeated stream failures it falls back to polling.
141
+ */
142
+ async followRun(runId, runToken, options) {
143
+ const { onUpdate, signal } = options;
144
+ let failures = 0;
145
+ let retryMs = 2e3;
146
+ while (failures < STREAM_FAILURES_BEFORE_POLLING) {
147
+ if (signal?.aborted) throw abortError();
148
+ try {
149
+ const outcome = await this.readStream(runId, runToken, onUpdate, signal, (ms) => {
150
+ retryMs = ms;
151
+ });
152
+ if (outcome) return outcome;
153
+ failures = 0;
154
+ await sleep(250, signal);
155
+ } catch (error) {
156
+ if (error.name === "AbortError") throw error;
157
+ if (error instanceof ChatbotError && !error.retryable) throw error;
158
+ failures += 1;
159
+ await sleep(Math.min(retryMs * 2 ** (failures - 1), MAX_BACKOFF_MS), signal);
160
+ }
161
+ }
162
+ return this.pollRun(runId, runToken, onUpdate, signal);
163
+ }
164
+ async readStream(runId, runToken, onUpdate, signal, onRetry) {
165
+ const response = await this.request(
166
+ "GET",
167
+ `/api/client/v1/runs/${encodeURIComponent(runId)}/events`,
168
+ void 0,
169
+ { "X-Run-Token": runToken, Accept: "text/event-stream" },
170
+ signal
171
+ );
172
+ if (!response.body) throw new ChatbotError("Streaming is not supported here.", 0);
173
+ const reader = response.body.getReader();
174
+ const decoder = new TextDecoder();
175
+ const parser = new SseParser();
176
+ try {
177
+ for (; ; ) {
178
+ const { value, done } = await reader.read();
179
+ if (done) return null;
180
+ for (const event of parser.push(decoder.decode(value, { stream: true }))) {
181
+ if (event.retry !== void 0) onRetry(event.retry);
182
+ if (event.event === "snapshot" || event.event === "end") {
183
+ const view = JSON.parse(event.data);
184
+ onUpdate(view);
185
+ if (event.event === "end" || FINAL_PHASES.has(view.phase)) return view;
186
+ } else if (event.event === "gone") {
187
+ throw new ChatbotError("This conversation is no longer available.", 404);
188
+ }
189
+ }
190
+ }
191
+ } finally {
192
+ reader.cancel().catch(() => void 0);
193
+ }
194
+ }
195
+ async pollRun(runId, runToken, onUpdate, signal) {
196
+ let previous = "";
197
+ for (; ; ) {
198
+ try {
199
+ const view = await this.getRun(runId, runToken);
200
+ const serialized = JSON.stringify(view);
201
+ if (serialized !== previous) {
202
+ previous = serialized;
203
+ onUpdate(view);
204
+ }
205
+ if (FINAL_PHASES.has(view.phase)) return view;
206
+ } catch (error) {
207
+ if (error instanceof ChatbotError && !error.retryable) throw error;
208
+ }
209
+ await sleep(POLL_INTERVAL_MS, signal);
210
+ }
211
+ }
212
+ async json(method, path, body, headers = {}) {
213
+ const response = await this.request(method, path, body, headers);
214
+ return await response.json();
215
+ }
216
+ async request(method, path, body, headers, signal) {
217
+ let response;
218
+ try {
219
+ response = await this.fetchImpl(`${this.base}${path}`, {
220
+ method,
221
+ headers: {
222
+ "X-AegisHex-Key": this.key,
223
+ ...body === void 0 ? {} : { "Content-Type": "application/json" },
224
+ ...headers
225
+ },
226
+ body: body === void 0 ? void 0 : JSON.stringify(body),
227
+ credentials: "omit",
228
+ signal
229
+ });
230
+ } catch (error) {
231
+ if (error.name === "AbortError") throw error;
232
+ throw new ChatbotError("Can't reach the assistant right now. Check your connection and try again.", 0);
233
+ }
234
+ if (!response.ok) throw await toError(response);
235
+ return response;
236
+ }
237
+ };
238
+ async function toError(response) {
239
+ const retryHeader = response.headers.get("Retry-After");
240
+ const retryAfter = retryHeader && /^\d+$/.test(retryHeader) ? Number(retryHeader) : null;
241
+ let message = "Something went wrong. Please try again.";
242
+ try {
243
+ const body = await response.json();
244
+ if (typeof body.message === "string" && body.message) message = body.message;
245
+ const reason = body.details?.[0]?.reason;
246
+ if (response.status === 422 && typeof reason === "string") message = reason.replace(/^Value error, /, "");
247
+ } catch {
248
+ }
249
+ return new ChatbotError(message, response.status, retryAfter);
250
+ }
251
+
252
+ // src/styles.ts
253
+ var LIGHT = `
254
+ --ah-bg: #ffffff; --ah-surface: #f6f8fc; --ah-surface-2: #eef1f7; --ah-text: #17233b; --ah-muted: #596a80;
255
+ --ah-border: #e3e8f0; --ah-shadow: 0 18px 48px rgba(23, 35, 59, .18), 0 2px 8px rgba(23, 35, 59, .08);
256
+ --ah-good: #0b7f66; --ah-good-bg: #e6f6f1; --ah-warn: #8a5a00; --ah-warn-bg: #fff6e0; --ah-warn-border: #f2d48a;
257
+ --ah-bad: #b42335; --ah-bad-bg: #fdecef;`;
258
+ var DARK = `
259
+ --ah-bg: #111a2c; --ah-surface: #172238; --ah-surface-2: #1e2b45; --ah-text: #e6ebf5; --ah-muted: #a3b0c4;
260
+ --ah-border: #2a3954; --ah-shadow: 0 18px 48px rgba(0, 0, 0, .5), 0 2px 8px rgba(0, 0, 0, .35);
261
+ --ah-good: #6fdcbc; --ah-good-bg: #12352f; --ah-warn: #f5c868; --ah-warn-bg: #3a2f14; --ah-warn-border: #6b5520;
262
+ --ah-bad: #ff9aa8; --ah-bad-bg: #3d1a24;`;
263
+ var STYLES = `
264
+ :host { all: initial; ${LIGHT} --ah-accent: #5364dd; --ah-on-accent: #ffffff; --ah-z: 2147483000;
265
+ font-family: "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif; }
266
+ :host([data-theme="dark"]) { ${DARK} }
267
+ @media (prefers-color-scheme: dark) { :host([data-theme="auto"]) { ${DARK} } }
268
+ *, *::before, *::after { box-sizing: border-box; }
269
+ button, textarea { font: inherit; color: inherit; }
270
+ .root { position: fixed; bottom: 20px; right: 20px; z-index: var(--ah-z); display: flex; flex-direction: column;
271
+ align-items: flex-end; gap: 14px; }
272
+ .root.left { right: auto; left: 20px; align-items: flex-start; }
273
+ .root.inline { position: static; display: block; height: 100%; }
274
+ .launcher { width: 58px; height: 58px; border-radius: 50%; border: 0; cursor: pointer; background: var(--ah-accent);
275
+ color: var(--ah-on-accent); display: grid; place-items: center; box-shadow: var(--ah-shadow);
276
+ transition: transform .15s ease, box-shadow .15s ease; }
277
+ .launcher:hover { transform: translateY(-2px); }
278
+ .launcher:focus-visible, button:focus-visible { outline: 3px solid color-mix(in srgb, var(--ah-accent) 45%, transparent); outline-offset: 2px; }
279
+ .launcher svg { width: 26px; height: 26px; }
280
+ .panel { width: min(390px, calc(100vw - 32px)); height: min(620px, calc(100vh - 110px)); background: var(--ah-bg);
281
+ color: var(--ah-text); border: 1px solid var(--ah-border); border-radius: 18px; box-shadow: var(--ah-shadow);
282
+ display: flex; flex-direction: column; overflow: hidden; transform-origin: bottom right;
283
+ animation: ah-pop .18s ease-out; }
284
+ .root.left .panel { transform-origin: bottom left; }
285
+ .root.inline .panel { width: 100%; height: 100%; min-height: 420px; box-shadow: none; animation: none; }
286
+ .panel[hidden] { display: none; }
287
+ @keyframes ah-pop { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
288
+ .header { display: flex; align-items: center; gap: 11px; padding: 14px 14px 14px 16px; border-bottom: 1px solid var(--ah-border);
289
+ background: linear-gradient(180deg, color-mix(in srgb, var(--ah-accent) 9%, var(--ah-bg)), var(--ah-bg)); }
290
+ .mark { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; flex: none;
291
+ background: var(--ah-accent); color: var(--ah-on-accent); }
292
+ .mark svg { width: 20px; height: 20px; }
293
+ .titles { flex: 1; min-width: 0; }
294
+ .title { font-size: 15px; font-weight: 700; line-height: 1.25; margin: 0; }
295
+ .subtitle { font-size: 12px; color: var(--ah-muted); display: flex; align-items: center; gap: 6px; margin-top: 2px; }
296
+ .online { width: 7px; height: 7px; border-radius: 50%; background: var(--ah-good); }
297
+ .icon-btn { width: 34px; height: 34px; border-radius: 9px; border: 0; background: transparent; cursor: pointer;
298
+ color: var(--ah-muted); display: grid; place-items: center; }
299
+ .icon-btn:hover { background: var(--ah-surface-2); color: var(--ah-text); }
300
+ .icon-btn svg { width: 18px; height: 18px; }
301
+ .log { flex: 1; overflow-y: auto; padding: 16px 14px 8px; display: flex; flex-direction: column; gap: 12px;
302
+ scroll-behavior: smooth; overscroll-behavior: contain; }
303
+ .row { display: flex; }
304
+ .row.user { justify-content: flex-end; }
305
+ .bubble { max-width: 86%; padding: 10px 13px; border-radius: 14px; font-size: 14px; line-height: 1.5;
306
+ white-space: pre-wrap; overflow-wrap: anywhere; }
307
+ .row.user .bubble { background: var(--ah-accent); color: var(--ah-on-accent); border-bottom-right-radius: 5px; }
308
+ .row.bot .bubble { background: var(--ah-surface); border: 1px solid var(--ah-border); border-bottom-left-radius: 5px; }
309
+ .card { width: 100%; max-width: 92%; background: var(--ah-surface); border: 1px solid var(--ah-border);
310
+ border-radius: 14px; border-bottom-left-radius: 5px; padding: 12px 13px; font-size: 14px; line-height: 1.5; }
311
+ .answer { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
312
+ .support-link { align-self: flex-start; color: inherit; font-weight: 600; text-decoration: underline; }
313
+ .status { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--ah-muted);
314
+ margin-bottom: 8px; letter-spacing: .01em; }
315
+ .badge { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: 999px; font-size: 11.5px;
316
+ font-weight: 600; }
317
+ .badge svg { width: 12px; height: 12px; }
318
+ .badge.good { background: var(--ah-good-bg); color: var(--ah-good); }
319
+ .badge.warn { background: var(--ah-warn-bg); color: var(--ah-warn); }
320
+ .badge.bad { background: var(--ah-bad-bg); color: var(--ah-bad); }
321
+ .badge.busy { background: var(--ah-surface-2); color: var(--ah-muted); }
322
+ .steps { list-style: none; margin: 10px 0 0; padding: 10px 0 0; border-top: 1px dashed var(--ah-border);
323
+ display: flex; flex-direction: column; gap: 6px; }
324
+ .steps li { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--ah-muted); }
325
+ .steps li.done { color: var(--ah-text); }
326
+ .steps .dot { width: 16px; height: 16px; flex: none; display: grid; place-items: center; border-radius: 50%; }
327
+ .steps li.done .dot { background: var(--ah-good-bg); color: var(--ah-good); }
328
+ .steps li.problem .dot { background: var(--ah-bad-bg); color: var(--ah-bad); }
329
+ .steps .dot svg { width: 10px; height: 10px; }
330
+ .spinner { width: 12px; height: 12px; border: 2px solid var(--ah-border); border-top-color: var(--ah-accent);
331
+ border-radius: 50%; animation: ah-spin .8s linear infinite; }
332
+ @keyframes ah-spin { to { transform: rotate(360deg); } }
333
+ .typing { display: inline-flex; gap: 4px; padding: 2px 0; }
334
+ .typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--ah-muted); opacity: .5;
335
+ animation: ah-blink 1.2s infinite ease-in-out; }
336
+ .typing span:nth-child(2) { animation-delay: .15s; } .typing span:nth-child(3) { animation-delay: .3s; }
337
+ @keyframes ah-blink { 0%, 80%, 100% { opacity: .25; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-2px); } }
338
+ .approval { margin-top: 10px; padding: 11px 12px; border-radius: 11px; background: var(--ah-warn-bg);
339
+ border: 1px solid var(--ah-warn-border); color: var(--ah-text); }
340
+ .approval strong { display: block; font-size: 13px; margin-bottom: 3px; text-transform: capitalize; }
341
+ .approval p { margin: 0; font-size: 12.5px; color: var(--ah-muted); }
342
+ .facts { margin: 10px 0 0; padding: 0; display: grid; grid-template-columns: fit-content(45%) minmax(0, 1fr);
343
+ gap: 6px 12px; font-size: 13px; }
344
+ .facts dt { color: var(--ah-muted); overflow-wrap: anywhere; }
345
+ .facts dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; }
346
+ .facts .passage { grid-column: 1 / -1; }
347
+ .facts dt.passage:not(:first-child) { margin-top: 6px; }
348
+ .facts dd.passage { white-space: pre-wrap; font-weight: 400; }
349
+ .sources { margin-top: 10px; font-size: 12px; color: var(--ah-muted); }
350
+ .sources summary { cursor: pointer; width: fit-content; }
351
+ .sources dd { color: var(--ah-text); }
352
+ .card-actions { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; gap: 8px; }
353
+ .ref { font-size: 11.5px; color: var(--ah-muted); }
354
+ .link-btn { border: 0; background: none; padding: 0; color: var(--ah-accent); font-size: 12.5px; font-weight: 600; cursor: pointer; }
355
+ .link-btn:hover { text-decoration: underline; }
356
+ .notice { margin: 0 14px 8px; padding: 9px 12px; border-radius: 10px; font-size: 12.5px; line-height: 1.45;
357
+ background: var(--ah-bad-bg); color: var(--ah-bad); }
358
+ .notice[hidden] { display: none; }
359
+ .composer { border-top: 1px solid var(--ah-border); padding: 10px 12px 8px; background: var(--ah-bg); }
360
+ .input-row { display: flex; align-items: flex-end; gap: 8px; background: var(--ah-surface); border: 1px solid var(--ah-border);
361
+ border-radius: 14px; padding: 6px 6px 6px 12px; transition: border-color .15s; }
362
+ .input-row:focus-within { border-color: var(--ah-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ah-accent) 22%, transparent); }
363
+ textarea { flex: 1; border: 0; background: transparent; resize: none; outline: none; box-shadow: none; font-size: 14px; line-height: 1.45;
364
+ max-height: 120px; min-height: 22px; padding: 6px 0; }
365
+ textarea::placeholder { color: var(--ah-muted); }
366
+ .send { width: 36px; height: 36px; flex: none; border: 0; border-radius: 10px; background: var(--ah-accent);
367
+ color: var(--ah-on-accent); cursor: pointer; display: grid; place-items: center; transition: opacity .15s; }
368
+ .send:disabled { opacity: .45; cursor: not-allowed; }
369
+ .send svg { width: 17px; height: 17px; }
370
+ .quick-action { margin: 0 0 8px; padding: 5px 10px; border: 1px solid var(--ah-border); border-radius: 999px;
371
+ background: var(--ah-surface); color: var(--ah-text); cursor: pointer; font-size: 12px; font-weight: 600; }
372
+ .quick-action:hover { border-color: var(--ah-accent); }
373
+ .foot { display: flex; justify-content: space-between; gap: 8px; margin-top: 6px; font-size: 11px; color: var(--ah-muted); }
374
+ .foot b { font-weight: 700; color: var(--ah-text); }
375
+ .foot b span { color: #0e9f80; }
376
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
377
+ @media (max-width: 480px) {
378
+ .root:not(.inline) { bottom: 12px; right: 12px; left: 12px; align-items: flex-end; }
379
+ .root:not(.inline) .panel { width: 100%; height: calc(100vh - 96px); }
380
+ }
381
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
382
+ `;
383
+
384
+ // src/widget.ts
385
+ var ICONS = {
386
+ chat: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12Z"/></svg>',
387
+ close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',
388
+ send: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>',
389
+ mark: '<svg viewBox="0 0 40 40" fill="none" aria-hidden="true"><path d="M20 3 34.5 11.5v17L20 37 5.5 28.5v-17L20 3Z" stroke="currentColor" stroke-width="3"/><path d="m14.8 20 3.4 3.4 7.2-7.2" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>',
390
+ check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12.5 4.5 4.5L19 7.5"/></svg>',
391
+ alert: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" aria-hidden="true"><path d="M12 7v6M12 17h.01"/></svg>',
392
+ clock: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></svg>'
393
+ };
394
+ var DEFAULT_CONFIG = {
395
+ assistantName: "Assistant",
396
+ greeting: "Hi! How can I help?",
397
+ accentColor: "#5364dd",
398
+ organization: "",
399
+ minMessageLength: 2,
400
+ maxMessageLength: 2e3
401
+ };
402
+ function el(tag, className, text) {
403
+ const node = document.createElement(tag);
404
+ if (className) node.className = className;
405
+ if (text !== void 0) node.textContent = text;
406
+ return node;
407
+ }
408
+ function icon(name) {
409
+ const span = el("span");
410
+ span.style.display = "contents";
411
+ span.innerHTML = ICONS[name];
412
+ return span;
413
+ }
414
+ function readableOn(hex) {
415
+ const match = /^#([0-9a-f]{6})$/i.exec(hex);
416
+ if (!match) return "#ffffff";
417
+ const channels = [0, 2, 4].map((offset) => parseInt(match[1].slice(offset, offset + 2), 16) / 255).map((c) => c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
418
+ const luminance = 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
419
+ return luminance > 0.36 ? "#111827" : "#ffffff";
420
+ }
421
+ var counter = 0;
422
+ var nextId = () => `m${Date.now().toString(36)}${counter += 1}`;
423
+ function mountChatbot(options) {
424
+ const client = new AegisHexClient(options);
425
+ const inline = Boolean(options.target);
426
+ const storageKey = `aegishex-chat:${options.publishableKey.slice(-12)}`;
427
+ const persist = options.persist !== false;
428
+ const host = el("div");
429
+ host.setAttribute("data-aegishex-chatbot", "");
430
+ host.setAttribute("data-theme", options.theme ?? "auto");
431
+ const shadow = host.attachShadow({ mode: "open" });
432
+ const style = el("style");
433
+ style.textContent = STYLES;
434
+ shadow.append(style);
435
+ const root = el("div", `root${options.position === "bottom-left" ? " left" : ""}${inline ? " inline" : ""}`);
436
+ const panel = el("section", "panel");
437
+ panel.setAttribute("role", inline ? "region" : "dialog");
438
+ panel.setAttribute("aria-label", "Chat");
439
+ if (!inline) panel.hidden = true;
440
+ const header = el("header", "header");
441
+ const mark = el("div", "mark");
442
+ mark.append(icon("mark"));
443
+ const titles = el("div", "titles");
444
+ const title = el("h2", "title", DEFAULT_CONFIG.assistantName);
445
+ const subtitle = el("div", "subtitle");
446
+ const online = el("span", "online");
447
+ const subtitleText = el("span", void 0, "Verified answers");
448
+ subtitle.append(online, subtitleText);
449
+ titles.append(title, subtitle);
450
+ header.append(mark, titles);
451
+ let closeButton = null;
452
+ if (!inline) {
453
+ closeButton = el("button", "icon-btn");
454
+ closeButton.type = "button";
455
+ closeButton.setAttribute("aria-label", "Close chat");
456
+ closeButton.append(icon("close"));
457
+ header.append(closeButton);
458
+ }
459
+ const log = el("div", "log");
460
+ log.setAttribute("role", "log");
461
+ log.setAttribute("aria-live", "polite");
462
+ log.setAttribute("aria-relevant", "additions text");
463
+ const notice = el("p", "notice");
464
+ notice.setAttribute("role", "alert");
465
+ notice.hidden = true;
466
+ const composer = el("form", "composer");
467
+ const inputRow = el("div", "input-row");
468
+ const label = el("label", "sr-only", "Message");
469
+ const input = el("textarea");
470
+ input.rows = 1;
471
+ input.placeholder = "Type your message\u2026";
472
+ input.id = "aegishex-input";
473
+ label.htmlFor = input.id;
474
+ const send = el("button", "send");
475
+ send.type = "submit";
476
+ send.setAttribute("aria-label", "Send message");
477
+ send.append(icon("send"));
478
+ inputRow.append(label, input, send);
479
+ const foot = el("div", "foot");
480
+ const hint = el("span", void 0, "Enter to send \xB7 Shift+Enter for a new line");
481
+ const powered = el("span");
482
+ powered.append(document.createTextNode("Powered by "));
483
+ const brand = el("b", void 0, "aegis");
484
+ brand.append(el("span", void 0, "hex"));
485
+ powered.append(brand);
486
+ foot.append(hint, powered);
487
+ if (options.quickAction) {
488
+ const { label: label2, onSelect } = options.quickAction;
489
+ const action = el("button", "quick-action", label2);
490
+ action.type = "button";
491
+ action.addEventListener("click", onSelect);
492
+ composer.append(action);
493
+ }
494
+ composer.append(inputRow, foot);
495
+ panel.append(header, log, notice, composer);
496
+ let launcher = null;
497
+ if (!inline) {
498
+ launcher = el("button", "launcher");
499
+ launcher.type = "button";
500
+ launcher.setAttribute("aria-label", "Open chat");
501
+ launcher.setAttribute("aria-expanded", "false");
502
+ launcher.append(icon("chat"));
503
+ }
504
+ root.append(panel);
505
+ if (launcher) root.append(launcher);
506
+ shadow.append(root);
507
+ (options.target ?? document.body).append(host);
508
+ let config = DEFAULT_CONFIG;
509
+ let entries = loadEntries();
510
+ let sending = false;
511
+ const following = /* @__PURE__ */ new Map();
512
+ let destroyed = false;
513
+ function applyConfig(next) {
514
+ config = next;
515
+ const accent = options.accentColor && /^#[0-9a-f]{6}$/i.test(options.accentColor) ? options.accentColor : next.accentColor;
516
+ host.style.setProperty("--ah-accent", accent);
517
+ host.style.setProperty("--ah-on-accent", readableOn(accent));
518
+ title.textContent = next.assistantName;
519
+ subtitleText.textContent = next.organization ? `${next.organization} \xB7 verified answers` : "Verified answers";
520
+ input.maxLength = next.maxMessageLength;
521
+ render();
522
+ }
523
+ function loadEntries() {
524
+ if (!persist) return [];
525
+ try {
526
+ const raw = window.sessionStorage.getItem(storageKey);
527
+ const parsed = raw ? JSON.parse(raw) : [];
528
+ return Array.isArray(parsed) ? parsed.slice(-50) : [];
529
+ } catch {
530
+ return [];
531
+ }
532
+ }
533
+ function save() {
534
+ if (!persist) return;
535
+ try {
536
+ window.sessionStorage.setItem(storageKey, JSON.stringify(entries.slice(-50)));
537
+ } catch {
538
+ }
539
+ }
540
+ function activeRun() {
541
+ return entries.find((entry) => entry.kind === "run" && !FINAL_PHASES.has(entry.view.phase));
542
+ }
543
+ function showNotice(message) {
544
+ notice.textContent = message ?? "";
545
+ notice.hidden = !message;
546
+ }
547
+ function updateComposer() {
548
+ const busy = sending || Boolean(activeRun());
549
+ const length = input.value.trim().length;
550
+ send.disabled = busy || length < config.minMessageLength;
551
+ input.disabled = sending;
552
+ if (busy) hint.textContent = "Waiting for the current request to finish\u2026";
553
+ else if (length > 0 && length < config.minMessageLength) hint.textContent = `Add a little more detail (${config.minMessageLength - length} more characters).`;
554
+ else hint.textContent = "Enter to send \xB7 Shift+Enter for a new line";
555
+ }
556
+ function renderRun(entry) {
557
+ const { view } = entry;
558
+ const card = el("div", "card");
559
+ card.setAttribute("data-phase", view.phase);
560
+ const status = el("div", "status");
561
+ const badge = (kind, text, glyph) => {
562
+ const node = el("span", `badge ${kind}`);
563
+ if (glyph) node.append(icon(glyph));
564
+ else if (kind === "busy") node.append(el("span", "spinner"));
565
+ node.append(document.createTextNode(text));
566
+ return node;
567
+ };
568
+ if (view.phase === "working") {
569
+ status.append(badge("busy", view.steps.length ? "Working on it" : "Thinking\u2026"));
570
+ } else if (view.phase === "awaiting_approval") status.append(badge("warn", "Waiting for approval", "clock"));
571
+ else if (view.phase === "completed") status.append(badge("good", view.facts.length ? "Verified" : "Done", "check"));
572
+ else if (view.phase === "denied") status.append(badge("bad", "Declined", "alert"));
573
+ else if (view.phase === "cancelled") status.append(badge("bad", "Stopped", "alert"));
574
+ else status.append(badge("bad", "Couldn't finish", "alert"));
575
+ card.append(status);
576
+ if (view.phase === "working" && !view.steps.length) {
577
+ const typing = el("span", "typing");
578
+ typing.setAttribute("aria-label", "Working");
579
+ typing.append(el("span"), el("span"), el("span"));
580
+ card.append(typing);
581
+ } else {
582
+ card.append(el("p", "answer", view.answer));
583
+ if (view.supportUrl && /^https?:\/\//i.test(view.supportUrl)) {
584
+ const support = el("a", "support-link", "Contact support");
585
+ support.href = view.supportUrl;
586
+ support.target = "_blank";
587
+ support.rel = "noopener noreferrer";
588
+ card.append(support);
589
+ }
590
+ }
591
+ if (view.approval && view.phase === "awaiting_approval") {
592
+ const box = el("div", "approval");
593
+ box.append(el("strong", void 0, view.approval.amount ? `${view.approval.action} \xB7 ${view.approval.amount}` : view.approval.action));
594
+ box.append(el("p", void 0, `A person on the ${config.organization || "site"} team reviews this before anything happens.`));
595
+ card.append(box);
596
+ }
597
+ if (view.facts.length && (view.phase === "completed" || view.phase === "awaiting_approval")) {
598
+ const facts = el("dl", "facts");
599
+ for (const fact of view.facts) {
600
+ const className = fact.label.startsWith("Source: ") ? "passage" : void 0;
601
+ facts.append(el("dt", className, fact.label), el("dd", className, fact.value));
602
+ }
603
+ if (view.sourcesCollapsible) {
604
+ const sources = el("details", "sources");
605
+ sources.append(el("summary", void 0, view.facts.length === 1 ? "View source" : "View sources"), facts);
606
+ card.append(sources);
607
+ } else {
608
+ card.append(facts);
609
+ }
610
+ }
611
+ if (view.steps.length && !FINAL_PHASES.has(view.phase)) {
612
+ const steps = el("ul", "steps");
613
+ steps.setAttribute("aria-label", "Progress");
614
+ for (const step of view.steps) {
615
+ const item = el("li", step.status);
616
+ const dot = el("span", "dot");
617
+ if (step.status === "done") dot.append(icon("check"));
618
+ else if (step.status === "problem") dot.append(icon("alert"));
619
+ else dot.append(el("span", "spinner"));
620
+ item.append(dot, document.createTextNode(step.label));
621
+ steps.append(item);
622
+ }
623
+ card.append(steps);
624
+ }
625
+ const actions = el("div", "card-actions");
626
+ if (!view.runId.startsWith("greet-")) {
627
+ actions.append(el("span", "ref", `Ref ${view.reference}`));
628
+ }
629
+ if (!FINAL_PHASES.has(view.phase)) {
630
+ const stop = el("button", "link-btn", "Stop request");
631
+ stop.type = "button";
632
+ stop.addEventListener("click", () => void stopRun(entry));
633
+ actions.append(stop);
634
+ }
635
+ if (actions.childElementCount > 0) card.append(actions);
636
+ return card;
637
+ }
638
+ function render() {
639
+ const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
640
+ log.replaceChildren();
641
+ const greeting = el("div", "row bot");
642
+ greeting.append(el("div", "bubble", config.greeting));
643
+ log.append(greeting);
644
+ for (const entry of entries) {
645
+ const row = el("div", `row ${entry.kind === "user" ? "user" : "bot"}`);
646
+ if (entry.kind === "run") row.append(renderRun(entry));
647
+ else row.append(el("div", "bubble", entry.text));
648
+ log.append(row);
649
+ }
650
+ if (nearBottom || sending) log.scrollTop = log.scrollHeight;
651
+ updateComposer();
652
+ }
653
+ function follow(entry) {
654
+ if (following.has(entry.runId) || FINAL_PHASES.has(entry.view.phase)) return;
655
+ const controller = new AbortController();
656
+ following.set(entry.runId, controller);
657
+ client.followRun(entry.runId, entry.runToken, {
658
+ signal: controller.signal,
659
+ onUpdate: (view) => {
660
+ entry.view = view;
661
+ save();
662
+ render();
663
+ }
664
+ }).catch((error) => {
665
+ if (error.name === "AbortError" || destroyed) return;
666
+ showNotice(error instanceof ChatbotError ? error.message : "Lost track of this request. Reload to try again.");
667
+ }).finally(() => {
668
+ following.delete(entry.runId);
669
+ render();
670
+ });
671
+ }
672
+ async function stopRun(entry) {
673
+ try {
674
+ entry.view = await client.cancelRun(entry.runId, entry.runToken);
675
+ following.get(entry.runId)?.abort();
676
+ save();
677
+ render();
678
+ } catch (error) {
679
+ showNotice(error instanceof ChatbotError ? error.message : "Couldn't stop the request.");
680
+ }
681
+ }
682
+ let promptHistory = [];
683
+ let historyIndex = -1;
684
+ let draft = "";
685
+ async function sendMessage(text) {
686
+ const message = text.trim();
687
+ if (sending || activeRun() || message.length < config.minMessageLength) return;
688
+ if (promptHistory[promptHistory.length - 1] !== message) promptHistory.push(message);
689
+ historyIndex = -1;
690
+ draft = "";
691
+ sending = true;
692
+ showNotice(null);
693
+ const userEntry = { kind: "user", id: nextId(), text: message };
694
+ entries.push(userEntry);
695
+ input.value = "";
696
+ autosize();
697
+ render();
698
+ try {
699
+ const started = await client.sendMessage(message);
700
+ const runEntry = {
701
+ kind: "run",
702
+ id: nextId(),
703
+ runId: started.run.runId,
704
+ runToken: started.runToken,
705
+ view: started.run
706
+ };
707
+ entries.push(runEntry);
708
+ save();
709
+ follow(runEntry);
710
+ } catch (error) {
711
+ entries = entries.filter((entry) => entry !== userEntry);
712
+ input.value = message;
713
+ autosize();
714
+ const wait = error instanceof ChatbotError && error.retryAfterS ? ` (${error.retryAfterS}s)` : "";
715
+ showNotice(error instanceof ChatbotError ? `${error.message}${wait}` : "Something went wrong. Please try again.");
716
+ } finally {
717
+ sending = false;
718
+ render();
719
+ input.focus();
720
+ }
721
+ }
722
+ function autosize() {
723
+ input.style.height = "auto";
724
+ input.style.height = `${Math.min(input.scrollHeight, 120)}px`;
725
+ }
726
+ function setOpen(open) {
727
+ if (inline) return;
728
+ panel.hidden = !open;
729
+ launcher?.setAttribute("aria-expanded", String(open));
730
+ launcher?.setAttribute("aria-label", open ? "Close chat" : "Open chat");
731
+ if (open) {
732
+ render();
733
+ log.scrollTop = log.scrollHeight;
734
+ input.focus();
735
+ } else {
736
+ launcher?.focus();
737
+ }
738
+ }
739
+ composer.addEventListener("submit", (event) => {
740
+ event.preventDefault();
741
+ void sendMessage(input.value);
742
+ });
743
+ input.addEventListener("keydown", (event) => {
744
+ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
745
+ event.preventDefault();
746
+ void sendMessage(input.value);
747
+ return;
748
+ }
749
+ if (event.key === "ArrowUp" && !event.shiftKey && !event.isComposing && promptHistory.length > 0) {
750
+ const pos = input.selectionStart ?? 0;
751
+ if (!input.value.slice(0, pos).includes("\n")) {
752
+ event.preventDefault();
753
+ if (historyIndex === -1) {
754
+ draft = input.value;
755
+ historyIndex = promptHistory.length - 1;
756
+ } else if (historyIndex > 0) {
757
+ historyIndex -= 1;
758
+ }
759
+ input.value = promptHistory[historyIndex] ?? "";
760
+ autosize();
761
+ updateComposer();
762
+ input.setSelectionRange(input.value.length, input.value.length);
763
+ }
764
+ return;
765
+ }
766
+ if (event.key === "ArrowDown" && !event.shiftKey && !event.isComposing && historyIndex !== -1) {
767
+ const pos = input.selectionEnd ?? input.value.length;
768
+ if (!input.value.slice(pos).includes("\n")) {
769
+ event.preventDefault();
770
+ if (historyIndex < promptHistory.length - 1) {
771
+ historyIndex += 1;
772
+ input.value = promptHistory[historyIndex] ?? "";
773
+ } else {
774
+ historyIndex = -1;
775
+ input.value = draft;
776
+ }
777
+ autosize();
778
+ updateComposer();
779
+ input.setSelectionRange(input.value.length, input.value.length);
780
+ }
781
+ }
782
+ });
783
+ input.addEventListener("input", () => {
784
+ historyIndex = -1;
785
+ autosize();
786
+ updateComposer();
787
+ });
788
+ launcher?.addEventListener("click", () => setOpen(panel.hidden));
789
+ closeButton?.addEventListener("click", () => setOpen(false));
790
+ panel.addEventListener("keydown", (event) => {
791
+ if (event.key === "Escape" && !inline) setOpen(false);
792
+ });
793
+ render();
794
+ client.getConfig().then(applyConfig).catch((error) => {
795
+ showNotice(error instanceof ChatbotError ? error.message : "The assistant is unavailable right now.");
796
+ });
797
+ for (const entry of entries) if (entry.kind === "run") follow(entry);
798
+ if (options.open) setOpen(true);
799
+ return {
800
+ host,
801
+ open: () => setOpen(true),
802
+ close: () => setOpen(false),
803
+ toggle: () => setOpen(panel.hidden),
804
+ send: (text) => sendMessage(text),
805
+ destroy: () => {
806
+ destroyed = true;
807
+ for (const controller of following.values()) controller.abort();
808
+ following.clear();
809
+ host.remove();
810
+ }
811
+ };
812
+ }
813
+ export {
814
+ AegisHexClient,
815
+ ChatbotError,
816
+ FINAL_PHASES,
817
+ SseParser,
818
+ mountChatbot,
819
+ readableOn
820
+ };
821
+ //# sourceMappingURL=index.js.map