@vettvangur/ai-sdk 0.9.0 → 0.11.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/window.js ADDED
@@ -0,0 +1,2056 @@
1
+ import { a as isSafeLinkUrl, i as isPlainObject, o as readJsonAttribute, r as createSafeLink, t as createPart } from "./dom.js";
2
+ import { i as renderMarkdown, n as renderSurveyForm, r as countMarkdownStructuralItems } from "./survey.js";
3
+ //#region src/answer-card.ts
4
+ const ANSWER_CARD_KEYS = /* @__PURE__ */ new Set([
5
+ "kind",
6
+ "title",
7
+ "summary",
8
+ "highlight",
9
+ "sections",
10
+ "note",
11
+ "actions",
12
+ "sources",
13
+ "sourceNote"
14
+ ]);
15
+ const HIGHLIGHT_KEYS = /* @__PURE__ */ new Set(["label", "value"]);
16
+ const SECTION_KEYS = /* @__PURE__ */ new Set([
17
+ "title",
18
+ "text",
19
+ "facts",
20
+ "tables",
21
+ "links",
22
+ "note",
23
+ "collapsible"
24
+ ]);
25
+ const FACT_KEYS = /* @__PURE__ */ new Set(["label", "value"]);
26
+ const TABLE_KEYS = /* @__PURE__ */ new Set([
27
+ "label",
28
+ "headers",
29
+ "rows"
30
+ ]);
31
+ const LINK_KEYS = /* @__PURE__ */ new Set(["label", "url"]);
32
+ const MAX_ANSWER_CARD_SECTIONS = 12;
33
+ const MAX_ANSWER_CARD_FACTS = 24;
34
+ const MAX_ANSWER_CARD_LINKS = 24;
35
+ const MAX_ANSWER_CARD_TABLES = 8;
36
+ const MAX_ANSWER_CARD_TABLE_ROWS = 50;
37
+ const MAX_ANSWER_CARD_TABLE_CELLS = 12;
38
+ const MAX_ANSWER_CARD_TEXT_LENGTH = 8e3;
39
+ const MAX_ANSWER_CARD_URL_LENGTH = 2048;
40
+ const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24e3;
41
+ const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
42
+ const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
43
+ /**
44
+ * Every element an answer card renders carries a class under this block, so a host styles the card
45
+ * by class rather than by the order its elements happen to come in.
46
+ */
47
+ const ANSWER_CARD_CLASS = "vv-ai-answer-card";
48
+ function hasOnlyKeys(value, keys) {
49
+ let keyCount = 0;
50
+ for (const key in value) {
51
+ if (!Object.hasOwn(value, key)) continue;
52
+ keyCount += 1;
53
+ if (keyCount > keys.size || !keys.has(key)) return false;
54
+ }
55
+ return true;
56
+ }
57
+ function consumeStructuralItems(budget, count) {
58
+ budget.structuralItems += count;
59
+ return budget.structuralItems <= 512;
60
+ }
61
+ function consumeTableCells(budget, count) {
62
+ budget.tableCells += count;
63
+ return budget.tableCells <= 512;
64
+ }
65
+ function consumeTextCharacters(budget, count) {
66
+ budget.textCharacters += count;
67
+ return budget.textCharacters <= MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS;
68
+ }
69
+ function isAnswerCardText(value, budget) {
70
+ if (typeof value !== "string" || value.length > 8e3) return false;
71
+ return consumeTextCharacters(budget, value.length);
72
+ }
73
+ function hasOptionalNullableText(value, key, budget) {
74
+ return !Object.hasOwn(value, key) || value[key] === null || isAnswerCardText(value[key], budget);
75
+ }
76
+ function hasOptionalNullableMarkdown(value, key, budget) {
77
+ if (!Object.hasOwn(value, key) || value[key] === null) return true;
78
+ const text = value[key];
79
+ if (!isAnswerCardText(text, budget)) return false;
80
+ return consumeStructuralItems(budget, countMarkdownStructuralItems(text));
81
+ }
82
+ function hasOptionalBoolean(value, key) {
83
+ return !Object.hasOwn(value, key) || typeof value[key] === "boolean";
84
+ }
85
+ function isLink(value, budget) {
86
+ return isPlainObject(value) && hasOnlyKeys(value, LINK_KEYS) && isAnswerCardText(value.label, budget) && typeof value.url === "string" && value.url.length <= 2048 && consumeTextCharacters(budget, value.url.length) && consumeStructuralItems(budget, 1);
87
+ }
88
+ function isFact(value, budget) {
89
+ return isPlainObject(value) && hasOnlyKeys(value, FACT_KEYS) && isAnswerCardText(value.label, budget) && isAnswerCardText(value.value, budget) && consumeStructuralItems(budget, 1);
90
+ }
91
+ function isTextArray(value, maximumLength, budget) {
92
+ if (!Array.isArray(value) || value.length > maximumLength) return false;
93
+ for (const item of value) if (!isAnswerCardText(item, budget)) return false;
94
+ return true;
95
+ }
96
+ function isBoundedArray(value, maximumLength, guard) {
97
+ if (!Array.isArray(value) || value.length > maximumLength) return false;
98
+ for (const item of value) if (!guard(item)) return false;
99
+ return true;
100
+ }
101
+ function isTable(value, budget) {
102
+ if (!isPlainObject(value) || !hasOnlyKeys(value, TABLE_KEYS) || !hasOptionalNullableText(value, "label", budget)) return false;
103
+ const headers = value.headers;
104
+ const rows = value.rows;
105
+ if (!isTextArray(headers, 12, budget) || headers.length === 0 || !Array.isArray(rows) || !isBoundedArray(rows, 50, (row) => isTextArray(row, 12, budget) && row.length === headers.length)) return false;
106
+ return consumeStructuralItems(budget, rows.length + 2) && consumeTableCells(budget, headers.length * (rows.length + 1));
107
+ }
108
+ function hasOptionalNullableArray(value, key, maximumLength, guard) {
109
+ return !Object.hasOwn(value, key) || value[key] === null || isBoundedArray(value[key], maximumLength, guard);
110
+ }
111
+ function isSection(value, budget) {
112
+ if (!isPlainObject(value) || !hasOnlyKeys(value, SECTION_KEYS) || !consumeStructuralItems(budget, 1)) return false;
113
+ return hasOptionalNullableText(value, "title", budget) && hasOptionalNullableMarkdown(value, "text", budget) && hasOptionalNullableArray(value, "facts", 24, (fact) => isFact(fact, budget)) && hasOptionalNullableArray(value, "tables", 8, (table) => isTable(table, budget)) && hasOptionalNullableArray(value, "links", 24, (link) => isLink(link, budget)) && hasOptionalNullableText(value, "note", budget) && hasOptionalBoolean(value, "collapsible");
114
+ }
115
+ /**
116
+ * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
117
+ * server or a test, can hold its output to the same limits the renderer applies.
118
+ */
119
+ function isAnswerCard(value) {
120
+ const budget = {
121
+ textCharacters: 0,
122
+ structuralItems: 0,
123
+ tableCells: 0
124
+ };
125
+ return isPlainObject(value) && hasOnlyKeys(value, ANSWER_CARD_KEYS) && value.kind === "answer" && consumeStructuralItems(budget, 1) && isAnswerCardText(value.title, budget) && hasOptionalNullableMarkdown(value, "summary", budget) && (!Object.hasOwn(value, "highlight") || value.highlight === null || isFact(value.highlight, budget) && hasOnlyKeys(value.highlight, HIGHLIGHT_KEYS)) && hasOptionalNullableArray(value, "sections", 12, (section) => isSection(section, budget)) && hasOptionalNullableText(value, "note", budget) && hasOptionalNullableArray(value, "actions", 24, (link) => isLink(link, budget)) && hasOptionalNullableArray(value, "sources", 24, (link) => isLink(link, budget)) && hasOptionalNullableText(value, "sourceNote", budget);
126
+ }
127
+ function cardElement(document, tag, part) {
128
+ const created = document.createElement(tag);
129
+ created.className = part ? `${ANSWER_CARD_CLASS}__${part}` : ANSWER_CARD_CLASS;
130
+ return created;
131
+ }
132
+ function appendMarkdown(document, parent, text, part) {
133
+ if (text !== null && text !== void 0) {
134
+ const wrapper = cardElement(document, "div", part);
135
+ wrapper.append(renderMarkdown(document, text));
136
+ parent.append(wrapper);
137
+ }
138
+ }
139
+ function appendFacts(document, parent, facts, part = "facts") {
140
+ if (facts.length === 0) return;
141
+ const definitions = cardElement(document, "dl", part);
142
+ for (const fact of facts) {
143
+ const term = cardElement(document, "dt", "fact-label");
144
+ term.append(document.createTextNode(fact.label));
145
+ const definition = cardElement(document, "dd", "fact-value");
146
+ definition.append(document.createTextNode(fact.value));
147
+ definitions.append(term, definition);
148
+ }
149
+ parent.append(definitions);
150
+ }
151
+ function appendLinks(document, parent, links, part) {
152
+ if (links.length === 0) return;
153
+ const list = cardElement(document, "ul", part);
154
+ for (const item of links) {
155
+ const listItem = cardElement(document, "li", `${part}-item`);
156
+ const link = createSafeLink(document, item.label, item.url);
157
+ link?.classList.add(`${ANSWER_CARD_CLASS}__link`);
158
+ listItem.append(link ?? document.createTextNode(item.label));
159
+ list.append(listItem);
160
+ }
161
+ parent.append(list);
162
+ }
163
+ function appendNote(document, parent, note, part = "note") {
164
+ if (note === null || note === void 0) return;
165
+ const paragraph = cardElement(document, "p", part);
166
+ paragraph.append(document.createTextNode(note));
167
+ parent.append(paragraph);
168
+ }
169
+ function createTable(document, table) {
170
+ const element = cardElement(document, "table", "table");
171
+ if (table.headers.length > 0) {
172
+ const head = document.createElement("thead");
173
+ const row = document.createElement("tr");
174
+ for (const header of table.headers) {
175
+ const cell = cardElement(document, "th", "table-header");
176
+ cell.scope = "col";
177
+ cell.append(document.createTextNode(header));
178
+ row.append(cell);
179
+ }
180
+ head.append(row);
181
+ element.append(head);
182
+ }
183
+ if (table.rows.length > 0) {
184
+ const body = document.createElement("tbody");
185
+ for (const cells of table.rows) {
186
+ const row = document.createElement("tr");
187
+ for (const value of cells) {
188
+ const cell = cardElement(document, "td", "table-cell");
189
+ cell.append(document.createTextNode(value));
190
+ row.append(cell);
191
+ }
192
+ body.append(row);
193
+ }
194
+ element.append(body);
195
+ }
196
+ return element;
197
+ }
198
+ function tableRegionBaseName(table, sectionTitle, labels) {
199
+ return table.label?.trim() || sectionTitle?.trim() || labels.table;
200
+ }
201
+ function tableRegionNames(sections, labels) {
202
+ const counts = /* @__PURE__ */ new Map();
203
+ for (const section of sections) for (const table of section.tables ?? []) {
204
+ const name = tableRegionBaseName(table, section.title, labels);
205
+ counts.set(name, (counts.get(name) ?? 0) + 1);
206
+ }
207
+ return {
208
+ counts,
209
+ ordinals: /* @__PURE__ */ new Map()
210
+ };
211
+ }
212
+ function appendTables(document, parent, tables, sectionTitle, labels, names) {
213
+ for (const table of tables) {
214
+ const name = tableRegionBaseName(table, sectionTitle, labels);
215
+ const ordinal = (names.ordinals.get(name) ?? 0) + 1;
216
+ names.ordinals.set(name, ordinal);
217
+ const element = createTable(document, table);
218
+ const region = cardElement(document, "div", "table-region");
219
+ region.setAttribute("data-ai-table-region", "true");
220
+ region.setAttribute("role", "region");
221
+ region.setAttribute("tabindex", "0");
222
+ region.setAttribute("aria-label", (names.counts.get(name) ?? 0) > 1 ? `${name} (${ordinal})` : name);
223
+ region.style.overflowX = "auto";
224
+ const hint = cardElement(document, "p", "table-hint");
225
+ hint.append(document.createTextNode(labels.tableScroll));
226
+ region.append(hint);
227
+ region.append(element);
228
+ parent.append(region);
229
+ }
230
+ }
231
+ function appendSection(document, article, section, labels, names) {
232
+ const content = cardElement(document, "section", "section");
233
+ if (!section.collapsible && section.title !== null && section.title !== void 0) {
234
+ const heading = cardElement(document, "h3", "section-title");
235
+ heading.append(document.createTextNode(section.title));
236
+ content.append(heading);
237
+ }
238
+ appendMarkdown(document, content, section.text, "text");
239
+ appendFacts(document, content, section.facts ?? []);
240
+ appendTables(document, content, section.tables ?? [], section.title, labels, names);
241
+ appendLinks(document, content, section.links ?? [], "links");
242
+ appendNote(document, content, section.note);
243
+ if (!section.collapsible) {
244
+ article.append(content);
245
+ return;
246
+ }
247
+ const details = cardElement(document, "details", "details");
248
+ const summary = cardElement(document, "summary", "details-summary");
249
+ summary.append(document.createTextNode(section.title?.trim() ? section.title : labels.details));
250
+ details.append(summary, content);
251
+ article.append(details);
252
+ }
253
+ function renderKnownAnswerCard(document, card, labels) {
254
+ const article = cardElement(document, "article", "");
255
+ const heading = cardElement(document, "h2", "title");
256
+ heading.append(document.createTextNode(card.title));
257
+ article.append(heading);
258
+ appendMarkdown(document, article, card.summary, "summary");
259
+ if (card.highlight) appendFacts(document, article, [card.highlight], "highlight");
260
+ const names = tableRegionNames(card.sections ?? [], labels);
261
+ for (const section of card.sections ?? []) appendSection(document, article, section, labels, names);
262
+ appendNote(document, article, card.note);
263
+ appendLinks(document, article, card.actions ?? [], "actions");
264
+ if ((card.sources?.length ?? 0) > 0 || card.sourceNote !== null && card.sourceNote !== void 0) {
265
+ const sources = cardElement(document, "section", "sources");
266
+ const sourceHeading = cardElement(document, "h3", "sources-title");
267
+ sourceHeading.append(document.createTextNode(labels.sources));
268
+ sources.append(sourceHeading);
269
+ appendLinks(document, sources, card.sources ?? [], "sources-list");
270
+ appendNote(document, sources, card.sourceNote, "source-note");
271
+ article.append(sources);
272
+ }
273
+ return article;
274
+ }
275
+ function scalarValue(value) {
276
+ if (typeof value === "string") return value.length <= 2e3 && value.trim().length > 0 ? value : null;
277
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
278
+ return typeof value === "boolean" ? String(value) : null;
279
+ }
280
+ function humanizePropertyName(name) {
281
+ if (name.length > 2e3) return null;
282
+ const words = name.replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
283
+ return words.length === 0 ? null : `${words[0].toUpperCase()}${words.slice(1)}`;
284
+ }
285
+ function genericFields(value) {
286
+ const fields = [];
287
+ let propertyCount = 0;
288
+ for (const key in value) {
289
+ if (!Object.hasOwn(value, key)) continue;
290
+ propertyCount += 1;
291
+ if (propertyCount > 24) break;
292
+ const label = humanizePropertyName(key);
293
+ const scalar = scalarValue(value[key]);
294
+ if (label !== null && scalar !== null) {
295
+ fields.push({
296
+ label,
297
+ value: scalar
298
+ });
299
+ if (fields.length === 12) break;
300
+ }
301
+ }
302
+ return fields;
303
+ }
304
+ function genericEntries(data) {
305
+ if (isPlainObject(data)) {
306
+ const fields = genericFields(data);
307
+ return fields.length > 0 ? [fields] : [];
308
+ }
309
+ if (!Array.isArray(data) || data.length > 20) return [];
310
+ const entries = [];
311
+ for (const item of data) if (isPlainObject(item)) {
312
+ const fields = genericFields(item);
313
+ if (fields.length > 0) entries.push(fields);
314
+ if (entries.length === 5) break;
315
+ }
316
+ return entries;
317
+ }
318
+ function renderGenericAnswerCard(document, data) {
319
+ const entries = genericEntries(data);
320
+ if (entries.length === 0) return null;
321
+ const article = cardElement(document, "article", "");
322
+ article.classList.add(`${ANSWER_CARD_CLASS}--generic`);
323
+ const list = cardElement(document, "ul", "entries");
324
+ for (const fields of entries) {
325
+ const item = cardElement(document, "li", "entry");
326
+ appendFacts(document, item, fields);
327
+ list.append(item);
328
+ }
329
+ article.append(list);
330
+ return article;
331
+ }
332
+ function renderAnswerCard(document, data, labels) {
333
+ if (isPlainObject(data) && data.kind === "answer") return isAnswerCard(data) ? renderKnownAnswerCard(document, data, labels) : null;
334
+ return renderGenericAnswerCard(document, data);
335
+ }
336
+ const MARKDOWN_IN_PLAIN_TEXT = /\]\(|\\[\\`*_{}[\]()#+.!|~-]/;
337
+ function plainTextFields(card) {
338
+ const facts = (items) => (items ?? []).flatMap((fact) => [fact.label, fact.value]);
339
+ return [
340
+ card.title,
341
+ card.note,
342
+ card.sourceNote,
343
+ ...facts(card.highlight ? [card.highlight] : null),
344
+ ...(card.sections ?? []).flatMap((section) => [
345
+ section.title,
346
+ section.note,
347
+ ...facts(section.facts),
348
+ ...(section.tables ?? []).flatMap((table) => [
349
+ table.label,
350
+ ...table.headers,
351
+ ...table.rows.flat()
352
+ ])
353
+ ])
354
+ ].filter((value) => typeof value === "string");
355
+ }
356
+ /**
357
+ * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
358
+ * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
359
+ * a server's or a test's own cards; the message names what is wrong.
360
+ */
361
+ function assertAnswerCardContract(card) {
362
+ if (!isAnswerCard(card)) throw new Error("Not an answer card the renderer draws: check its kind, keys and limits");
363
+ for (const text of plainTextFields(card)) if (MARKDOWN_IN_PLAIN_TEXT.test(text)) throw new Error(`Markdown in a plain-text field of "${card.title}": ${text}`);
364
+ }
365
+ //#endregion
366
+ //#region src/cards.ts
367
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
368
+ const CARD_LIST_CLASS = "vv-ai-card-list";
369
+ const ACTIONS_CLASS = "vv-ai-actions";
370
+ function text(value) {
371
+ return typeof value === "string" && value.trim() ? value : null;
372
+ }
373
+ /**
374
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
375
+ * Items that render nothing are skipped, and a list with nothing in it is null.
376
+ */
377
+ function renderCardList(document, items, render, modifier) {
378
+ if (!Array.isArray(items)) return null;
379
+ const cards = items.map(render).filter((card) => card !== null);
380
+ if (!cards.length) return null;
381
+ const list = createPart(document, "div", CARD_LIST_CLASS);
382
+ if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
383
+ list.append(...cards);
384
+ return list;
385
+ }
386
+ /**
387
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
388
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
389
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
390
+ */
391
+ function renderActions(document, items) {
392
+ const elements = [];
393
+ for (const item of items) {
394
+ const label = text(item?.label);
395
+ if (!label) continue;
396
+ let element = null;
397
+ const action = text(item.action);
398
+ const url = text(item.url);
399
+ if (action) {
400
+ const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
401
+ button.type = "button";
402
+ button.dataset.aiAction = action;
403
+ const value = text(item.value);
404
+ if (value) button.dataset.aiActionValue = value;
405
+ element = button;
406
+ } else if (url) {
407
+ element = createSafeLink(document, label, url.trim());
408
+ if (element) element.className = `${ACTIONS_CLASS}__action`;
409
+ }
410
+ if (element) {
411
+ element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
412
+ elements.push(element);
413
+ }
414
+ }
415
+ if (!elements.length) return null;
416
+ const actions = createPart(document, "div", ACTIONS_CLASS);
417
+ actions.append(...elements);
418
+ return actions;
419
+ }
420
+ //#endregion
421
+ //#region src/protocol.ts
422
+ const AI_CHAT_PROTOCOL_VERSION = 1;
423
+ const MAX_TURN_TOKEN_LENGTH = 1024;
424
+ function isRecord(value) {
425
+ return typeof value === "object" && value !== null && !Array.isArray(value);
426
+ }
427
+ function stringValue(data, key) {
428
+ const value = data[key];
429
+ return typeof value === "string" ? value : null;
430
+ }
431
+ function parseStreamEvent(name, data) {
432
+ if (!isRecord(data)) return null;
433
+ switch (name) {
434
+ case "delta": {
435
+ const text = stringValue(data, "text");
436
+ return text === null ? null : {
437
+ name,
438
+ data: { text }
439
+ };
440
+ }
441
+ case "tool": {
442
+ const id = stringValue(data, "id");
443
+ const toolName = stringValue(data, "name");
444
+ return id === null || toolName === null ? null : {
445
+ name,
446
+ data: {
447
+ id,
448
+ name: toolName
449
+ }
450
+ };
451
+ }
452
+ case "tool_result": {
453
+ const id = stringValue(data, "id");
454
+ const toolName = stringValue(data, "name");
455
+ const reply = data.reply;
456
+ if (id === null || toolName === null || !Object.hasOwn(data, "data") || typeof reply !== "string" && reply !== null) return null;
457
+ return {
458
+ name,
459
+ data: {
460
+ id,
461
+ name: toolName,
462
+ data: data.data,
463
+ reply
464
+ }
465
+ };
466
+ }
467
+ case "tool_done": {
468
+ const id = stringValue(data, "id");
469
+ const toolName = stringValue(data, "name");
470
+ const isError = data.isError;
471
+ return id === null || toolName === null || typeof isError !== "boolean" ? null : {
472
+ name,
473
+ data: {
474
+ id,
475
+ name: toolName,
476
+ isError
477
+ }
478
+ };
479
+ }
480
+ case "suggestions": {
481
+ const suggestions = data.suggestions;
482
+ if (!Array.isArray(suggestions)) return null;
483
+ return {
484
+ name,
485
+ data: { suggestions: suggestions.filter((item) => typeof item === "string" && item.trim().length > 0).filter((item) => item.length <= 200).slice(0, 6) }
486
+ };
487
+ }
488
+ case "done": {
489
+ const turn = stringValue(data, "turn");
490
+ return {
491
+ name,
492
+ data: { turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null }
493
+ };
494
+ }
495
+ case "error": {
496
+ const message = stringValue(data, "message");
497
+ return message === null ? null : {
498
+ name,
499
+ data: { message }
500
+ };
501
+ }
502
+ default: return null;
503
+ }
504
+ }
505
+ //#endregion
506
+ //#region src/stream.ts
507
+ function findRecordBoundary(buffer) {
508
+ const lfIndex = buffer.indexOf("\n\n");
509
+ const crlfIndex = buffer.indexOf("\r\n\r\n");
510
+ if (lfIndex === -1 && crlfIndex === -1) return null;
511
+ if (lfIndex === -1 || crlfIndex !== -1 && crlfIndex < lfIndex) return {
512
+ index: crlfIndex,
513
+ length: 4
514
+ };
515
+ return {
516
+ index: lfIndex,
517
+ length: 2
518
+ };
519
+ }
520
+ function fieldValue(value) {
521
+ return value.startsWith(" ") ? value.slice(1) : value;
522
+ }
523
+ function parseRecord(record) {
524
+ let name;
525
+ const dataLines = [];
526
+ for (const line of record.split(/\r?\n/)) if (line.startsWith("event:")) name = fieldValue(line.slice(6));
527
+ else if (line.startsWith("data:")) dataLines.push(fieldValue(line.slice(5)));
528
+ if (!name || dataLines.length === 0) return null;
529
+ try {
530
+ return parseStreamEvent(name, JSON.parse(dataLines.join("\n")));
531
+ } catch {
532
+ return null;
533
+ }
534
+ }
535
+ function abortError$1() {
536
+ return /* @__PURE__ */ new Error("AI chat event stream was aborted");
537
+ }
538
+ async function* readEventStream(response, signal) {
539
+ if (!response.body) throw new Error("AI chat response has no body");
540
+ if (signal.aborted) throw abortError$1();
541
+ const decoder = new TextDecoder();
542
+ const reader = response.body.getReader();
543
+ let buffer = "";
544
+ let readerDone = false;
545
+ const cancelReader = () => {
546
+ reader.cancel().catch(() => void 0);
547
+ };
548
+ signal.addEventListener("abort", cancelReader, { once: true });
549
+ try {
550
+ while (true) {
551
+ if (signal.aborted) throw abortError$1();
552
+ const { done, value } = await reader.read();
553
+ if (signal.aborted) throw abortError$1();
554
+ if (done) {
555
+ readerDone = true;
556
+ buffer += decoder.decode();
557
+ } else buffer += decoder.decode(value, { stream: true });
558
+ let boundary = findRecordBoundary(buffer);
559
+ while (boundary) {
560
+ const event = parseRecord(buffer.slice(0, boundary.index));
561
+ buffer = buffer.slice(boundary.index + boundary.length);
562
+ if (event) {
563
+ if (event.name === "done" || event.name === "error") {
564
+ yield event;
565
+ return;
566
+ }
567
+ yield event;
568
+ }
569
+ boundary = findRecordBoundary(buffer);
570
+ }
571
+ if (readerDone) throw new Error("AI chat event stream ended before a terminal event");
572
+ }
573
+ } finally {
574
+ signal.removeEventListener("abort", cancelReader);
575
+ if (!readerDone) try {
576
+ await reader.cancel();
577
+ } catch {}
578
+ reader.releaseLock();
579
+ }
580
+ }
581
+ //#endregion
582
+ //#region src/chat.ts
583
+ const DEFAULT_TIMEOUT_MS = 6e4;
584
+ function abortError() {
585
+ return /* @__PURE__ */ new Error("AI chat request was canceled");
586
+ }
587
+ function afterNextPaint() {
588
+ return new Promise((resolve) => {
589
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
590
+ });
591
+ }
592
+ function createChatSession(options) {
593
+ const history = [];
594
+ const context = {};
595
+ const contextMessages = /* @__PURE__ */ new Map();
596
+ const listeners = /* @__PURE__ */ new Set();
597
+ let status = "idle";
598
+ let controller = null;
599
+ let timeout = null;
600
+ const session = {
601
+ get history() {
602
+ return history;
603
+ },
604
+ get context() {
605
+ return context;
606
+ },
607
+ get status() {
608
+ return status;
609
+ },
610
+ async send(message) {
611
+ const content = message.trim();
612
+ if (!content) throw new Error("AI chat messages cannot be empty");
613
+ if (status === "disposed") throw new Error("AI chat session is disposed");
614
+ if (controller) throw new Error("AI chat request is already active");
615
+ const requestController = new AbortController();
616
+ controller = requestController;
617
+ status = "sending";
618
+ const fetcher = options.fetch ?? fetch;
619
+ const headers = {
620
+ "Content-Type": "application/json",
621
+ ...options.headers
622
+ };
623
+ const requestHistory = [...history, {
624
+ role: "user",
625
+ content
626
+ }];
627
+ let turn = null;
628
+ let error = null;
629
+ let canceled = false;
630
+ let answer = "";
631
+ let replies = [];
632
+ timeout = setTimeout(() => requestController.abort(new DOMException("AI chat request timed out", "TimeoutError")), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
633
+ try {
634
+ const response = await fetcher(options.endpoint, {
635
+ method: "POST",
636
+ headers,
637
+ body: JSON.stringify({
638
+ messages: requestHistory,
639
+ provider: options.provider,
640
+ context
641
+ }),
642
+ signal: requestController.signal
643
+ });
644
+ if (!response.ok) throw new Error(`AI chat request failed with ${response.status}`);
645
+ for await (const event of readEventStream(response, requestController.signal)) {
646
+ options.onEvent?.(event);
647
+ for (const listener of listeners) listener(event);
648
+ if (event.name === "tool") await afterNextPaint();
649
+ if (event.name === "delta") answer += event.data.text;
650
+ else if (event.name === "tool_result" && event.data.reply) replies.push(event.data.reply);
651
+ else if (event.name === "done") turn = event.data.turn;
652
+ else if (event.name === "error") throw new Error(event.data.message);
653
+ }
654
+ if (answer.trim()) replies = [...replies, answer.trim()];
655
+ history.push({
656
+ role: "user",
657
+ content
658
+ }, ...replies.map((reply) => ({
659
+ role: "assistant",
660
+ content: reply
661
+ })));
662
+ } catch (caught) {
663
+ canceled = requestController.signal.aborted;
664
+ error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat request failed");
665
+ if (canceled && requestController.signal.reason?.name !== "TimeoutError") error = abortError();
666
+ } finally {
667
+ if (timeout) clearTimeout(timeout);
668
+ timeout = null;
669
+ if (controller === requestController) controller = null;
670
+ if (session.status !== "disposed") status = "idle";
671
+ }
672
+ return {
673
+ turn,
674
+ canceled,
675
+ error
676
+ };
677
+ },
678
+ cancel() {
679
+ controller?.abort();
680
+ },
681
+ reset() {
682
+ session.cancel();
683
+ history.splice(0);
684
+ for (const key of Object.keys(context)) delete context[key];
685
+ contextMessages.clear();
686
+ },
687
+ setContext(name, value) {
688
+ if (!name.trim()) throw new Error("AI chat context names cannot be empty");
689
+ context[name] = value;
690
+ },
691
+ setContextMessage(name, content) {
692
+ const value = content.trim();
693
+ if (!name.trim() || !value) throw new Error("AI chat context messages cannot be empty");
694
+ const existing = contextMessages.get(name);
695
+ if (existing) {
696
+ existing.content = value;
697
+ return;
698
+ }
699
+ const message = {
700
+ role: "user",
701
+ content: value
702
+ };
703
+ contextMessages.set(name, message);
704
+ history.push(message);
705
+ },
706
+ restoreHistory(messages) {
707
+ session.cancel();
708
+ history.splice(0, history.length, ...messages.map((message) => ({ ...message })));
709
+ contextMessages.clear();
710
+ },
711
+ addAssistantReply(content) {
712
+ const value = content.trim();
713
+ if (!value) throw new Error("AI chat assistant replies cannot be empty");
714
+ history.push({
715
+ role: "assistant",
716
+ content: value
717
+ });
718
+ },
719
+ clearContext(name) {
720
+ delete context[name];
721
+ },
722
+ subscribe(listener) {
723
+ listeners.add(listener);
724
+ return () => listeners.delete(listener);
725
+ },
726
+ dispose() {
727
+ session.cancel();
728
+ listeners.clear();
729
+ status = "disposed";
730
+ }
731
+ };
732
+ return session;
733
+ }
734
+ //#endregion
735
+ //#region src/handover.ts
736
+ /** The action the handover card's button runs; the binding hands over to a person with it. */
737
+ const LIVE_CHAT_ACTION = "livechat";
738
+ /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
739
+ const HANDOVER_TOOL = "request_human_agent";
740
+ /** A payload of kind `handover`, or one from the handover tool that names no kind. */
741
+ function isHandoverPayload(tool, data) {
742
+ return isPlainObject(data) && (data.kind === "handover" || tool === "request_human_agent" && data.kind === void 0);
743
+ }
744
+ function surveyAnswers(value) {
745
+ if (!isPlainObject(value)) return;
746
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" || typeof entry[1] === "boolean"));
747
+ }
748
+ /**
749
+ * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
750
+ * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
751
+ * goes on the button as its value. Null when neither applies.
752
+ */
753
+ function renderHandoverCard(document, data, labels) {
754
+ const prefill = surveyAnswers(data.prefill);
755
+ const value = prefill && Object.keys(prefill).length ? JSON.stringify(prefill) : null;
756
+ return renderActions(document, [...data.liveChatAvailable === true ? [{
757
+ label: labels.liveChat,
758
+ action: LIVE_CHAT_ACTION,
759
+ value,
760
+ primary: true
761
+ }] : [], ...typeof data.contactUrl === "string" ? [{
762
+ label: labels.contact,
763
+ url: data.contactUrl
764
+ }] : []]);
765
+ }
766
+ /** The survey answers a live chat button carries, or undefined when it carries none. */
767
+ function buttonPrefill(button) {
768
+ const value = button.dataset.aiActionValue;
769
+ if (!value) return;
770
+ try {
771
+ return surveyAnswers(JSON.parse(value));
772
+ } catch {
773
+ return;
774
+ }
775
+ }
776
+ /**
777
+ * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
778
+ * no one can take the chat. The contact link stays.
779
+ */
780
+ function closeHandoverCard(parent, text) {
781
+ for (const button of parent.querySelectorAll(`[data-ai-action="${LIVE_CHAT_ACTION}"]`)) button.replaceWith(createPart(button.ownerDocument, "p", ACTIONS_CLASS, "note", text));
782
+ }
783
+ //#endregion
784
+ //#region src/registry.ts
785
+ const entries = /* @__PURE__ */ new WeakMap();
786
+ function register(map, name, value) {
787
+ if (!name.trim()) throw new Error("AI chat registry names cannot be empty");
788
+ map.set(name, value);
789
+ return () => {
790
+ if (map.get(name) === value) map.delete(name);
791
+ };
792
+ }
793
+ function createAiChatRegistry() {
794
+ const state = {
795
+ renderers: /* @__PURE__ */ new Map(),
796
+ surfaces: /* @__PURE__ */ new Map(),
797
+ actions: /* @__PURE__ */ new Map()
798
+ };
799
+ const registry = {
800
+ registerRenderer: (name, renderer) => register(state.renderers, name, renderer),
801
+ registerSurface: (name, surface) => register(state.surfaces, name, surface),
802
+ registerAction: (name, action) => register(state.actions, name, action)
803
+ };
804
+ entries.set(registry, state);
805
+ return registry;
806
+ }
807
+ function registryEntries(registry) {
808
+ return registry ? entries.get(registry) : void 0;
809
+ }
810
+ //#endregion
811
+ //#region src/sheet.ts
812
+ /** The `data-ai-action` of a button that opens its `data-ai-action-value` in a sheet. */
813
+ const SHEET_ACTION = "sheet";
814
+ const SHEET_CLASS = "vv-ai-chat";
815
+ /**
816
+ * A page in a sheet over the chat: a dialog with a title, a close button and the page in a frame,
817
+ * appended to `root`. Escape closes it too, and focus goes back to where it was. Null for a URL
818
+ * a link could not open either.
819
+ */
820
+ function openSheet(root, options) {
821
+ if (!isSafeLinkUrl(options.url)) return null;
822
+ const document = root.ownerDocument;
823
+ const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
824
+ const titleId = `vv-ai-chat-sheet-${crypto.randomUUID()}`;
825
+ const sheet = createPart(document, "div", SHEET_CLASS, "sheet");
826
+ sheet.dataset.aiChatSheet = "";
827
+ sheet.setAttribute("role", "dialog");
828
+ sheet.setAttribute("aria-modal", "true");
829
+ sheet.setAttribute("aria-labelledby", titleId);
830
+ const header = createPart(document, "div", SHEET_CLASS, "sheet-header");
831
+ const title = createPart(document, "p", SHEET_CLASS, "sheet-title", options.title);
832
+ title.id = titleId;
833
+ const close = createPart(document, "button", SHEET_CLASS, "sheet-close", options.closeLabel);
834
+ close.type = "button";
835
+ header.append(title, close);
836
+ const frame = createPart(document, "iframe", SHEET_CLASS, "sheet-frame");
837
+ frame.title = options.title;
838
+ frame.src = options.url;
839
+ sheet.append(header, frame);
840
+ let open = true;
841
+ function dismiss() {
842
+ if (!open) return;
843
+ open = false;
844
+ sheet.removeEventListener("keydown", keydown);
845
+ sheet.remove();
846
+ returnFocus?.focus({ preventScroll: true });
847
+ options.onClose();
848
+ }
849
+ function keydown(event) {
850
+ if (event.key === "Escape") {
851
+ event.stopPropagation();
852
+ dismiss();
853
+ }
854
+ }
855
+ close.addEventListener("click", dismiss);
856
+ sheet.addEventListener("keydown", keydown);
857
+ root.append(sheet);
858
+ close.focus({ preventScroll: true });
859
+ return {
860
+ frame,
861
+ close: dismiss
862
+ };
863
+ }
864
+ //#endregion
865
+ //#region src/thread-store.ts
866
+ function storage() {
867
+ try {
868
+ return window.sessionStorage;
869
+ } catch {
870
+ return null;
871
+ }
872
+ }
873
+ function readThread(key) {
874
+ try {
875
+ const raw = storage()?.getItem(key);
876
+ const parsed = raw ? JSON.parse(raw) : null;
877
+ if (!isPlainObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.history) || !Array.isArray(parsed.entries)) return null;
878
+ return parsed;
879
+ } catch {
880
+ return null;
881
+ }
882
+ }
883
+ function writeThread(key, thread) {
884
+ try {
885
+ storage()?.setItem(key, JSON.stringify(thread));
886
+ } catch {}
887
+ }
888
+ function clearThread(key) {
889
+ try {
890
+ storage()?.removeItem(key);
891
+ } catch {}
892
+ }
893
+ //#endregion
894
+ //#region src/bind.ts
895
+ const defaultLabels = {
896
+ error: "Something went wrong. Please try again.",
897
+ timeout: "The reply took too long. Please try again.",
898
+ toolRunning: "Looking that up",
899
+ toolComplete: "Done",
900
+ toolFailed: "Unavailable",
901
+ toolInterrupted: "Lookup interrupted",
902
+ sources: "Sources",
903
+ details: "Details",
904
+ table: "Published table",
905
+ tableScroll: "Scroll sideways to see all columns",
906
+ followUps: "Suggested questions",
907
+ liveChat: "Chat with a person",
908
+ contact: "Contact us",
909
+ liveChatConnecting: "Connecting you to a person",
910
+ liveChatClosed: "No one is available to chat right now.",
911
+ liveChatEnded: "The chat has ended. You are talking to the AI again.",
912
+ liveChatFailed: "We could not connect you to a person. Please try again.",
913
+ liveChatTyping: "Typing",
914
+ liveChatAgent: "Agent",
915
+ liveChatStarted: "Chat with a person started",
916
+ liveChatJoined: "{name} joined the chat",
917
+ liveChatAgentEnded: "{name} ended the chat",
918
+ liveChatWaiting: "One moment, connecting you",
919
+ liveChatWaitingText: "",
920
+ liveChatTeam: "",
921
+ surveySubmit: "Start chat",
922
+ surveyCancel: "Cancel",
923
+ surveyRequired: "Please fill this in",
924
+ surveyInvalidEmail: "Please enter an email address",
925
+ surveyTitle: "",
926
+ surveyIntro: "",
927
+ surveyPrefilled: "",
928
+ sheetClose: "Close"
929
+ };
930
+ const NEAR_LIMIT = .9;
931
+ const TYPING_SHOWN_MS = 5e3;
932
+ const TYPING_SENT_MS = 3e3;
933
+ const DRAFT_SENT_MS = 700;
934
+ /**
935
+ * Every element the binding adds to the thread carries a class under this block, so a host styles
936
+ * the chat by class rather than by the order its elements happen to come in.
937
+ */
938
+ const CHAT_CLASS = "vv-ai-chat";
939
+ const CONVERSATION_CONTEXT = "conversationId";
940
+ function firstName(name) {
941
+ return name.trim().split(/\s+/)[0] ?? name;
942
+ }
943
+ function initials(name) {
944
+ const words = name.trim().split(/\s+/).filter(Boolean);
945
+ return (words.length > 1 ? [words[0], words[words.length - 1]] : words).map((word) => [...word][0] ?? "").join("").toUpperCase();
946
+ }
947
+ function part(name) {
948
+ return `${CHAT_CLASS}__${name}`;
949
+ }
950
+ function kebab(name) {
951
+ return name.replace(/[A-Z_]/g, (character) => character === "_" ? "-" : `-${character.toLowerCase()}`);
952
+ }
953
+ /** Labels from `data-ai-chat-label-*` on the root, under the options and over the defaults. */
954
+ function readLabels(root, labels) {
955
+ const read = {};
956
+ for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
957
+ return read;
958
+ }
959
+ function stringRecord(value) {
960
+ if (!isPlainObject(value)) return {};
961
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
962
+ }
963
+ function storedActions(value) {
964
+ if (!Array.isArray(value)) return [];
965
+ return value.filter((item) => isPlainObject(item) && typeof item.label === "string" && typeof item.url === "string" && typeof item.sheet === "boolean");
966
+ }
967
+ function dataString(data, name) {
968
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
969
+ const value = data[name];
970
+ return typeof value === "string" && value.length > 0 && value.length <= 128 ? value : null;
971
+ }
972
+ function bindChat(root, options = {}) {
973
+ const form = root.querySelector("[data-ai-chat-form]");
974
+ const input = root.querySelector("[data-ai-chat-input]");
975
+ const thread = root.querySelector("[data-ai-chat-thread]");
976
+ const send = root.querySelector("[data-ai-chat-send]");
977
+ const stop = root.querySelector("[data-ai-chat-stop]");
978
+ const counter = root.querySelector("[data-ai-chat-counter]");
979
+ if (!form || !input || !thread) throw new Error("AI chat shell requires form, input and thread elements");
980
+ const chatThread = thread;
981
+ const labels = readLabels(root, options.labels);
982
+ const initialThread = chatThread.cloneNode(true);
983
+ let initialNodes = Array.from(chatThread.childNodes);
984
+ const endpoint = options.endpoint ?? root.dataset.aiChatEndpoint ?? form.action;
985
+ const header = options.antiforgeryHeader ?? root.dataset.aiChatAntiforgeryHeader;
986
+ const token = options.antiforgeryToken ?? root.dataset.aiChatAntiforgeryToken;
987
+ const headers = header && token ? { [header]: token } : {};
988
+ const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
989
+ const handoverEndpoint = options.handoverEndpoint ?? root.dataset.aiChatHandoverEndpoint;
990
+ const storageKey = options.storageKey ?? root.dataset.aiChatStorageKey;
991
+ const handoverPrefill = options.handoverPrefill ?? surveyAnswers(readJsonAttribute(root, "data-ai-chat-live-prefill", options.onError));
992
+ const liveChat = typeof options.liveChat === "function" ? options.liveChat({
993
+ root,
994
+ headers,
995
+ onError: (error) => options.onError?.(error)
996
+ }) : options.liveChat;
997
+ let activeAssistant = null;
998
+ let activeText = null;
999
+ let activeTextContent = "";
1000
+ let pendingTool = null;
1001
+ let followUps = [];
1002
+ let destroyed = false;
1003
+ const formContexts = /* @__PURE__ */ new Map();
1004
+ const cleanups = [];
1005
+ let entries = [];
1006
+ let activeEntry = null;
1007
+ let activeEntryText = null;
1008
+ let mode = "ai";
1009
+ let isOpen = root.hasAttribute("data-ai-chat-open");
1010
+ let live = null;
1011
+ let handoverInFlight = null;
1012
+ let handoverRuns = 0;
1013
+ let pendingSurvey = null;
1014
+ let typingIndicator = null;
1015
+ let typingTimer = null;
1016
+ let typingSentAt = 0;
1017
+ let draftTimer = null;
1018
+ let waitingCard = null;
1019
+ let sheet = null;
1020
+ const placeholder = input.placeholder;
1021
+ const eventListeners = /* @__PURE__ */ new Map();
1022
+ const session = createChatSession({
1023
+ endpoint,
1024
+ provider: options.provider ?? root.dataset.aiChatProvider,
1025
+ headers,
1026
+ timeoutMs: options.timeoutMs
1027
+ });
1028
+ function startConversation() {
1029
+ session.setContext(CONVERSATION_CONTEXT, crypto.randomUUID());
1030
+ }
1031
+ function listen(target, type, listener, options) {
1032
+ target.addEventListener(type, listener, options);
1033
+ cleanups.push(() => target.removeEventListener(type, listener, options));
1034
+ }
1035
+ function appendMessage(role) {
1036
+ const message = root.ownerDocument.createElement("div");
1037
+ message.dataset.aiChatMessage = role;
1038
+ message.className = `${part("message")} ${part(`message--${role}`)}`;
1039
+ chatThread.append(message);
1040
+ return message;
1041
+ }
1042
+ function appendMarkdown(parent, text) {
1043
+ const bubble = root.ownerDocument.createElement("div");
1044
+ bubble.dataset.aiChatText = "true";
1045
+ bubble.className = part("text");
1046
+ bubble.append(renderMarkdown(root.ownerDocument, text));
1047
+ parent.append(bubble);
1048
+ return bubble;
1049
+ }
1050
+ function appendStreamedMarkdown(text) {
1051
+ if (!activeAssistant) return;
1052
+ if (!activeText) {
1053
+ activeText = root.ownerDocument.createElement("div");
1054
+ activeText.dataset.aiChatText = "true";
1055
+ activeText.className = part("text");
1056
+ activeAssistant.append(activeText);
1057
+ }
1058
+ activeTextContent += text;
1059
+ activeText.replaceChildren(renderMarkdown(root.ownerDocument, activeTextContent));
1060
+ }
1061
+ function report(error) {
1062
+ options.onError?.(error);
1063
+ const message = root.ownerDocument.createElement("p");
1064
+ message.setAttribute("role", "alert");
1065
+ message.className = part("error");
1066
+ message.append(error.name === "TimeoutError" ? labels.timeout : labels.error);
1067
+ chatThread.append(message);
1068
+ }
1069
+ function label(name) {
1070
+ if (name in labels) return labels[name];
1071
+ return options.labels?.[name] || root.getAttribute(`data-ai-chat-label-${kebab(name)}`) || "";
1072
+ }
1073
+ function toolLabel(name) {
1074
+ if (!/^[\w-]{1,64}$/.test(name)) return labels.toolRunning;
1075
+ return options.toolLabels?.[name] || root.getAttribute(`data-ai-chat-tool-${kebab(name)}`) || labels.toolRunning;
1076
+ }
1077
+ function tool(id, name) {
1078
+ const element = root.ownerDocument.createElement("div");
1079
+ element.dataset.aiChatTool = id;
1080
+ element.className = part("tool");
1081
+ const dot = root.ownerDocument.createElement("span");
1082
+ dot.className = part("tool-dot");
1083
+ dot.setAttribute("aria-hidden", "true");
1084
+ const label = root.ownerDocument.createElement("span");
1085
+ label.className = part("tool-label");
1086
+ label.append(root.ownerDocument.createTextNode(toolLabel(name)));
1087
+ const status = root.ownerDocument.createElement("span");
1088
+ status.className = part("tool-status");
1089
+ element.append(dot, label, status);
1090
+ activeAssistant?.append(element);
1091
+ return element;
1092
+ }
1093
+ function clearPendingTool() {
1094
+ pendingTool?.remove();
1095
+ pendingTool = null;
1096
+ }
1097
+ function finishTool(id, failed, interrupted = false) {
1098
+ const element = activeAssistant?.querySelector(`[data-ai-chat-tool="${CSS.escape(id)}"]`);
1099
+ finishToolElement(element, failed, interrupted);
1100
+ }
1101
+ function finishToolElement(element, failed, interrupted) {
1102
+ if (element) {
1103
+ element.classList.add(part("tool--done"));
1104
+ element.classList.toggle(part("tool--failed"), failed || interrupted);
1105
+ const status = element.querySelector(`.${part("tool-status")}`);
1106
+ if (status) status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
1107
+ }
1108
+ }
1109
+ function renderResult(parent, result) {
1110
+ const context = {
1111
+ document: root.ownerDocument,
1112
+ root,
1113
+ tool: result.name,
1114
+ data: result.data,
1115
+ reply: result.reply,
1116
+ labels,
1117
+ label
1118
+ };
1119
+ let content = null;
1120
+ try {
1121
+ const templateName = dataString(result.data, "template");
1122
+ const surfaceName = dataString(result.data, "surface");
1123
+ if (templateName) content = root.querySelector(`template[data-template="${CSS.escape(templateName)}"]`)?.content.cloneNode(true) ?? null;
1124
+ if (!content && surfaceName) content = registryEntries(options.registry)?.surfaces.get(surfaceName)?.(context) ?? root.querySelector(`template[data-ai-surface="${CSS.escape(surfaceName)}"]`)?.content.cloneNode(true) ?? null;
1125
+ if (!content) content = registryEntries(options.registry)?.renderers.get(result.name)?.(context) ?? null;
1126
+ if (!content && isHandoverPayload(result.name, result.data)) content = renderHandoverCard(root.ownerDocument, result.data, labels);
1127
+ else content ??= renderAnswerCard(root.ownerDocument, result.data, labels);
1128
+ } catch (caught) {
1129
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat extension failed"));
1130
+ }
1131
+ if (content) {
1132
+ const wrapper = root.ownerDocument.createElement("div");
1133
+ wrapper.dataset.aiChatCard = "true";
1134
+ wrapper.className = part("result");
1135
+ wrapper.append(content);
1136
+ parent.append(wrapper);
1137
+ options.onEmbedded?.(wrapper);
1138
+ return wrapper;
1139
+ }
1140
+ if (result.reply) appendMarkdown(parent, result.reply);
1141
+ return null;
1142
+ }
1143
+ function checkLiveChat(card) {
1144
+ if (!liveChat || !card.querySelector(`[data-ai-action="livechat"]`)) return;
1145
+ liveChat.availability().then((availability) => {
1146
+ if (!destroyed && availability.status === "closed") closeHandoverCard(card, labels.liveChatClosed);
1147
+ }, (caught) => options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat availability failed")));
1148
+ }
1149
+ const unsubscribe = session.subscribe((event) => {
1150
+ if (destroyed) return;
1151
+ if (event.name === "delta" && activeAssistant) {
1152
+ clearPendingTool();
1153
+ appendStreamedMarkdown(event.data.text);
1154
+ if (activeEntry) {
1155
+ if (!activeEntryText) {
1156
+ activeEntryText = { text: "" };
1157
+ activeEntry.parts.push(activeEntryText);
1158
+ }
1159
+ activeEntryText.text += event.data.text;
1160
+ }
1161
+ } else if (event.name === "tool") {
1162
+ clearPendingTool();
1163
+ tool(event.data.id, event.data.name);
1164
+ } else if (event.name === "tool_result") {
1165
+ clearPendingTool();
1166
+ if (activeAssistant) {
1167
+ activeText = null;
1168
+ activeTextContent = "";
1169
+ const result = {
1170
+ name: event.data.name,
1171
+ data: event.data.data,
1172
+ reply: event.data.reply
1173
+ };
1174
+ const card = renderResult(activeAssistant, result);
1175
+ if (card && isHandoverPayload(result.name, result.data)) checkLiveChat(card);
1176
+ activeEntry?.parts.push({ result });
1177
+ activeEntryText = null;
1178
+ }
1179
+ } else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
1180
+ else if (event.name === "suggestions") followUps = event.data.suggestions;
1181
+ else if (event.name === "done" || event.name === "error") clearPendingTool();
1182
+ });
1183
+ function setBusy(busy) {
1184
+ if (busy) root.setAttribute("aria-busy", "true");
1185
+ else root.removeAttribute("aria-busy");
1186
+ if (send) {
1187
+ send.disabled = busy;
1188
+ if (stop) send.hidden = busy;
1189
+ }
1190
+ if (stop) stop.hidden = !busy;
1191
+ }
1192
+ const focusInput = () => {
1193
+ const view = root.ownerDocument.defaultView;
1194
+ const active = root.ownerDocument.activeElement;
1195
+ if (!view?.matchMedia?.("(pointer: fine)").matches || active && chatThread.contains(active)) return;
1196
+ input.focus({ preventScroll: true });
1197
+ };
1198
+ function appendFollowUps(parent, suggestions) {
1199
+ if (!suggestions.length) return;
1200
+ const list = root.ownerDocument.createElement("div");
1201
+ list.dataset.aiChatFollowUps = "true";
1202
+ list.className = part("follow-ups");
1203
+ list.setAttribute("role", "group");
1204
+ list.setAttribute("aria-label", labels.followUps);
1205
+ for (const suggestion of suggestions) {
1206
+ const button = root.ownerDocument.createElement("button");
1207
+ button.type = "button";
1208
+ button.className = part("follow-up");
1209
+ button.dataset.aiChatSuggestion = suggestion;
1210
+ button.append(root.ownerDocument.createTextNode(suggestion));
1211
+ list.append(button);
1212
+ }
1213
+ parent.append(list);
1214
+ }
1215
+ function appendReplyActions(parent, turn) {
1216
+ const template = root.querySelector("template[data-ai-chat-reply-actions]");
1217
+ if (!template) return;
1218
+ const actions = root.ownerDocument.createElement("div");
1219
+ actions.className = part("reply-actions");
1220
+ actions.append(template.content.cloneNode(true));
1221
+ if (turn && feedbackEndpoint) actions.dataset.aiChatTurn = turn;
1222
+ else for (const button of actions.querySelectorAll("[data-ai-chat-feedback]")) button.remove();
1223
+ if (actions.children.length) parent.append(actions);
1224
+ }
1225
+ async function copyReply(button) {
1226
+ const message = button.closest("[data-ai-chat-message]");
1227
+ const parts = Array.from(message?.querySelectorAll("[data-ai-chat-text], [data-ai-chat-card]") ?? [], (element) => (element.innerText ?? element.textContent ?? "").trim()).filter(Boolean);
1228
+ if (!parts.length) return;
1229
+ await navigator.clipboard.writeText(parts.join("\n\n"));
1230
+ button.dataset.aiChatCopied = "true";
1231
+ setTimeout(() => delete button.dataset.aiChatCopied, 2e3);
1232
+ }
1233
+ async function sendFeedback(button) {
1234
+ const actions = button.closest("[data-ai-chat-turn]");
1235
+ const rating = button.dataset.aiChatFeedback;
1236
+ if (!actions?.dataset.aiChatTurn || !feedbackEndpoint || rating !== "up" && rating !== "down") return;
1237
+ const response = await fetch(feedbackEndpoint, {
1238
+ method: "POST",
1239
+ headers: {
1240
+ "Content-Type": "application/json",
1241
+ ...headers
1242
+ },
1243
+ body: JSON.stringify({
1244
+ turn: actions.dataset.aiChatTurn,
1245
+ rating
1246
+ })
1247
+ });
1248
+ if (!response.ok) throw new Error(`AI chat feedback failed with ${response.status}`);
1249
+ for (const item of actions.querySelectorAll("[data-ai-chat-feedback]")) item.setAttribute("aria-pressed", String(item === button));
1250
+ }
1251
+ const updateCounter = () => {
1252
+ if (!counter || input.maxLength <= 0) return;
1253
+ counter.textContent = `${input.value.length} / ${input.maxLength}`;
1254
+ counter.toggleAttribute("data-ai-chat-near-limit", input.value.length >= input.maxLength * NEAR_LIMIT);
1255
+ };
1256
+ const resizeInput = () => {
1257
+ input.style.height = "auto";
1258
+ input.style.height = `${input.scrollHeight}px`;
1259
+ };
1260
+ function emit(name, detail) {
1261
+ for (const listener of eventListeners.get(name) ?? []) listener(detail);
1262
+ }
1263
+ function save() {
1264
+ if (!storageKey) return;
1265
+ const thread = {
1266
+ version: 1,
1267
+ conversationId: session.context[CONVERSATION_CONTEXT] ?? null,
1268
+ history: [...session.history],
1269
+ entries,
1270
+ open: isOpen,
1271
+ live: live?.resume ? {
1272
+ resume: live.resume,
1273
+ seen: [...live.seen],
1274
+ agent: live.agent
1275
+ } : null
1276
+ };
1277
+ writeThread(storageKey, thread);
1278
+ }
1279
+ function record(entry) {
1280
+ entries.push(entry);
1281
+ save();
1282
+ }
1283
+ function scrollToEnd() {
1284
+ const scroller = root.querySelector("[data-ai-chat-scroll]");
1285
+ scroller?.scrollTo({ top: scroller.scrollHeight });
1286
+ }
1287
+ function clearStart() {
1288
+ for (const node of initialNodes) node.remove();
1289
+ for (const list of chatThread.querySelectorAll("[data-ai-chat-follow-ups]")) list.remove();
1290
+ followUps = [];
1291
+ }
1292
+ const clearInput = () => {
1293
+ input.value = "";
1294
+ resizeInput();
1295
+ updateCounter();
1296
+ };
1297
+ function appendNotice(text, modifier) {
1298
+ const notice = root.ownerDocument.createElement("p");
1299
+ notice.dataset.aiChatNotice = modifier;
1300
+ notice.className = `${part("notice")} ${part(`notice--${modifier}`)}`;
1301
+ notice.setAttribute("role", modifier === "failed" ? "alert" : "status");
1302
+ notice.append(text);
1303
+ chatThread.append(notice);
1304
+ scrollToEnd();
1305
+ }
1306
+ function notify(text, modifier) {
1307
+ appendNotice(text, modifier);
1308
+ record({
1309
+ kind: "notice",
1310
+ text,
1311
+ modifier
1312
+ });
1313
+ }
1314
+ function appendInitials(parent, name) {
1315
+ const avatar = root.ownerDocument.createElement("span");
1316
+ avatar.className = part("initials");
1317
+ avatar.setAttribute("aria-hidden", "true");
1318
+ avatar.append(initials(name || labels.liveChatAgent));
1319
+ parent.append(avatar);
1320
+ }
1321
+ function appendPerson(name, text, actions = []) {
1322
+ const message = appendMessage("person");
1323
+ appendInitials(message, name);
1324
+ const sender = root.ownerDocument.createElement("span");
1325
+ sender.className = part("sender");
1326
+ const shown = name ? firstName(name) : labels.liveChatAgent;
1327
+ sender.append(labels.liveChatTeam ? `${shown} · ${labels.liveChatTeam}` : shown);
1328
+ message.append(sender);
1329
+ const bubble = text ? appendMarkdown(message, text) : null;
1330
+ const buttons = renderActions(root.ownerDocument, actions.map((action, index) => action.sheet ? {
1331
+ label: action.label,
1332
+ action: SHEET_ACTION,
1333
+ value: action.url,
1334
+ primary: index === 0
1335
+ } : {
1336
+ label: action.label,
1337
+ url: action.url,
1338
+ primary: index === 0
1339
+ }));
1340
+ if (buttons) (bubble ?? message).append(buttons);
1341
+ scrollToEnd();
1342
+ }
1343
+ function showSheet(url, title) {
1344
+ sheet?.close();
1345
+ let disconnectSheet = () => {};
1346
+ const opened = openSheet(root, {
1347
+ url,
1348
+ title,
1349
+ closeLabel: labels.sheetClose,
1350
+ onClose: () => {
1351
+ disconnectSheet();
1352
+ if (sheet === opened) sheet = null;
1353
+ }
1354
+ });
1355
+ sheet = opened;
1356
+ const provider = live?.provider ?? liveChat;
1357
+ if (opened && provider?.connectSheet) disconnectSheet = provider.connectSheet(opened.frame, {
1358
+ send: sendLive,
1359
+ close: opened.close
1360
+ });
1361
+ }
1362
+ function notifyAgent(template, name, modifier) {
1363
+ const time = new Intl.DateTimeFormat(root.ownerDocument.documentElement.lang || void 0, {
1364
+ hour: "2-digit",
1365
+ minute: "2-digit"
1366
+ }).format(/* @__PURE__ */ new Date());
1367
+ notify(`${template.replace("{name}", firstName(name))} · ${time}`, modifier);
1368
+ }
1369
+ function showWaiting() {
1370
+ if (waitingCard) return;
1371
+ waitingCard = root.ownerDocument.createElement("div");
1372
+ waitingCard.className = part("waiting");
1373
+ waitingCard.setAttribute("role", "status");
1374
+ const title = root.ownerDocument.createElement("p");
1375
+ title.className = part("waiting-title");
1376
+ title.append(labels.liveChatWaiting);
1377
+ waitingCard.append(title);
1378
+ if (labels.liveChatWaitingText) {
1379
+ const text = root.ownerDocument.createElement("p");
1380
+ text.className = part("waiting-text");
1381
+ text.append(labels.liveChatWaitingText);
1382
+ waitingCard.append(text);
1383
+ }
1384
+ chatThread.append(waitingCard);
1385
+ scrollToEnd();
1386
+ }
1387
+ function hideWaiting() {
1388
+ waitingCard?.remove();
1389
+ waitingCard = null;
1390
+ }
1391
+ function showAgent(name) {
1392
+ if (live) root.dataset.aiChatLive = name ? "agent" : "waiting";
1393
+ else delete root.dataset.aiChatLive;
1394
+ for (const element of root.querySelectorAll("[data-ai-chat-agent-name]")) element.textContent = name ?? "";
1395
+ for (const element of root.querySelectorAll("[data-ai-chat-agent-initials]")) element.textContent = name ? initials(name) : "";
1396
+ }
1397
+ function hideTyping() {
1398
+ if (typingTimer) clearTimeout(typingTimer);
1399
+ typingTimer = null;
1400
+ typingIndicator?.remove();
1401
+ typingIndicator = null;
1402
+ }
1403
+ function showTyping() {
1404
+ if (!typingIndicator) {
1405
+ typingIndicator = root.ownerDocument.createElement("div");
1406
+ typingIndicator.dataset.aiChatTyping = "true";
1407
+ typingIndicator.className = part("typing");
1408
+ typingIndicator.setAttribute("role", "status");
1409
+ appendInitials(typingIndicator, live?.agent ?? null);
1410
+ const dots = root.ownerDocument.createElement("span");
1411
+ dots.className = part("typing-dots");
1412
+ dots.setAttribute("aria-hidden", "true");
1413
+ for (let dot = 0; dot < 3; dot++) {
1414
+ const span = root.ownerDocument.createElement("span");
1415
+ span.className = part("typing-dot");
1416
+ dots.append(span);
1417
+ }
1418
+ const label = root.ownerDocument.createElement("span");
1419
+ label.className = part("typing-label");
1420
+ label.append(labels.liveChatTyping);
1421
+ typingIndicator.append(dots, label);
1422
+ }
1423
+ chatThread.append(typingIndicator);
1424
+ if (typingTimer) clearTimeout(typingTimer);
1425
+ typingTimer = setTimeout(hideTyping, TYPING_SHOWN_MS);
1426
+ scrollToEnd();
1427
+ }
1428
+ function renderEntry(entry) {
1429
+ if (entry.kind === "user" && typeof entry.text === "string") appendMarkdown(appendMessage("user"), entry.text);
1430
+ else if (entry.kind === "assistant" && Array.isArray(entry.parts)) {
1431
+ const message = appendMessage("assistant");
1432
+ for (const item of entry.parts) if ("text" in item && typeof item.text === "string") appendMarkdown(message, item.text);
1433
+ else if ("result" in item && isPlainObject(item.result) && typeof item.result.name === "string") renderResult(message, item.result);
1434
+ appendReplyActions(message, typeof entry.turn === "string" ? entry.turn : null);
1435
+ } else if (entry.kind === "person" && typeof entry.text === "string") appendPerson(typeof entry.name === "string" ? entry.name : null, entry.text, storedActions(entry.actions));
1436
+ else if (entry.kind === "notice" && typeof entry.text === "string" && typeof entry.modifier === "string") appendNotice(entry.text, entry.modifier);
1437
+ }
1438
+ const setMode = (next) => {
1439
+ mode = next;
1440
+ root.dataset.aiChatMode = next;
1441
+ input.disabled = next === "handover";
1442
+ for (const button of root.querySelectorAll("[data-ai-chat-end]")) button.hidden = next !== "live";
1443
+ input.placeholder = next === "live" ? input.dataset.aiChatLivePlaceholder ?? placeholder : next === "handover" ? input.dataset.aiChatHandoverPlaceholder ?? placeholder : placeholder;
1444
+ };
1445
+ function setOpen(next) {
1446
+ if (next === isOpen) return;
1447
+ isOpen = next;
1448
+ root.toggleAttribute("data-ai-chat-open", next);
1449
+ save();
1450
+ emit(next ? "open" : "close", void 0);
1451
+ if (next) {
1452
+ scrollToEnd();
1453
+ focusInput();
1454
+ }
1455
+ }
1456
+ function receiveLive(message) {
1457
+ if (!live || live.seen.has(message.id)) return;
1458
+ live.seen.add(message.id);
1459
+ hideTyping();
1460
+ if (message.sender === "agent" && !live.agent) agentJoined({ name: message.name });
1461
+ if (message.sender === "system") notify(message.text, "system");
1462
+ else {
1463
+ appendPerson(message.name, message.text, message.actions);
1464
+ record({
1465
+ kind: "person",
1466
+ id: message.id,
1467
+ text: message.text,
1468
+ name: message.name,
1469
+ ...message.actions?.length ? { actions: message.actions } : {}
1470
+ });
1471
+ }
1472
+ }
1473
+ function agentJoined(agent) {
1474
+ if (!live) return;
1475
+ const name = agent.name?.trim() || labels.liveChatAgent;
1476
+ if (live.agent === name) return;
1477
+ live.agent = name;
1478
+ hideWaiting();
1479
+ showAgent(name);
1480
+ notifyAgent(labels.liveChatJoined, name, "joined");
1481
+ emit("agent", { name: agent.name?.trim() || null });
1482
+ }
1483
+ function connect(provider, resume, seen, agent = null) {
1484
+ live = {
1485
+ provider,
1486
+ resume,
1487
+ seen: new Set(seen),
1488
+ agent,
1489
+ unsubscribes: [
1490
+ provider.onMessage(receiveLive),
1491
+ provider.onTyping(showTyping),
1492
+ provider.onEnded(() => finishLive("agent")),
1493
+ ...provider.onAgent ? [provider.onAgent(agentJoined)] : []
1494
+ ]
1495
+ };
1496
+ showAgent(agent);
1497
+ }
1498
+ function disconnect() {
1499
+ for (const unsubscribe of live?.unsubscribes ?? []) unsubscribe();
1500
+ live = null;
1501
+ hideTyping();
1502
+ hideWaiting();
1503
+ showAgent(null);
1504
+ }
1505
+ function finishLive(reason) {
1506
+ if (!live) return;
1507
+ const agent = live.agent;
1508
+ disconnect();
1509
+ setMode("ai");
1510
+ if (reason === "agent" && agent) notifyAgent(labels.liveChatAgentEnded, agent, "agent-ended");
1511
+ notify(labels.liveChatEnded, "ended");
1512
+ emit("end", { reason });
1513
+ }
1514
+ async function requestHandover() {
1515
+ if (!handoverEndpoint) return {
1516
+ transcript: null,
1517
+ context: {}
1518
+ };
1519
+ try {
1520
+ const response = await fetch(handoverEndpoint, {
1521
+ method: "POST",
1522
+ headers: {
1523
+ "Content-Type": "application/json",
1524
+ ...headers
1525
+ },
1526
+ body: JSON.stringify({
1527
+ conversationId: session.context[CONVERSATION_CONTEXT],
1528
+ culture: session.context.culture,
1529
+ messages: session.history
1530
+ })
1531
+ });
1532
+ if (!response.ok) throw new Error(`AI chat handover request failed with ${response.status}`);
1533
+ const body = await response.json();
1534
+ return {
1535
+ transcript: (isPlainObject(body) && typeof body.transcript === "string" ? body.transcript.trim() : "") || null,
1536
+ context: stringRecord(isPlainObject(body) ? body.context : null)
1537
+ };
1538
+ } catch (caught) {
1539
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover request failed"));
1540
+ return {
1541
+ transcript: null,
1542
+ context: {}
1543
+ };
1544
+ }
1545
+ }
1546
+ async function runHandover(handover) {
1547
+ const provider = handover.provider ?? liveChat;
1548
+ if (!provider) throw new Error("AI chat handover needs a live chat provider");
1549
+ const run = ++handoverRuns;
1550
+ const stale = () => destroyed || run !== handoverRuns;
1551
+ session.cancel();
1552
+ clearStart();
1553
+ setMode("handover");
1554
+ let started = false;
1555
+ try {
1556
+ const availability = await provider.availability();
1557
+ if (stale()) return { status: "canceled" };
1558
+ if (availability.status === "closed") {
1559
+ notify(labels.liveChatClosed, "closed");
1560
+ setMode("ai");
1561
+ return availability;
1562
+ }
1563
+ const handoff = requestHandover();
1564
+ const fields = await provider.survey();
1565
+ let answers = {};
1566
+ if (fields?.length && !stale()) {
1567
+ const survey = renderSurveyForm(root.ownerDocument, fields, {
1568
+ labels: {
1569
+ submit: labels.surveySubmit,
1570
+ cancel: labels.surveyCancel,
1571
+ required: labels.surveyRequired,
1572
+ invalidEmail: labels.surveyInvalidEmail,
1573
+ title: labels.surveyTitle,
1574
+ intro: labels.surveyIntro,
1575
+ prefilled: labels.surveyPrefilled
1576
+ },
1577
+ prefill: {
1578
+ ...handoverPrefill,
1579
+ ...handover.prefill
1580
+ }
1581
+ });
1582
+ pendingSurvey = survey;
1583
+ const wrapper = root.ownerDocument.createElement("div");
1584
+ wrapper.className = part("survey");
1585
+ wrapper.append(survey.form);
1586
+ chatThread.append(wrapper);
1587
+ scrollToEnd();
1588
+ survey.form.querySelector("input, textarea, select")?.focus({ preventScroll: true });
1589
+ const submitted = await survey.answers;
1590
+ pendingSurvey = null;
1591
+ wrapper.remove();
1592
+ if (!submitted) {
1593
+ if (!stale()) setMode("ai");
1594
+ return { status: "canceled" };
1595
+ }
1596
+ answers = submitted;
1597
+ }
1598
+ if (stale()) return { status: "canceled" };
1599
+ notify(labels.liveChatConnecting, "connecting");
1600
+ const server = await handoff;
1601
+ connect(provider, null, []);
1602
+ started = true;
1603
+ await provider.start({
1604
+ answers,
1605
+ context: {
1606
+ ...server.context,
1607
+ ...handover.context
1608
+ },
1609
+ openingMessage: server.transcript ?? void 0
1610
+ });
1611
+ if (stale()) {
1612
+ await provider.end();
1613
+ return { status: "canceled" };
1614
+ }
1615
+ const resume = await provider.resumeToken();
1616
+ if (live) live.resume = resume;
1617
+ setMode("live");
1618
+ notify(labels.liveChatStarted, "started");
1619
+ if (!live?.agent) showWaiting();
1620
+ emit("handover", void 0);
1621
+ return { status: "live" };
1622
+ } catch (caught) {
1623
+ const error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover failed");
1624
+ options.onError?.(error);
1625
+ if (started) {
1626
+ disconnect();
1627
+ provider.end().catch(() => void 0);
1628
+ }
1629
+ if (!stale()) {
1630
+ notify(labels.liveChatFailed, "failed");
1631
+ setMode("ai");
1632
+ }
1633
+ return {
1634
+ status: "failed",
1635
+ error
1636
+ };
1637
+ }
1638
+ }
1639
+ function resumeLive(stored) {
1640
+ const provider = liveChat;
1641
+ if (!provider) {
1642
+ notify(labels.liveChatEnded, "ended");
1643
+ return;
1644
+ }
1645
+ connect(provider, stored.resume, stored.seen, stored.agent ?? null);
1646
+ setMode("live");
1647
+ if (!stored.agent) showWaiting();
1648
+ provider.start({ resume: stored.resume }).catch((caught) => {
1649
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat live chat could not reconnect"));
1650
+ if (live?.provider === provider) finishLive("disconnected");
1651
+ });
1652
+ }
1653
+ async function sendLive(text) {
1654
+ if (!live) return;
1655
+ clearStart();
1656
+ appendMarkdown(appendMessage("user"), text);
1657
+ record({
1658
+ kind: "user",
1659
+ text
1660
+ });
1661
+ scrollToEnd();
1662
+ await live.provider.send(text);
1663
+ }
1664
+ const submit = async (event) => {
1665
+ event?.preventDefault();
1666
+ const question = input.value.trim();
1667
+ if (!question || mode === "handover") return;
1668
+ if (mode === "live") {
1669
+ if (draftTimer) {
1670
+ clearTimeout(draftTimer);
1671
+ draftTimer = null;
1672
+ }
1673
+ clearInput();
1674
+ sendLive(question).catch(report);
1675
+ return;
1676
+ }
1677
+ if (session.status !== "idle") return;
1678
+ clearInput();
1679
+ clearStart();
1680
+ appendMarkdown(appendMessage("user"), question);
1681
+ entries.push({
1682
+ kind: "user",
1683
+ text: question
1684
+ });
1685
+ activeEntry = {
1686
+ kind: "assistant",
1687
+ parts: [],
1688
+ turn: null
1689
+ };
1690
+ activeEntryText = null;
1691
+ entries.push(activeEntry);
1692
+ activeAssistant = appendMessage("assistant");
1693
+ activeText = null;
1694
+ activeTextContent = "";
1695
+ pendingTool = tool("pending", "");
1696
+ setBusy(true);
1697
+ const assistant = activeAssistant;
1698
+ const entry = activeEntry;
1699
+ const result = await session.send(question);
1700
+ if (destroyed) return;
1701
+ setBusy(false);
1702
+ entry.turn = result.turn;
1703
+ if (!entry.parts.length) entries = entries.filter((item) => item !== entry);
1704
+ if (activeEntry === entry) {
1705
+ activeEntry = null;
1706
+ activeEntryText = null;
1707
+ }
1708
+ save();
1709
+ if (result.error && !result.canceled) report(result.error);
1710
+ if (!result.error && assistant.isConnected && assistant.childNodes.length) {
1711
+ appendReplyActions(assistant, result.turn);
1712
+ appendFollowUps(assistant, followUps);
1713
+ }
1714
+ focusInput();
1715
+ if (result.canceled) activeAssistant?.querySelectorAll(`[data-ai-chat-tool]:not(.${part("tool--done")})`).forEach((item) => {
1716
+ finishToolElement(item, false, true);
1717
+ });
1718
+ };
1719
+ const click = (event) => {
1720
+ const target = event.target instanceof Element ? event.target : null;
1721
+ const suggestion = target?.closest("[data-ai-chat-suggestion]");
1722
+ if (suggestion) {
1723
+ input.value = suggestion.dataset.aiChatSuggestion ?? suggestion.textContent?.trim() ?? "";
1724
+ submit();
1725
+ return;
1726
+ }
1727
+ if (target?.closest("[data-ai-chat-stop]")) {
1728
+ session.cancel();
1729
+ return;
1730
+ }
1731
+ const copy = target?.closest("[data-ai-chat-copy]");
1732
+ if (copy) {
1733
+ copyReply(copy).catch(report);
1734
+ return;
1735
+ }
1736
+ const feedback = target?.closest("[data-ai-chat-feedback]");
1737
+ if (feedback) {
1738
+ sendFeedback(feedback).catch(report);
1739
+ return;
1740
+ }
1741
+ if (target?.closest("[data-ai-chat-close]")) {
1742
+ setOpen(false);
1743
+ return;
1744
+ }
1745
+ if (target?.closest("[data-ai-chat-end]")) {
1746
+ binding.endLiveChat().catch(report);
1747
+ return;
1748
+ }
1749
+ if (target?.closest("[data-ai-chat-reset]")) {
1750
+ const provider = live?.provider;
1751
+ sheet?.close();
1752
+ disconnect();
1753
+ handoverRuns += 1;
1754
+ pendingSurvey?.cancel();
1755
+ setMode("ai");
1756
+ if (provider) {
1757
+ emit("end", { reason: "visitor" });
1758
+ provider.end().catch(report);
1759
+ }
1760
+ if (storageKey) clearThread(storageKey);
1761
+ entries = [];
1762
+ activeEntry = null;
1763
+ activeEntryText = null;
1764
+ session.reset();
1765
+ chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
1766
+ initialNodes = Array.from(chatThread.childNodes);
1767
+ input.value = "";
1768
+ resizeInput();
1769
+ activeAssistant = null;
1770
+ activeText = null;
1771
+ activeTextContent = "";
1772
+ pendingTool = null;
1773
+ followUps = [];
1774
+ formContexts.clear();
1775
+ startConversation();
1776
+ updateCounter();
1777
+ focusInput();
1778
+ return;
1779
+ }
1780
+ const actionElement = target?.closest("[data-ai-action]");
1781
+ const action = actionElement ? registryEntries(options.registry)?.actions.get(actionElement.dataset.aiAction ?? "") : void 0;
1782
+ if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover({ prefill: buttonPrefill(actionElement) }).catch(report);
1783
+ else if (!action && actionElement?.dataset.aiAction === "sheet") showSheet(actionElement.dataset.aiActionValue ?? "", actionElement.textContent?.trim() ?? "");
1784
+ else if (action && actionElement) Promise.resolve(action({
1785
+ root,
1786
+ element: actionElement,
1787
+ value: actionElement.dataset.aiActionValue ?? null,
1788
+ session
1789
+ })).then((result) => {
1790
+ if (result) session.setContext(...result.context);
1791
+ }).catch(report);
1792
+ };
1793
+ const keydown = (event) => {
1794
+ if (event.key === "Enter" && !event.shiftKey) {
1795
+ event.preventDefault();
1796
+ submit();
1797
+ }
1798
+ };
1799
+ function followAnswer() {
1800
+ const scroller = root.querySelector("[data-ai-chat-scroll]");
1801
+ if (!scroller) return;
1802
+ let question = null;
1803
+ let following = false;
1804
+ const release = () => {
1805
+ following = false;
1806
+ };
1807
+ listen(scroller, "wheel", release, { passive: true });
1808
+ listen(scroller, "touchmove", release, { passive: true });
1809
+ const observer = new MutationObserver(() => {
1810
+ const questions = chatThread.querySelectorAll("[data-ai-chat-message=\"user\"]");
1811
+ const latest = questions[questions.length - 1] ?? null;
1812
+ if (latest !== question) {
1813
+ question = latest;
1814
+ following = true;
1815
+ }
1816
+ if (!question || !following || root.getAttribute("aria-busy") !== "true") return;
1817
+ const top = question.getBoundingClientRect().top - chatThread.getBoundingClientRect().top - Number.parseFloat(getComputedStyle(chatThread).paddingTop || "0");
1818
+ following = top > scroller.scrollHeight - scroller.clientHeight;
1819
+ scroller.scrollTo({ top });
1820
+ });
1821
+ observer.observe(chatThread, {
1822
+ childList: true,
1823
+ subtree: true
1824
+ });
1825
+ cleanups.push(() => observer.disconnect());
1826
+ }
1827
+ function trackKeyboard() {
1828
+ const viewport = root.ownerDocument.defaultView?.visualViewport;
1829
+ if (!viewport) return;
1830
+ const apply = () => {
1831
+ const covered = window.innerHeight - viewport.height - viewport.offsetTop;
1832
+ root.style.setProperty(`--${CHAT_CLASS}-keyboard`, `${Math.max(0, covered)}px`);
1833
+ };
1834
+ apply();
1835
+ listen(viewport, "resize", apply);
1836
+ listen(viewport, "scroll", apply);
1837
+ }
1838
+ function trackOffset() {
1839
+ const selector = root.dataset.aiChatOffset;
1840
+ const element = options.offsetElement ?? (selector ? root.ownerDocument.querySelector(selector) : null);
1841
+ if (!element) return;
1842
+ const apply = () => root.style.setProperty(`--${CHAT_CLASS}-offset`, `${element.offsetHeight}px`);
1843
+ apply();
1844
+ const observer = new ResizeObserver(apply);
1845
+ observer.observe(element);
1846
+ cleanups.push(() => observer.disconnect());
1847
+ }
1848
+ listen(form, "submit", submit);
1849
+ listen(root, "click", click);
1850
+ listen(input, "keydown", keydown);
1851
+ const typingFailed = (caught) => {
1852
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat typing event failed"));
1853
+ };
1854
+ listen(input, "input", () => {
1855
+ resizeInput();
1856
+ updateCounter();
1857
+ if (!live || mode !== "live") return;
1858
+ if (live.provider.draft) draftTimer ??= setTimeout(() => {
1859
+ draftTimer = null;
1860
+ if (live && mode === "live") live.provider.draft?.(input.value.trim()).catch(typingFailed);
1861
+ }, DRAFT_SENT_MS);
1862
+ else if (input.value && Date.now() - typingSentAt > TYPING_SENT_MS) {
1863
+ typingSentAt = Date.now();
1864
+ live.provider.typing().catch(typingFailed);
1865
+ }
1866
+ });
1867
+ setBusy(false);
1868
+ setMode("ai");
1869
+ updateCounter();
1870
+ followAnswer();
1871
+ trackKeyboard();
1872
+ trackOffset();
1873
+ const stored = storageKey ? readThread(storageKey) : null;
1874
+ if (stored) {
1875
+ session.restoreHistory(stored.history);
1876
+ if (stored.entries.length) {
1877
+ clearStart();
1878
+ for (const entry of stored.entries) renderEntry(entry);
1879
+ entries = [...stored.entries];
1880
+ }
1881
+ isOpen = stored.open === true;
1882
+ root.toggleAttribute("data-ai-chat-open", isOpen);
1883
+ scrollToEnd();
1884
+ }
1885
+ if (stored?.conversationId) session.setContext(CONVERSATION_CONTEXT, stored.conversationId);
1886
+ else startConversation();
1887
+ if (stored?.live) resumeLive(stored.live);
1888
+ const binding = {
1889
+ root,
1890
+ session,
1891
+ labels,
1892
+ headers,
1893
+ get mode() {
1894
+ return mode;
1895
+ },
1896
+ get isOpen() {
1897
+ return isOpen;
1898
+ },
1899
+ get liveChat() {
1900
+ return live?.provider ?? null;
1901
+ },
1902
+ label,
1903
+ appendAssistantReply(text) {
1904
+ const content = text.trim();
1905
+ if (!content) return;
1906
+ appendMarkdown(appendMessage("assistant"), content);
1907
+ session.addAssistantReply(content);
1908
+ record({
1909
+ kind: "assistant",
1910
+ parts: [{ text: content }],
1911
+ turn: null
1912
+ });
1913
+ },
1914
+ setFormContext(name, summary, followUp) {
1915
+ const content = summary.trim();
1916
+ if (!content || formContexts.get(name) === content) return;
1917
+ const first = !formContexts.has(name);
1918
+ formContexts.set(name, content);
1919
+ session.setContextMessage(name, content);
1920
+ if (first && followUp) binding.appendAssistantReply(followUp);
1921
+ else save();
1922
+ },
1923
+ open() {
1924
+ setOpen(true);
1925
+ },
1926
+ close() {
1927
+ setOpen(false);
1928
+ },
1929
+ handover(handover = {}) {
1930
+ if (mode === "live") return Promise.resolve({ status: "live" });
1931
+ handoverInFlight ??= runHandover(handover).finally(() => {
1932
+ handoverInFlight = null;
1933
+ });
1934
+ return handoverInFlight;
1935
+ },
1936
+ async endLiveChat() {
1937
+ const provider = live?.provider;
1938
+ if (!provider) return;
1939
+ finishLive("visitor");
1940
+ await provider.end();
1941
+ },
1942
+ on(name, listener) {
1943
+ let listeners = eventListeners.get(name);
1944
+ if (!listeners) {
1945
+ listeners = /* @__PURE__ */ new Set();
1946
+ eventListeners.set(name, listeners);
1947
+ }
1948
+ const added = listener;
1949
+ listeners.add(added);
1950
+ return () => {
1951
+ listeners.delete(added);
1952
+ };
1953
+ },
1954
+ destroy() {
1955
+ if (destroyed) return;
1956
+ destroyed = true;
1957
+ sheet?.close();
1958
+ pendingSurvey?.cancel();
1959
+ disconnect();
1960
+ eventListeners.clear();
1961
+ unsubscribe();
1962
+ session.dispose();
1963
+ for (const cleanup of cleanups.splice(0)) cleanup();
1964
+ }
1965
+ };
1966
+ return binding;
1967
+ }
1968
+ //#endregion
1969
+ //#region src/window.ts
1970
+ /**
1971
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
1972
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
1973
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
1974
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
1975
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
1976
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
1977
+ */
1978
+ function bindChatWindow(binding) {
1979
+ const document = binding.root.ownerDocument;
1980
+ const menu = binding.root.querySelector("details[data-ai-chat-menu]");
1981
+ const summary = menu?.querySelector("summary") ?? null;
1982
+ const toggles = () => document.querySelectorAll("[data-ai-chat-window-toggle]");
1983
+ const sync = () => {
1984
+ for (const toggle of toggles()) toggle.setAttribute("aria-expanded", String(binding.isOpen));
1985
+ };
1986
+ const click = (event) => {
1987
+ const target = event.target instanceof Element ? event.target : null;
1988
+ if (menu?.open && !(target && summary?.contains(target))) menu.open = false;
1989
+ const opener = target?.closest("[data-ai-chat-window-open]");
1990
+ if (opener) {
1991
+ if (opener.hasAttribute("data-ai-chat-window-toggle") && binding.isOpen) binding.close();
1992
+ else binding.open();
1993
+ return;
1994
+ }
1995
+ const expand = target?.closest("[data-ai-chat-expand]");
1996
+ if (expand && binding.root.contains(expand)) binding.close();
1997
+ };
1998
+ const keydown = (event) => {
1999
+ if (event.key !== "Escape") return;
2000
+ if (menu?.open) {
2001
+ menu.open = false;
2002
+ summary?.focus();
2003
+ } else if (binding.isOpen) binding.close();
2004
+ };
2005
+ document.addEventListener("click", click);
2006
+ document.addEventListener("keydown", keydown);
2007
+ const unsubscribes = [binding.on("open", sync), binding.on("close", () => {
2008
+ sync();
2009
+ toggles()[0]?.focus();
2010
+ })];
2011
+ sync();
2012
+ return () => {
2013
+ document.removeEventListener("click", click);
2014
+ document.removeEventListener("keydown", keydown);
2015
+ for (const unsubscribe of unsubscribes) unsubscribe();
2016
+ };
2017
+ }
2018
+ function teaserShown(key) {
2019
+ if (!key) return false;
2020
+ try {
2021
+ return window.sessionStorage.getItem(key) !== null;
2022
+ } catch {
2023
+ return true;
2024
+ }
2025
+ }
2026
+ function markTeaserShown(key) {
2027
+ if (!key) return;
2028
+ try {
2029
+ window.sessionStorage.setItem(key, "1");
2030
+ } catch {}
2031
+ }
2032
+ /**
2033
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
2034
+ * started a chat: not while the window is open or its thread has messages. A
2035
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
2036
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
2037
+ */
2038
+ function bindLauncherTeaser(binding, container, options = {}) {
2039
+ const teaser = container.querySelector("[data-ai-launcher-teaser]");
2040
+ const key = options.storageKey || teaser?.dataset.aiLauncherTeaser || "";
2041
+ if (!teaser || binding.isOpen || teaserShown(key) || binding.root.querySelector("[data-ai-chat-message]")) return () => void 0;
2042
+ teaser.hidden = false;
2043
+ markTeaserShown(key);
2044
+ const hide = () => {
2045
+ teaser.hidden = true;
2046
+ };
2047
+ const dismiss = teaser.querySelector("[data-ai-launcher-dismiss]");
2048
+ dismiss?.addEventListener("click", hide);
2049
+ const unsubscribe = binding.on("open", hide);
2050
+ return () => {
2051
+ dismiss?.removeEventListener("click", hide);
2052
+ unsubscribe();
2053
+ };
2054
+ }
2055
+ //#endregion
2056
+ export { MAX_ANSWER_CARD_URL_LENGTH as A, MAX_ANSWER_CARD_TABLES as C, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS as D, MAX_ANSWER_CARD_TEXT_LENGTH as E, isAnswerCard as M, renderAnswerCard as N, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS as O, MAX_ANSWER_CARD_SECTIONS as S, MAX_ANSWER_CARD_TABLE_ROWS as T, renderActions as _, createAiChatRegistry as a, MAX_ANSWER_CARD_FACTS as b, closeHandoverCard as c, createChatSession as d, readEventStream as f, CARD_LIST_CLASS as g, ACTIONS_CLASS as h, bindChat as i, assertAnswerCardContract as j, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS as k, isHandoverPayload as l, parseStreamEvent as m, bindLauncherTeaser as n, HANDOVER_TOOL as o, AI_CHAT_PROTOCOL_VERSION as p, CHAT_CLASS as r, LIVE_CHAT_ACTION as s, bindChatWindow as t, renderHandoverCard as u, renderCardList as v, MAX_ANSWER_CARD_TABLE_CELLS as w, MAX_ANSWER_CARD_LINKS as x, ANSWER_CARD_CLASS as y };