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