@vettvangur/ai-sdk 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,292 +1,6 @@
1
- //#region src/dom.ts
2
- function hasUnsafeLinkCharacter(value) {
3
- for (const character of value) {
4
- const code = character.charCodeAt(0);
5
- if (/\s/.test(character) || character === "\\" || code <= 31 || code >= 127 && code <= 159) return true;
6
- }
7
- return false;
8
- }
9
- function isSafeLinkUrl(url) {
10
- if (url.length === 0 || hasUnsafeLinkCharacter(url)) return false;
11
- if (url.startsWith("/") || url.startsWith("#")) return !url.startsWith("//");
12
- if (/^https?:\/\//i.test(url)) try {
13
- const parsed = new URL(url);
14
- return parsed.protocol === "http:" || parsed.protocol === "https:";
15
- } catch {
16
- return false;
17
- }
18
- return /^(?:mailto|tel):[^:]+$/i.test(url);
19
- }
20
- function createSafeLink(document, label, url) {
21
- if (!isSafeLinkUrl(url)) return null;
22
- const link = document.createElement("a");
23
- link.href = url;
24
- link.append(document.createTextNode(label));
25
- if (/^https?:\/\//i.test(url)) {
26
- link.target = "_blank";
27
- link.rel = "noopener noreferrer";
28
- }
29
- return link;
30
- }
31
- function isPlainObject(value) {
32
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
33
- const prototype = Object.getPrototypeOf(value);
34
- return prototype === Object.prototype || prototype === null;
35
- }
36
- /**
37
- * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
38
- * width and height, when given, let the browser reserve the space before the image arrives.
39
- */
40
- function createSafeImage(document, image) {
41
- if (!image || typeof image.url !== "string" || !/^(https?:\/\/|\/)/i.test(image.url) || !isSafeLinkUrl(image.url)) return null;
42
- const element = document.createElement("img");
43
- element.src = image.url;
44
- element.alt = typeof image.alt === "string" ? image.alt : "";
45
- element.loading = "lazy";
46
- element.decoding = "async";
47
- if (typeof image.url2x === "string" && /^(https?:\/\/|\/)/i.test(image.url2x) && isSafeLinkUrl(image.url2x)) element.srcset = `${image.url} 1x, ${image.url2x} 2x`;
48
- if (image.width && image.height) {
49
- element.width = image.width;
50
- element.height = image.height;
51
- }
52
- return element;
53
- }
54
- /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
55
- function createPart(document, tag, block, part, text) {
56
- const element = document.createElement(tag);
57
- element.className = part ? `${block}__${part}` : block;
58
- if (text) element.textContent = text;
59
- return element;
60
- }
61
- //#endregion
62
- //#region src/markdown.ts
63
- const MAX_MARKDOWN_CHARACTERS = 8e3;
64
- function isWordCharacter(character) {
65
- return character !== void 0 && /[\p{L}\p{N}]/u.test(character);
66
- }
67
- function delimitedToken(source, start, marker, type) {
68
- if (!source.startsWith(marker, start)) return null;
69
- const contentStart = start + marker.length;
70
- const closing = source.indexOf(marker, contentStart);
71
- if (closing === -1 || closing === contentStart) return null;
72
- return {
73
- type,
74
- content: source.slice(contentStart, closing),
75
- end: closing + marker.length
76
- };
77
- }
78
- function linkToken(source, start) {
79
- if (source[start] !== "[") return null;
80
- let labelEnd = start + 1;
81
- while (labelEnd < source.length) {
82
- if (source[labelEnd] === "[") return null;
83
- if (source[labelEnd] === "]" && source[labelEnd + 1] === "(") break;
84
- labelEnd += 1;
85
- }
86
- if (labelEnd === source.length) return {
87
- type: "text",
88
- content: source.slice(start),
89
- end: source.length
90
- };
91
- if (labelEnd === start + 1) return null;
92
- let depth = 1;
93
- let end = labelEnd + 2;
94
- while (end < source.length && depth > 0) {
95
- if (source[end] === "(") depth += 1;
96
- else if (source[end] === ")") depth -= 1;
97
- end += 1;
98
- }
99
- if (depth !== 0) return {
100
- type: "text",
101
- content: source.slice(start),
102
- end: source.length
103
- };
104
- const url = source.slice(labelEnd + 2, end - 1);
105
- if (!isSafeLinkUrl(url)) return {
106
- type: "text",
107
- content: source.slice(start, end),
108
- end
109
- };
110
- return {
111
- type: "link",
112
- label: source.slice(start + 1, labelEnd),
113
- url,
114
- end
115
- };
116
- }
117
- function inlineToken(source, start) {
118
- const link = linkToken(source, start);
119
- if (link) return link;
120
- const code = delimitedToken(source, start, "`", "code");
121
- if (code) return code;
122
- const bold = delimitedToken(source, start, "**", "bold") ?? delimitedToken(source, start, "__", "bold");
123
- if (bold) return bold;
124
- const marker = source[start];
125
- if ((marker === "*" || marker === "_") && !isWordCharacter(source[start - 1])) return delimitedToken(source, start, marker, "italic");
126
- return null;
127
- }
128
- function inlineStructuralItemCount(source) {
129
- let count = 0;
130
- let index = 0;
131
- while (index < source.length) {
132
- const token = inlineToken(source, index);
133
- if (!token) {
134
- index += 1;
135
- continue;
136
- }
137
- switch (token.type) {
138
- case "bold":
139
- case "italic":
140
- count += 1 + inlineStructuralItemCount(token.content);
141
- break;
142
- case "code":
143
- case "link": count += 1;
144
- }
145
- index = token.end;
146
- }
147
- return count;
148
- }
149
- function appendInlineMarkdown(document, parent, source) {
150
- let textStart = 0;
151
- let index = 0;
152
- while (index < source.length) {
153
- const token = inlineToken(source, index);
154
- if (!token) {
155
- index += 1;
156
- continue;
157
- }
158
- if (textStart < index) parent.append(document.createTextNode(source.slice(textStart, index)));
159
- switch (token.type) {
160
- case "code": {
161
- const code = document.createElement("code");
162
- code.append(document.createTextNode(token.content));
163
- parent.append(code);
164
- break;
165
- }
166
- case "bold": {
167
- const strong = document.createElement("strong");
168
- appendInlineMarkdown(document, strong, token.content);
169
- parent.append(strong);
170
- break;
171
- }
172
- case "italic": {
173
- const emphasis = document.createElement("em");
174
- appendInlineMarkdown(document, emphasis, token.content);
175
- parent.append(emphasis);
176
- break;
177
- }
178
- case "link": {
179
- const link = createSafeLink(document, token.label, token.url);
180
- if (link) parent.append(link);
181
- else parent.append(document.createTextNode(source.slice(index, token.end)));
182
- break;
183
- }
184
- case "text": parent.append(document.createTextNode(token.content));
185
- }
186
- index = token.end;
187
- textStart = index;
188
- }
189
- if (textStart < source.length) parent.append(document.createTextNode(source.slice(textStart)));
190
- }
191
- function unorderedListItem(line) {
192
- return /^\s*[-+*]\s+(.+)$/.exec(line)?.[1] ?? null;
193
- }
194
- function orderedListItem(line) {
195
- return /^\s*\d+[.)]\s+(.+)$/.exec(line)?.[1] ?? null;
196
- }
197
- function heading(line) {
198
- return /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/.exec(line)?.[1] ?? null;
199
- }
200
- function countMarkdownStructuralItems(source) {
201
- const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
202
- let count = 0;
203
- let index = 0;
204
- while (index < lines.length) {
205
- const line = lines[index];
206
- if (line.trim().length === 0) {
207
- index += 1;
208
- continue;
209
- }
210
- const headingText = heading(line);
211
- if (headingText !== null) {
212
- count += 2 + inlineStructuralItemCount(headingText);
213
- index += 1;
214
- continue;
215
- }
216
- const unorderedItem = unorderedListItem(line);
217
- const orderedItem = orderedListItem(line);
218
- if (unorderedItem !== null || orderedItem !== null) {
219
- const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
220
- count += 1;
221
- while (index < lines.length) {
222
- const item = itemForLine(lines[index]);
223
- if (item === null) break;
224
- count += 1 + inlineStructuralItemCount(item);
225
- index += 1;
226
- }
227
- continue;
228
- }
229
- const paragraphLines = [];
230
- while (index < lines.length) {
231
- const paragraphLine = lines[index];
232
- if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
233
- paragraphLines.push(paragraphLine);
234
- index += 1;
235
- }
236
- count += 1 + inlineStructuralItemCount(paragraphLines.join(" "));
237
- }
238
- return count;
239
- }
240
- function renderMarkdown(document, source) {
241
- const fragment = document.createDocumentFragment();
242
- const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
243
- let index = 0;
244
- while (index < lines.length) {
245
- const line = lines[index];
246
- if (line.trim().length === 0) {
247
- index += 1;
248
- continue;
249
- }
250
- const headingText = heading(line);
251
- if (headingText !== null) {
252
- const paragraph = document.createElement("p");
253
- const strong = document.createElement("strong");
254
- appendInlineMarkdown(document, strong, headingText);
255
- paragraph.append(strong);
256
- fragment.append(paragraph);
257
- index += 1;
258
- continue;
259
- }
260
- const unorderedItem = unorderedListItem(line);
261
- const orderedItem = orderedListItem(line);
262
- if (unorderedItem !== null || orderedItem !== null) {
263
- const list = document.createElement(unorderedItem === null ? "ol" : "ul");
264
- const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
265
- while (index < lines.length) {
266
- const item = itemForLine(lines[index]);
267
- if (item === null) break;
268
- const listItem = document.createElement("li");
269
- appendInlineMarkdown(document, listItem, item);
270
- list.append(listItem);
271
- index += 1;
272
- }
273
- fragment.append(list);
274
- continue;
275
- }
276
- const paragraphLines = [];
277
- while (index < lines.length) {
278
- const paragraphLine = lines[index];
279
- if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
280
- paragraphLines.push(paragraphLine);
281
- index += 1;
282
- }
283
- const paragraph = document.createElement("p");
284
- appendInlineMarkdown(document, paragraph, paragraphLines.join(" "));
285
- fragment.append(paragraph);
286
- }
287
- return fragment;
288
- }
289
- //#endregion
1
+ import { a as isSafeLinkUrl, i as isPlainObject, n as createSafeImage, o as readJsonAttribute, r as createSafeLink, t as createPart } from "./dom.js";
2
+ import { i as renderMarkdown, n as renderSurveyForm, r as countMarkdownStructuralItems } from "./survey.js";
3
+ import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
290
4
  //#region src/answer-card.ts
291
5
  const ANSWER_CARD_KEYS = /* @__PURE__ */ new Set([
292
6
  "kind",
@@ -620,6 +334,35 @@ function renderAnswerCard(document, data, labels) {
620
334
  if (isPlainObject(data) && data.kind === "answer") return isAnswerCard(data) ? renderKnownAnswerCard(document, data, labels) : null;
621
335
  return renderGenericAnswerCard(document, data);
622
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
+ }
623
366
  //#endregion
624
367
  //#region src/protocol.ts
625
368
  const AI_CHAT_PROTOCOL_VERSION = 1;
@@ -906,6 +649,11 @@ function createChatSession(options) {
906
649
  contextMessages.set(name, message);
907
650
  history.push(message);
908
651
  },
652
+ restoreHistory(messages) {
653
+ session.cancel();
654
+ history.splice(0, history.length, ...messages.map((message) => ({ ...message })));
655
+ contextMessages.clear();
656
+ },
909
657
  addAssistantReply(content) {
910
658
  const value = content.trim();
911
659
  if (!value) throw new Error("AI chat assistant replies cannot be empty");
@@ -930,6 +678,85 @@ function createChatSession(options) {
930
678
  return session;
931
679
  }
932
680
  //#endregion
681
+ //#region src/cards.ts
682
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
683
+ const CARD_LIST_CLASS = "vv-ai-card-list";
684
+ const ACTIONS_CLASS = "vv-ai-actions";
685
+ function text(value) {
686
+ return typeof value === "string" && value.trim() ? value : null;
687
+ }
688
+ /**
689
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
690
+ * Items that render nothing are skipped, and a list with nothing in it is null.
691
+ */
692
+ function renderCardList(document, items, render, modifier) {
693
+ if (!Array.isArray(items)) return null;
694
+ const cards = items.map(render).filter((card) => card !== null);
695
+ if (!cards.length) return null;
696
+ const list = createPart(document, "div", CARD_LIST_CLASS);
697
+ if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
698
+ list.append(...cards);
699
+ return list;
700
+ }
701
+ /**
702
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
703
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
704
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
705
+ */
706
+ function renderActions(document, items) {
707
+ const elements = [];
708
+ for (const item of items) {
709
+ const label = text(item?.label);
710
+ if (!label) continue;
711
+ let element = null;
712
+ const action = text(item.action);
713
+ const url = text(item.url);
714
+ if (action) {
715
+ const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
716
+ button.type = "button";
717
+ button.dataset.aiAction = action;
718
+ const value = text(item.value);
719
+ if (value) button.dataset.aiActionValue = value;
720
+ element = button;
721
+ } else if (url) {
722
+ element = createSafeLink(document, label, url.trim());
723
+ if (element) element.className = `${ACTIONS_CLASS}__action`;
724
+ }
725
+ if (element) {
726
+ element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
727
+ elements.push(element);
728
+ }
729
+ }
730
+ if (!elements.length) return null;
731
+ const actions = createPart(document, "div", ACTIONS_CLASS);
732
+ actions.append(...elements);
733
+ return actions;
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
933
760
  //#region src/registry.ts
934
761
  const entries = /* @__PURE__ */ new WeakMap();
935
762
  function register(map, name, value) {
@@ -957,6 +784,35 @@ function registryEntries(registry) {
957
784
  return registry ? entries.get(registry) : void 0;
958
785
  }
959
786
  //#endregion
787
+ //#region src/thread-store.ts
788
+ function storage() {
789
+ try {
790
+ return window.sessionStorage;
791
+ } catch {
792
+ return null;
793
+ }
794
+ }
795
+ function readThread(key) {
796
+ try {
797
+ const raw = storage()?.getItem(key);
798
+ const parsed = raw ? JSON.parse(raw) : null;
799
+ if (!isPlainObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.history) || !Array.isArray(parsed.entries)) return null;
800
+ return parsed;
801
+ } catch {
802
+ return null;
803
+ }
804
+ }
805
+ function writeThread(key, thread) {
806
+ try {
807
+ storage()?.setItem(key, JSON.stringify(thread));
808
+ } catch {}
809
+ }
810
+ function clearThread(key) {
811
+ try {
812
+ storage()?.removeItem(key);
813
+ } catch {}
814
+ }
815
+ //#endregion
960
816
  //#region src/bind.ts
961
817
  const defaultLabels = {
962
818
  error: "Something went wrong. Please try again.",
@@ -969,15 +825,46 @@ const defaultLabels = {
969
825
  details: "Details",
970
826
  table: "Published table",
971
827
  tableScroll: "Scroll sideways to see all columns",
972
- followUps: "Suggested questions"
828
+ followUps: "Suggested questions",
829
+ liveChat: "Chat with a person",
830
+ contact: "Contact us",
831
+ liveChatConnecting: "Connecting you to a person",
832
+ liveChatClosed: "No one is available to chat right now.",
833
+ liveChatEnded: "The chat has ended. You are talking to the AI again.",
834
+ liveChatFailed: "We could not connect you to a person. Please try again.",
835
+ liveChatTyping: "Typing",
836
+ liveChatAgent: "Agent",
837
+ liveChatStarted: "Chat with a person started",
838
+ liveChatJoined: "{name} joined the chat",
839
+ liveChatAgentEnded: "{name} ended the chat",
840
+ liveChatWaiting: "One moment, connecting you",
841
+ liveChatWaitingText: "",
842
+ liveChatTeam: "",
843
+ surveySubmit: "Start chat",
844
+ surveyCancel: "Cancel",
845
+ surveyRequired: "Please fill this in",
846
+ surveyInvalidEmail: "Please enter an email address",
847
+ surveyTitle: "",
848
+ surveyIntro: "",
849
+ surveyPrefilled: ""
973
850
  };
974
851
  const NEAR_LIMIT = .9;
852
+ const TYPING_SHOWN_MS = 5e3;
853
+ const TYPING_SENT_MS = 3e3;
854
+ const DRAFT_SENT_MS = 700;
975
855
  /**
976
856
  * Every element the binding adds to the thread carries a class under this block, so a host styles
977
857
  * the chat by class rather than by the order its elements happen to come in.
978
858
  */
979
859
  const CHAT_CLASS = "vv-ai-chat";
980
860
  const CONVERSATION_CONTEXT = "conversationId";
861
+ function firstName(name) {
862
+ return name.trim().split(/\s+/)[0] ?? name;
863
+ }
864
+ function initials(name) {
865
+ const words = name.trim().split(/\s+/).filter(Boolean);
866
+ return (words.length > 1 ? [words[0], words[words.length - 1]] : words).map((word) => [...word][0] ?? "").join("").toUpperCase();
867
+ }
981
868
  function part(name) {
982
869
  return `${CHAT_CLASS}__${name}`;
983
870
  }
@@ -990,6 +877,14 @@ function readLabels(root, labels) {
990
877
  for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
991
878
  return read;
992
879
  }
880
+ function answers(value) {
881
+ if (!isPlainObject(value)) return;
882
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" || typeof entry[1] === "boolean"));
883
+ }
884
+ function stringRecord(value) {
885
+ if (!isPlainObject(value)) return {};
886
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
887
+ }
993
888
  function dataString(data, name) {
994
889
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
995
890
  const value = data[name];
@@ -1010,8 +905,16 @@ function bindChat(root, options = {}) {
1010
905
  const endpoint = options.endpoint ?? root.dataset.aiChatEndpoint ?? form.action;
1011
906
  const header = options.antiforgeryHeader ?? root.dataset.aiChatAntiforgeryHeader;
1012
907
  const token = options.antiforgeryToken ?? root.dataset.aiChatAntiforgeryToken;
1013
- const headers = header && token ? { [header]: token } : void 0;
908
+ const headers = header && token ? { [header]: token } : {};
1014
909
  const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
910
+ const handoverEndpoint = options.handoverEndpoint ?? root.dataset.aiChatHandoverEndpoint;
911
+ const storageKey = options.storageKey ?? root.dataset.aiChatStorageKey;
912
+ const handoverPrefill = options.handoverPrefill ?? answers(readJsonAttribute(root, "data-ai-chat-live-prefill", options.onError));
913
+ const liveChat = typeof options.liveChat === "function" ? options.liveChat({
914
+ root,
915
+ headers,
916
+ onError: (error) => options.onError?.(error)
917
+ }) : options.liveChat;
1015
918
  let activeAssistant = null;
1016
919
  let activeText = null;
1017
920
  let activeTextContent = "";
@@ -1020,6 +923,22 @@ function bindChat(root, options = {}) {
1020
923
  let destroyed = false;
1021
924
  const formContexts = /* @__PURE__ */ new Map();
1022
925
  const cleanups = [];
926
+ let entries = [];
927
+ let activeEntry = null;
928
+ let activeEntryText = null;
929
+ let mode = "ai";
930
+ let isOpen = root.hasAttribute("data-ai-chat-open");
931
+ let live = null;
932
+ let handoverInFlight = null;
933
+ let handoverRuns = 0;
934
+ let pendingSurvey = null;
935
+ let typingIndicator = null;
936
+ let typingTimer = null;
937
+ let typingSentAt = 0;
938
+ let draftTimer = null;
939
+ let waitingCard = null;
940
+ const placeholder = input.placeholder;
941
+ const eventListeners = /* @__PURE__ */ new Map();
1023
942
  const session = createChatSession({
1024
943
  endpoint,
1025
944
  provider: options.provider ?? root.dataset.aiChatProvider,
@@ -1066,6 +985,10 @@ function bindChat(root, options = {}) {
1066
985
  message.append(error.name === "TimeoutError" ? labels.timeout : labels.error);
1067
986
  chatThread.append(message);
1068
987
  }
988
+ function label(name) {
989
+ if (name in labels) return labels[name];
990
+ return options.labels?.[name] || root.getAttribute(`data-ai-chat-label-${kebab(name)}`) || "";
991
+ }
1069
992
  function toolLabel(name) {
1070
993
  if (!/^[\w-]{1,64}$/.test(name)) return labels.toolRunning;
1071
994
  return options.toolLabels?.[name] || root.getAttribute(`data-ai-chat-tool-${kebab(name)}`) || labels.toolRunning;
@@ -1102,26 +1025,25 @@ function bindChat(root, options = {}) {
1102
1025
  if (status) status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
1103
1026
  }
1104
1027
  }
1105
- function renderResult(event) {
1106
- if (!activeAssistant) return;
1107
- activeText = null;
1108
- activeTextContent = "";
1028
+ function renderResult(parent, result) {
1109
1029
  const context = {
1110
1030
  document: root.ownerDocument,
1111
1031
  root,
1112
- tool: event.data.name,
1113
- data: event.data.data,
1114
- reply: event.data.reply,
1115
- labels
1032
+ tool: result.name,
1033
+ data: result.data,
1034
+ reply: result.reply,
1035
+ labels,
1036
+ label
1116
1037
  };
1117
1038
  let content = null;
1118
1039
  try {
1119
- const templateName = dataString(event.data.data, "template");
1120
- const surfaceName = dataString(event.data.data, "surface");
1040
+ const templateName = dataString(result.data, "template");
1041
+ const surfaceName = dataString(result.data, "surface");
1121
1042
  if (templateName) content = root.querySelector(`template[data-template="${CSS.escape(templateName)}"]`)?.content.cloneNode(true) ?? null;
1122
1043
  if (!content && surfaceName) content = registryEntries(options.registry)?.surfaces.get(surfaceName)?.(context) ?? root.querySelector(`template[data-ai-surface="${CSS.escape(surfaceName)}"]`)?.content.cloneNode(true) ?? null;
1123
- if (!content) content = registryEntries(options.registry)?.renderers.get(event.data.name)?.(context) ?? null;
1124
- content ??= renderAnswerCard(root.ownerDocument, event.data.data, labels);
1044
+ if (!content) content = registryEntries(options.registry)?.renderers.get(result.name)?.(context) ?? null;
1045
+ if (!content && isHandoverPayload(result.name, result.data)) content = renderHandoverCard(root.ownerDocument, result.data, labels);
1046
+ else content ??= renderAnswerCard(root.ownerDocument, result.data, labels);
1125
1047
  } catch (caught) {
1126
1048
  options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat extension failed"));
1127
1049
  }
@@ -1130,21 +1052,39 @@ function bindChat(root, options = {}) {
1130
1052
  wrapper.dataset.aiChatCard = "true";
1131
1053
  wrapper.className = part("result");
1132
1054
  wrapper.append(content);
1133
- activeAssistant.append(wrapper);
1055
+ parent.append(wrapper);
1134
1056
  options.onEmbedded?.(wrapper);
1135
- } else if (event.data.reply) appendMarkdown(activeAssistant, event.data.reply);
1057
+ } else if (result.reply) appendMarkdown(parent, result.reply);
1136
1058
  }
1137
1059
  const unsubscribe = session.subscribe((event) => {
1138
1060
  if (destroyed) return;
1139
1061
  if (event.name === "delta" && activeAssistant) {
1140
1062
  clearPendingTool();
1141
1063
  appendStreamedMarkdown(event.data.text);
1064
+ if (activeEntry) {
1065
+ if (!activeEntryText) {
1066
+ activeEntryText = { text: "" };
1067
+ activeEntry.parts.push(activeEntryText);
1068
+ }
1069
+ activeEntryText.text += event.data.text;
1070
+ }
1142
1071
  } else if (event.name === "tool") {
1143
1072
  clearPendingTool();
1144
1073
  tool(event.data.id, event.data.name);
1145
1074
  } else if (event.name === "tool_result") {
1146
1075
  clearPendingTool();
1147
- renderResult(event);
1076
+ if (activeAssistant) {
1077
+ activeText = null;
1078
+ activeTextContent = "";
1079
+ const result = {
1080
+ name: event.data.name,
1081
+ data: event.data.data,
1082
+ reply: event.data.reply
1083
+ };
1084
+ renderResult(activeAssistant, result);
1085
+ activeEntry?.parts.push({ result });
1086
+ activeEntryText = null;
1087
+ }
1148
1088
  } else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
1149
1089
  else if (event.name === "suggestions") followUps = event.data.suggestions;
1150
1090
  else if (event.name === "done" || event.name === "error") clearPendingTool();
@@ -1226,26 +1166,418 @@ function bindChat(root, options = {}) {
1226
1166
  input.style.height = "auto";
1227
1167
  input.style.height = `${input.scrollHeight}px`;
1228
1168
  };
1229
- const submit = async (event) => {
1230
- event?.preventDefault();
1231
- const question = input.value.trim();
1232
- if (!question || session.status !== "idle") return;
1233
- input.value = "";
1234
- resizeInput();
1235
- updateCounter();
1169
+ function emit(name, detail) {
1170
+ for (const listener of eventListeners.get(name) ?? []) listener(detail);
1171
+ }
1172
+ function save() {
1173
+ if (!storageKey) return;
1174
+ const thread = {
1175
+ version: 1,
1176
+ conversationId: session.context[CONVERSATION_CONTEXT] ?? null,
1177
+ history: [...session.history],
1178
+ entries,
1179
+ open: isOpen,
1180
+ live: live?.resume ? {
1181
+ resume: live.resume,
1182
+ seen: [...live.seen],
1183
+ agent: live.agent
1184
+ } : null
1185
+ };
1186
+ writeThread(storageKey, thread);
1187
+ }
1188
+ function record(entry) {
1189
+ entries.push(entry);
1190
+ save();
1191
+ }
1192
+ function scrollToEnd() {
1193
+ const scroller = root.querySelector("[data-ai-chat-scroll]");
1194
+ scroller?.scrollTo({ top: scroller.scrollHeight });
1195
+ }
1196
+ function clearStart() {
1236
1197
  for (const node of initialNodes) node.remove();
1237
1198
  for (const list of chatThread.querySelectorAll("[data-ai-chat-follow-ups]")) list.remove();
1238
1199
  followUps = [];
1200
+ }
1201
+ const clearInput = () => {
1202
+ input.value = "";
1203
+ resizeInput();
1204
+ updateCounter();
1205
+ };
1206
+ function appendNotice(text, modifier) {
1207
+ const notice = root.ownerDocument.createElement("p");
1208
+ notice.dataset.aiChatNotice = modifier;
1209
+ notice.className = `${part("notice")} ${part(`notice--${modifier}`)}`;
1210
+ notice.setAttribute("role", modifier === "failed" ? "alert" : "status");
1211
+ notice.append(text);
1212
+ chatThread.append(notice);
1213
+ scrollToEnd();
1214
+ }
1215
+ function notify(text, modifier) {
1216
+ appendNotice(text, modifier);
1217
+ record({
1218
+ kind: "notice",
1219
+ text,
1220
+ modifier
1221
+ });
1222
+ }
1223
+ function appendInitials(parent, name) {
1224
+ const avatar = root.ownerDocument.createElement("span");
1225
+ avatar.className = part("initials");
1226
+ avatar.setAttribute("aria-hidden", "true");
1227
+ avatar.append(initials(name || labels.liveChatAgent));
1228
+ parent.append(avatar);
1229
+ }
1230
+ function appendPerson(name, text) {
1231
+ const message = appendMessage("person");
1232
+ appendInitials(message, name);
1233
+ const sender = root.ownerDocument.createElement("span");
1234
+ sender.className = part("sender");
1235
+ const shown = name ? firstName(name) : labels.liveChatAgent;
1236
+ sender.append(labels.liveChatTeam ? `${shown} · ${labels.liveChatTeam}` : shown);
1237
+ message.append(sender);
1238
+ appendMarkdown(message, text);
1239
+ scrollToEnd();
1240
+ }
1241
+ function notifyAgent(template, name, modifier) {
1242
+ const time = new Intl.DateTimeFormat(root.ownerDocument.documentElement.lang || void 0, {
1243
+ hour: "2-digit",
1244
+ minute: "2-digit"
1245
+ }).format(/* @__PURE__ */ new Date());
1246
+ notify(`${template.replace("{name}", firstName(name))} · ${time}`, modifier);
1247
+ }
1248
+ function showWaiting() {
1249
+ if (waitingCard) return;
1250
+ waitingCard = root.ownerDocument.createElement("div");
1251
+ waitingCard.className = part("waiting");
1252
+ waitingCard.setAttribute("role", "status");
1253
+ const title = root.ownerDocument.createElement("p");
1254
+ title.className = part("waiting-title");
1255
+ title.append(labels.liveChatWaiting);
1256
+ waitingCard.append(title);
1257
+ if (labels.liveChatWaitingText) {
1258
+ const text = root.ownerDocument.createElement("p");
1259
+ text.className = part("waiting-text");
1260
+ text.append(labels.liveChatWaitingText);
1261
+ waitingCard.append(text);
1262
+ }
1263
+ chatThread.append(waitingCard);
1264
+ scrollToEnd();
1265
+ }
1266
+ function hideWaiting() {
1267
+ waitingCard?.remove();
1268
+ waitingCard = null;
1269
+ }
1270
+ function showAgent(name) {
1271
+ if (live) root.dataset.aiChatLive = name ? "agent" : "waiting";
1272
+ else delete root.dataset.aiChatLive;
1273
+ for (const element of root.querySelectorAll("[data-ai-chat-agent-name]")) element.textContent = name ?? "";
1274
+ for (const element of root.querySelectorAll("[data-ai-chat-agent-initials]")) element.textContent = name ? initials(name) : "";
1275
+ }
1276
+ function hideTyping() {
1277
+ if (typingTimer) clearTimeout(typingTimer);
1278
+ typingTimer = null;
1279
+ typingIndicator?.remove();
1280
+ typingIndicator = null;
1281
+ }
1282
+ function showTyping() {
1283
+ if (!typingIndicator) {
1284
+ typingIndicator = root.ownerDocument.createElement("div");
1285
+ typingIndicator.dataset.aiChatTyping = "true";
1286
+ typingIndicator.className = part("typing");
1287
+ typingIndicator.setAttribute("role", "status");
1288
+ appendInitials(typingIndicator, live?.agent ?? null);
1289
+ const dots = root.ownerDocument.createElement("span");
1290
+ dots.className = part("typing-dots");
1291
+ dots.setAttribute("aria-hidden", "true");
1292
+ for (let dot = 0; dot < 3; dot++) {
1293
+ const span = root.ownerDocument.createElement("span");
1294
+ span.className = part("typing-dot");
1295
+ dots.append(span);
1296
+ }
1297
+ const label = root.ownerDocument.createElement("span");
1298
+ label.className = part("typing-label");
1299
+ label.append(labels.liveChatTyping);
1300
+ typingIndicator.append(dots, label);
1301
+ }
1302
+ chatThread.append(typingIndicator);
1303
+ if (typingTimer) clearTimeout(typingTimer);
1304
+ typingTimer = setTimeout(hideTyping, TYPING_SHOWN_MS);
1305
+ scrollToEnd();
1306
+ }
1307
+ function renderEntry(entry) {
1308
+ if (entry.kind === "user" && typeof entry.text === "string") appendMarkdown(appendMessage("user"), entry.text);
1309
+ else if (entry.kind === "assistant" && Array.isArray(entry.parts)) {
1310
+ const message = appendMessage("assistant");
1311
+ for (const item of entry.parts) if ("text" in item && typeof item.text === "string") appendMarkdown(message, item.text);
1312
+ else if ("result" in item && isPlainObject(item.result) && typeof item.result.name === "string") renderResult(message, item.result);
1313
+ appendReplyActions(message, typeof entry.turn === "string" ? entry.turn : null);
1314
+ } else if (entry.kind === "person" && typeof entry.text === "string") appendPerson(typeof entry.name === "string" ? entry.name : null, entry.text);
1315
+ else if (entry.kind === "notice" && typeof entry.text === "string" && typeof entry.modifier === "string") appendNotice(entry.text, entry.modifier);
1316
+ }
1317
+ const setMode = (next) => {
1318
+ mode = next;
1319
+ root.dataset.aiChatMode = next;
1320
+ input.disabled = next === "handover";
1321
+ for (const button of root.querySelectorAll("[data-ai-chat-end]")) button.hidden = next !== "live";
1322
+ input.placeholder = next === "live" ? input.dataset.aiChatLivePlaceholder ?? placeholder : next === "handover" ? input.dataset.aiChatHandoverPlaceholder ?? placeholder : placeholder;
1323
+ };
1324
+ function setOpen(next) {
1325
+ if (next === isOpen) return;
1326
+ isOpen = next;
1327
+ root.toggleAttribute("data-ai-chat-open", next);
1328
+ save();
1329
+ emit(next ? "open" : "close", void 0);
1330
+ if (next) {
1331
+ scrollToEnd();
1332
+ focusInput();
1333
+ }
1334
+ }
1335
+ function receiveLive(message) {
1336
+ if (!live || live.seen.has(message.id)) return;
1337
+ live.seen.add(message.id);
1338
+ hideTyping();
1339
+ if (message.sender === "agent" && !live.agent) agentJoined({ name: message.name });
1340
+ if (message.sender === "system") notify(message.text, "system");
1341
+ else {
1342
+ appendPerson(message.name, message.text);
1343
+ record({
1344
+ kind: "person",
1345
+ id: message.id,
1346
+ text: message.text,
1347
+ name: message.name
1348
+ });
1349
+ }
1350
+ }
1351
+ function agentJoined(agent) {
1352
+ if (!live) return;
1353
+ const name = agent.name?.trim() || labels.liveChatAgent;
1354
+ if (live.agent === name) return;
1355
+ live.agent = name;
1356
+ hideWaiting();
1357
+ showAgent(name);
1358
+ notifyAgent(labels.liveChatJoined, name, "joined");
1359
+ emit("agent", { name: agent.name?.trim() || null });
1360
+ }
1361
+ function connect(provider, resume, seen, agent = null) {
1362
+ live = {
1363
+ provider,
1364
+ resume,
1365
+ seen: new Set(seen),
1366
+ agent,
1367
+ unsubscribes: [
1368
+ provider.onMessage(receiveLive),
1369
+ provider.onTyping(showTyping),
1370
+ provider.onEnded(() => finishLive("agent")),
1371
+ ...provider.onAgent ? [provider.onAgent(agentJoined)] : []
1372
+ ]
1373
+ };
1374
+ showAgent(agent);
1375
+ }
1376
+ function disconnect() {
1377
+ for (const unsubscribe of live?.unsubscribes ?? []) unsubscribe();
1378
+ live = null;
1379
+ hideTyping();
1380
+ hideWaiting();
1381
+ showAgent(null);
1382
+ }
1383
+ function finishLive(reason) {
1384
+ if (!live) return;
1385
+ const agent = live.agent;
1386
+ disconnect();
1387
+ setMode("ai");
1388
+ if (reason === "agent" && agent) notifyAgent(labels.liveChatAgentEnded, agent, "agent-ended");
1389
+ notify(labels.liveChatEnded, "ended");
1390
+ emit("end", { reason });
1391
+ }
1392
+ async function requestHandover() {
1393
+ if (!handoverEndpoint) return {
1394
+ transcript: null,
1395
+ context: {}
1396
+ };
1397
+ try {
1398
+ const response = await fetch(handoverEndpoint, {
1399
+ method: "POST",
1400
+ headers: {
1401
+ "Content-Type": "application/json",
1402
+ ...headers
1403
+ },
1404
+ body: JSON.stringify({
1405
+ conversationId: session.context[CONVERSATION_CONTEXT],
1406
+ culture: session.context.culture,
1407
+ messages: session.history
1408
+ })
1409
+ });
1410
+ if (!response.ok) throw new Error(`AI chat handover request failed with ${response.status}`);
1411
+ const body = await response.json();
1412
+ return {
1413
+ transcript: (isPlainObject(body) && typeof body.transcript === "string" ? body.transcript.trim() : "") || null,
1414
+ context: stringRecord(isPlainObject(body) ? body.context : null)
1415
+ };
1416
+ } catch (caught) {
1417
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover request failed"));
1418
+ return {
1419
+ transcript: null,
1420
+ context: {}
1421
+ };
1422
+ }
1423
+ }
1424
+ async function runHandover(handover) {
1425
+ const provider = handover.provider ?? liveChat;
1426
+ if (!provider) throw new Error("AI chat handover needs a live chat provider");
1427
+ const run = ++handoverRuns;
1428
+ const stale = () => destroyed || run !== handoverRuns;
1429
+ session.cancel();
1430
+ clearStart();
1431
+ setMode("handover");
1432
+ let started = false;
1433
+ try {
1434
+ const availability = await provider.availability();
1435
+ if (stale()) return { status: "canceled" };
1436
+ if (availability.status === "closed") {
1437
+ notify(labels.liveChatClosed, "closed");
1438
+ setMode("ai");
1439
+ return availability;
1440
+ }
1441
+ const handoff = requestHandover();
1442
+ const fields = await provider.survey();
1443
+ let answers = {};
1444
+ if (fields?.length && !stale()) {
1445
+ const survey = renderSurveyForm(root.ownerDocument, fields, {
1446
+ labels: {
1447
+ submit: labels.surveySubmit,
1448
+ cancel: labels.surveyCancel,
1449
+ required: labels.surveyRequired,
1450
+ invalidEmail: labels.surveyInvalidEmail,
1451
+ title: labels.surveyTitle,
1452
+ intro: labels.surveyIntro,
1453
+ prefilled: labels.surveyPrefilled
1454
+ },
1455
+ prefill: handover.prefill ?? handoverPrefill
1456
+ });
1457
+ pendingSurvey = survey;
1458
+ const wrapper = root.ownerDocument.createElement("div");
1459
+ wrapper.className = part("survey");
1460
+ wrapper.append(survey.form);
1461
+ chatThread.append(wrapper);
1462
+ scrollToEnd();
1463
+ survey.form.querySelector("input, textarea, select")?.focus({ preventScroll: true });
1464
+ const submitted = await survey.answers;
1465
+ pendingSurvey = null;
1466
+ wrapper.remove();
1467
+ if (!submitted) {
1468
+ if (!stale()) setMode("ai");
1469
+ return { status: "canceled" };
1470
+ }
1471
+ answers = submitted;
1472
+ }
1473
+ if (stale()) return { status: "canceled" };
1474
+ notify(labels.liveChatConnecting, "connecting");
1475
+ const server = await handoff;
1476
+ connect(provider, null, []);
1477
+ started = true;
1478
+ await provider.start({
1479
+ answers,
1480
+ context: {
1481
+ ...server.context,
1482
+ ...handover.context
1483
+ },
1484
+ openingMessage: server.transcript ?? void 0
1485
+ });
1486
+ if (stale()) {
1487
+ await provider.end();
1488
+ return { status: "canceled" };
1489
+ }
1490
+ const resume = await provider.resumeToken();
1491
+ if (live) live.resume = resume;
1492
+ setMode("live");
1493
+ notify(labels.liveChatStarted, "started");
1494
+ if (!live?.agent) showWaiting();
1495
+ emit("handover", void 0);
1496
+ return { status: "live" };
1497
+ } catch (caught) {
1498
+ const error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover failed");
1499
+ options.onError?.(error);
1500
+ if (started) disconnect();
1501
+ if (!stale()) {
1502
+ notify(labels.liveChatFailed, "failed");
1503
+ setMode("ai");
1504
+ }
1505
+ return {
1506
+ status: "failed",
1507
+ error
1508
+ };
1509
+ }
1510
+ }
1511
+ function resumeLive(stored) {
1512
+ const provider = liveChat;
1513
+ if (!provider) {
1514
+ notify(labels.liveChatEnded, "ended");
1515
+ return;
1516
+ }
1517
+ connect(provider, stored.resume, stored.seen, stored.agent ?? null);
1518
+ setMode("live");
1519
+ if (!stored.agent) showWaiting();
1520
+ provider.start({ resume: stored.resume }).catch((caught) => {
1521
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat live chat could not reconnect"));
1522
+ if (live?.provider === provider) finishLive("disconnected");
1523
+ });
1524
+ }
1525
+ async function sendLive(text) {
1526
+ if (!live) return;
1527
+ if (draftTimer) {
1528
+ clearTimeout(draftTimer);
1529
+ draftTimer = null;
1530
+ }
1531
+ clearInput();
1532
+ clearStart();
1533
+ appendMarkdown(appendMessage("user"), text);
1534
+ record({
1535
+ kind: "user",
1536
+ text
1537
+ });
1538
+ scrollToEnd();
1539
+ await live.provider.send(text);
1540
+ }
1541
+ const submit = async (event) => {
1542
+ event?.preventDefault();
1543
+ const question = input.value.trim();
1544
+ if (!question || mode === "handover") return;
1545
+ if (mode === "live") {
1546
+ sendLive(question).catch(report);
1547
+ return;
1548
+ }
1549
+ if (session.status !== "idle") return;
1550
+ clearInput();
1551
+ clearStart();
1239
1552
  appendMarkdown(appendMessage("user"), question);
1553
+ entries.push({
1554
+ kind: "user",
1555
+ text: question
1556
+ });
1557
+ activeEntry = {
1558
+ kind: "assistant",
1559
+ parts: [],
1560
+ turn: null
1561
+ };
1562
+ activeEntryText = null;
1563
+ entries.push(activeEntry);
1240
1564
  activeAssistant = appendMessage("assistant");
1241
1565
  activeText = null;
1242
1566
  activeTextContent = "";
1243
1567
  pendingTool = tool("pending", "");
1244
1568
  setBusy(true);
1245
1569
  const assistant = activeAssistant;
1570
+ const entry = activeEntry;
1246
1571
  const result = await session.send(question);
1247
1572
  if (destroyed) return;
1248
1573
  setBusy(false);
1574
+ entry.turn = result.turn;
1575
+ if (!entry.parts.length) entries = entries.filter((item) => item !== entry);
1576
+ if (activeEntry === entry) {
1577
+ activeEntry = null;
1578
+ activeEntryText = null;
1579
+ }
1580
+ save();
1249
1581
  if (result.error && !result.canceled) report(result.error);
1250
1582
  if (!result.error && assistant.isConnected && assistant.childNodes.length) {
1251
1583
  appendReplyActions(assistant, result.turn);
@@ -1278,7 +1610,28 @@ function bindChat(root, options = {}) {
1278
1610
  sendFeedback(feedback).catch(report);
1279
1611
  return;
1280
1612
  }
1613
+ if (target?.closest("[data-ai-chat-close]")) {
1614
+ setOpen(false);
1615
+ return;
1616
+ }
1617
+ if (target?.closest("[data-ai-chat-end]")) {
1618
+ binding.endLiveChat().catch(report);
1619
+ return;
1620
+ }
1281
1621
  if (target?.closest("[data-ai-chat-reset]")) {
1622
+ const provider = live?.provider;
1623
+ disconnect();
1624
+ handoverRuns += 1;
1625
+ pendingSurvey?.cancel();
1626
+ setMode("ai");
1627
+ if (provider) {
1628
+ emit("end", { reason: "visitor" });
1629
+ provider.end().catch(report);
1630
+ }
1631
+ if (storageKey) clearThread(storageKey);
1632
+ entries = [];
1633
+ activeEntry = null;
1634
+ activeEntryText = null;
1282
1635
  session.reset();
1283
1636
  chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
1284
1637
  initialNodes = Array.from(chatThread.childNodes);
@@ -1297,7 +1650,8 @@ function bindChat(root, options = {}) {
1297
1650
  }
1298
1651
  const actionElement = target?.closest("[data-ai-action]");
1299
1652
  const action = actionElement ? registryEntries(options.registry)?.actions.get(actionElement.dataset.aiAction ?? "") : void 0;
1300
- if (action && actionElement) Promise.resolve(action({
1653
+ if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover().catch(report);
1654
+ else if (action && actionElement) Promise.resolve(action({
1301
1655
  root,
1302
1656
  element: actionElement,
1303
1657
  value: actionElement.dataset.aiActionValue ?? null,
@@ -1364,24 +1718,68 @@ function bindChat(root, options = {}) {
1364
1718
  listen(form, "submit", submit);
1365
1719
  listen(root, "click", click);
1366
1720
  listen(input, "keydown", keydown);
1721
+ const typingFailed = (caught) => {
1722
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat typing event failed"));
1723
+ };
1367
1724
  listen(input, "input", () => {
1368
1725
  resizeInput();
1369
1726
  updateCounter();
1727
+ if (!live || mode !== "live") return;
1728
+ if (live.provider.draft) draftTimer ??= setTimeout(() => {
1729
+ draftTimer = null;
1730
+ if (live && mode === "live") live.provider.draft?.(input.value.trim()).catch(typingFailed);
1731
+ }, DRAFT_SENT_MS);
1732
+ else if (input.value && Date.now() - typingSentAt > TYPING_SENT_MS) {
1733
+ typingSentAt = Date.now();
1734
+ live.provider.typing().catch(typingFailed);
1735
+ }
1370
1736
  });
1371
1737
  setBusy(false);
1738
+ setMode("ai");
1372
1739
  updateCounter();
1373
1740
  followAnswer();
1374
1741
  trackKeyboard();
1375
1742
  trackOffset();
1376
- startConversation();
1743
+ const stored = storageKey ? readThread(storageKey) : null;
1744
+ if (stored) {
1745
+ session.restoreHistory(stored.history);
1746
+ if (stored.entries.length) {
1747
+ clearStart();
1748
+ for (const entry of stored.entries) renderEntry(entry);
1749
+ entries = [...stored.entries];
1750
+ }
1751
+ isOpen = stored.open === true;
1752
+ root.toggleAttribute("data-ai-chat-open", isOpen);
1753
+ scrollToEnd();
1754
+ }
1755
+ if (stored?.conversationId) session.setContext(CONVERSATION_CONTEXT, stored.conversationId);
1756
+ else startConversation();
1757
+ if (stored?.live) resumeLive(stored.live);
1377
1758
  const binding = {
1759
+ root,
1378
1760
  session,
1379
1761
  labels,
1762
+ headers,
1763
+ get mode() {
1764
+ return mode;
1765
+ },
1766
+ get isOpen() {
1767
+ return isOpen;
1768
+ },
1769
+ get liveChat() {
1770
+ return live?.provider ?? null;
1771
+ },
1772
+ label,
1380
1773
  appendAssistantReply(text) {
1381
1774
  const content = text.trim();
1382
1775
  if (!content) return;
1383
1776
  appendMarkdown(appendMessage("assistant"), content);
1384
1777
  session.addAssistantReply(content);
1778
+ record({
1779
+ kind: "assistant",
1780
+ parts: [{ text: content }],
1781
+ turn: null
1782
+ });
1385
1783
  },
1386
1784
  setFormContext(name, summary, followUp) {
1387
1785
  const content = summary.trim();
@@ -1390,10 +1788,45 @@ function bindChat(root, options = {}) {
1390
1788
  formContexts.set(name, content);
1391
1789
  session.setContextMessage(name, content);
1392
1790
  if (first && followUp) binding.appendAssistantReply(followUp);
1791
+ else save();
1792
+ },
1793
+ open() {
1794
+ setOpen(true);
1795
+ },
1796
+ close() {
1797
+ setOpen(false);
1798
+ },
1799
+ handover(handover = {}) {
1800
+ if (mode === "live") return Promise.resolve({ status: "live" });
1801
+ handoverInFlight ??= runHandover(handover).finally(() => {
1802
+ handoverInFlight = null;
1803
+ });
1804
+ return handoverInFlight;
1805
+ },
1806
+ async endLiveChat() {
1807
+ const provider = live?.provider;
1808
+ if (!provider) return;
1809
+ finishLive("visitor");
1810
+ await provider.end();
1811
+ },
1812
+ on(name, listener) {
1813
+ let listeners = eventListeners.get(name);
1814
+ if (!listeners) {
1815
+ listeners = /* @__PURE__ */ new Set();
1816
+ eventListeners.set(name, listeners);
1817
+ }
1818
+ const added = listener;
1819
+ listeners.add(added);
1820
+ return () => {
1821
+ listeners.delete(added);
1822
+ };
1393
1823
  },
1394
1824
  destroy() {
1395
1825
  if (destroyed) return;
1396
1826
  destroyed = true;
1827
+ pendingSurvey?.cancel();
1828
+ disconnect();
1829
+ eventListeners.clear();
1397
1830
  unsubscribe();
1398
1831
  session.dispose();
1399
1832
  for (const cleanup of cleanups.splice(0)) cleanup();
@@ -1402,79 +1835,121 @@ function bindChat(root, options = {}) {
1402
1835
  return binding;
1403
1836
  }
1404
1837
  //#endregion
1405
- //#region src/cards.ts
1406
- /** Block classes of the cards below. Every element a card renders carries a class under its block. */
1407
- const CARD_LIST_CLASS = "vv-ai-card-list";
1408
- const ACTIONS_CLASS = "vv-ai-actions";
1409
- function text(value) {
1410
- return typeof value === "string" && value.trim() ? value : null;
1411
- }
1838
+ //#region src/form-context.ts
1412
1839
  /**
1413
- * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
1414
- * Items that render nothing are skipped, and a list with nothing in it is null.
1840
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
1841
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
1842
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
1843
+ * something the visitor said. Returns a function that stops watching.
1415
1844
  */
1416
- function renderCardList(document, items, render, modifier) {
1417
- if (!Array.isArray(items)) return null;
1418
- const cards = items.map(render).filter((card) => card !== null);
1419
- if (!cards.length) return null;
1420
- const list = createPart(document, "div", CARD_LIST_CLASS);
1421
- if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
1422
- list.append(...cards);
1423
- return list;
1845
+ function watchFormContext(binding, element, options) {
1846
+ const record = () => {
1847
+ const form = element.querySelector(options.form);
1848
+ if (!form) return;
1849
+ const values = new FormData(form);
1850
+ const parts = options.fields.map(([field, label]) => {
1851
+ const raw = String(values.get(field) ?? "").trim();
1852
+ const value = options.values?.[raw] ?? raw;
1853
+ return value ? `${label}: ${value}` : "";
1854
+ }).filter(Boolean);
1855
+ if (!parts.length) return;
1856
+ const note = options.note ? ` ${options.note}` : "";
1857
+ binding.setFormContext(options.name, `Context, not a message from the visitor: they filled in ${options.title} with ${parts.join(", ")}.${note}`, options.followUp);
1858
+ };
1859
+ const observer = new MutationObserver(record);
1860
+ observer.observe(element, {
1861
+ childList: true,
1862
+ subtree: true
1863
+ });
1864
+ record();
1865
+ return () => observer.disconnect();
1424
1866
  }
1867
+ //#endregion
1868
+ //#region src/window.ts
1425
1869
  /**
1426
- * A row of things the visitor can do next. An item with `action` is a button that runs the action
1427
- * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
1428
- * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
1870
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
1871
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
1872
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
1873
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
1874
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
1875
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
1429
1876
  */
1430
- function renderActions(document, items) {
1431
- const elements = [];
1432
- for (const item of items) {
1433
- const label = text(item?.label);
1434
- if (!label) continue;
1435
- let element = null;
1436
- const action = text(item.action);
1437
- const url = text(item.url);
1438
- if (action) {
1439
- const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
1440
- button.type = "button";
1441
- button.dataset.aiAction = action;
1442
- const value = text(item.value);
1443
- if (value) button.dataset.aiActionValue = value;
1444
- element = button;
1445
- } else if (url) {
1446
- element = createSafeLink(document, label, url.trim());
1447
- if (element) element.className = `${ACTIONS_CLASS}__action`;
1448
- }
1449
- if (element) {
1450
- element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
1451
- elements.push(element);
1877
+ function bindChatWindow(binding) {
1878
+ const document = binding.root.ownerDocument;
1879
+ const menu = binding.root.querySelector("details[data-ai-chat-menu]");
1880
+ const summary = menu?.querySelector("summary") ?? null;
1881
+ const toggles = () => document.querySelectorAll("[data-ai-chat-window-toggle]");
1882
+ const sync = () => {
1883
+ for (const toggle of toggles()) toggle.setAttribute("aria-expanded", String(binding.isOpen));
1884
+ };
1885
+ const click = (event) => {
1886
+ const target = event.target instanceof Element ? event.target : null;
1887
+ if (menu?.open && !(target && summary?.contains(target))) menu.open = false;
1888
+ const opener = target?.closest("[data-ai-chat-window-open]");
1889
+ if (opener) {
1890
+ if (opener.hasAttribute("data-ai-chat-window-toggle") && binding.isOpen) binding.close();
1891
+ else binding.open();
1892
+ return;
1452
1893
  }
1894
+ const expand = target?.closest("[data-ai-chat-expand]");
1895
+ if (expand && binding.root.contains(expand)) binding.close();
1896
+ };
1897
+ const keydown = (event) => {
1898
+ if (event.key !== "Escape") return;
1899
+ if (menu?.open) {
1900
+ menu.open = false;
1901
+ summary?.focus();
1902
+ } else if (binding.isOpen) binding.close();
1903
+ };
1904
+ document.addEventListener("click", click);
1905
+ document.addEventListener("keydown", keydown);
1906
+ const unsubscribes = [binding.on("open", sync), binding.on("close", () => {
1907
+ sync();
1908
+ toggles()[0]?.focus();
1909
+ })];
1910
+ sync();
1911
+ return () => {
1912
+ document.removeEventListener("click", click);
1913
+ document.removeEventListener("keydown", keydown);
1914
+ for (const unsubscribe of unsubscribes) unsubscribe();
1915
+ };
1916
+ }
1917
+ function teaserShown(key) {
1918
+ if (!key) return false;
1919
+ try {
1920
+ return window.sessionStorage.getItem(key) !== null;
1921
+ } catch {
1922
+ return true;
1453
1923
  }
1454
- if (!elements.length) return null;
1455
- const actions = createPart(document, "div", ACTIONS_CLASS);
1456
- actions.append(...elements);
1457
- return actions;
1458
1924
  }
1459
- //#endregion
1460
- //#region src/surfaces.ts
1925
+ function markTeaserShown(key) {
1926
+ if (!key) return;
1927
+ try {
1928
+ window.sessionStorage.setItem(key, "1");
1929
+ } catch {}
1930
+ }
1461
1931
  /**
1462
- * A surface that shows one item out of an authored list template. The template is cloned, every
1463
- * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
1464
- * rest of the template stays as authored, so one item is the same markup the whole list shows.
1465
- * Null when the template is missing or no item matches.
1932
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
1933
+ * started a chat: not while the window is open or its thread has messages. A
1934
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
1935
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
1466
1936
  */
1467
- function createTemplateItemSurface(options) {
1468
- return ({ root, data }) => {
1469
- const value = isPlainObject(data) ? data[options.key] : null;
1470
- const template = root.querySelector(`template[data-template="${CSS.escape(options.template)}"]`);
1471
- if (typeof value !== "string" || !template) return null;
1472
- const content = template.content.cloneNode(true);
1473
- let found = false;
1474
- for (const item of content.querySelectorAll(`[${CSS.escape(options.attribute)}]`)) if (item.getAttribute(options.attribute) === value) found = true;
1475
- else item.remove();
1476
- return found ? content : null;
1937
+ function bindLauncherTeaser(binding, container, options = {}) {
1938
+ const teaser = container.querySelector("[data-ai-launcher-teaser]");
1939
+ const key = options.storageKey || teaser?.dataset.aiLauncherTeaser || "";
1940
+ if (!teaser || binding.isOpen || teaserShown(key) || binding.root.querySelector("[data-ai-chat-message]")) return () => void 0;
1941
+ teaser.hidden = false;
1942
+ markTeaserShown(key);
1943
+ const hide = () => {
1944
+ teaser.hidden = true;
1945
+ };
1946
+ const dismiss = teaser.querySelector("[data-ai-launcher-dismiss]");
1947
+ dismiss?.addEventListener("click", hide);
1948
+ const unsubscribe = binding.on("open", hide);
1949
+ return () => {
1950
+ dismiss?.removeEventListener("click", hide);
1951
+ unsubscribe();
1477
1952
  };
1478
1953
  }
1479
1954
  //#endregion
1480
- export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, 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, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList };
1955
+ 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 };