@vettvangur/ai-sdk 0.4.1 → 0.5.4

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,5 @@
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, r as createSafeLink, t as createPart } from "./dom.js";
2
+ import { i as renderMarkdown, n as renderSurveyForm, r as countMarkdownStructuralItems } from "./survey.js";
290
3
  //#region src/answer-card.ts
291
4
  const ANSWER_CARD_KEYS = /* @__PURE__ */ new Set([
292
5
  "kind",
@@ -689,14 +402,10 @@ function parseStreamEvent(name, data) {
689
402
  };
690
403
  }
691
404
  case "done": {
692
- const provider = stringValue(data, "provider");
693
405
  const turn = stringValue(data, "turn");
694
- return provider === null ? null : {
406
+ return {
695
407
  name,
696
- data: {
697
- provider,
698
- turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null
699
- }
408
+ data: { turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null }
700
409
  };
701
410
  }
702
411
  case "error": {
@@ -831,7 +540,6 @@ function createChatSession(options) {
831
540
  role: "user",
832
541
  content
833
542
  }];
834
- let provider = null;
835
543
  let turn = null;
836
544
  let error = null;
837
545
  let canceled = false;
@@ -856,10 +564,8 @@ function createChatSession(options) {
856
564
  if (event.name === "tool") await afterNextPaint();
857
565
  if (event.name === "delta") answer += event.data.text;
858
566
  else if (event.name === "tool_result" && event.data.reply) replies.push(event.data.reply);
859
- else if (event.name === "done") {
860
- provider = event.data.provider;
861
- turn = event.data.turn;
862
- } else if (event.name === "error") throw new Error(event.data.message);
567
+ else if (event.name === "done") turn = event.data.turn;
568
+ else if (event.name === "error") throw new Error(event.data.message);
863
569
  }
864
570
  if (answer.trim()) replies = [...replies, answer.trim()];
865
571
  history.push({
@@ -880,7 +586,6 @@ function createChatSession(options) {
880
586
  if (session.status !== "disposed") status = "idle";
881
587
  }
882
588
  return {
883
- provider,
884
589
  turn,
885
590
  canceled,
886
591
  error
@@ -914,6 +619,11 @@ function createChatSession(options) {
914
619
  contextMessages.set(name, message);
915
620
  history.push(message);
916
621
  },
622
+ restoreHistory(messages) {
623
+ session.cancel();
624
+ history.splice(0, history.length, ...messages.map((message) => ({ ...message })));
625
+ contextMessages.clear();
626
+ },
917
627
  addAssistantReply(content) {
918
628
  const value = content.trim();
919
629
  if (!value) throw new Error("AI chat assistant replies cannot be empty");
@@ -965,6 +675,35 @@ function registryEntries(registry) {
965
675
  return registry ? entries.get(registry) : void 0;
966
676
  }
967
677
  //#endregion
678
+ //#region src/thread-store.ts
679
+ function storage() {
680
+ try {
681
+ return window.sessionStorage;
682
+ } catch {
683
+ return null;
684
+ }
685
+ }
686
+ function readThread(key) {
687
+ try {
688
+ const raw = storage()?.getItem(key);
689
+ const parsed = raw ? JSON.parse(raw) : null;
690
+ if (!isPlainObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.history) || !Array.isArray(parsed.entries)) return null;
691
+ return parsed;
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+ function writeThread(key, thread) {
697
+ try {
698
+ storage()?.setItem(key, JSON.stringify(thread));
699
+ } catch {}
700
+ }
701
+ function clearThread(key) {
702
+ try {
703
+ storage()?.removeItem(key);
704
+ } catch {}
705
+ }
706
+ //#endregion
968
707
  //#region src/bind.ts
969
708
  const defaultLabels = {
970
709
  error: "Something went wrong. Please try again.",
@@ -977,15 +716,44 @@ const defaultLabels = {
977
716
  details: "Details",
978
717
  table: "Published table",
979
718
  tableScroll: "Scroll sideways to see all columns",
980
- followUps: "Suggested questions"
719
+ followUps: "Suggested questions",
720
+ liveChatConnecting: "Connecting you to a person",
721
+ liveChatClosed: "No one is available to chat right now.",
722
+ liveChatEnded: "The chat has ended. You are talking to the AI again.",
723
+ liveChatFailed: "We could not connect you to a person. Please try again.",
724
+ liveChatTyping: "Typing",
725
+ liveChatAgent: "Agent",
726
+ liveChatStarted: "Chat with a person started",
727
+ liveChatJoined: "{name} joined the chat",
728
+ liveChatAgentEnded: "{name} ended the chat",
729
+ liveChatWaiting: "One moment, connecting you",
730
+ liveChatWaitingText: "",
731
+ liveChatTeam: "",
732
+ surveySubmit: "Start chat",
733
+ surveyCancel: "Cancel",
734
+ surveyRequired: "Please fill this in",
735
+ surveyInvalidEmail: "Please enter an email address",
736
+ surveyTitle: "",
737
+ surveyIntro: "",
738
+ surveyPrefilled: ""
981
739
  };
982
740
  const NEAR_LIMIT = .9;
741
+ const TYPING_SHOWN_MS = 5e3;
742
+ const TYPING_SENT_MS = 3e3;
743
+ const DRAFT_SENT_MS = 700;
983
744
  /**
984
745
  * Every element the binding adds to the thread carries a class under this block, so a host styles
985
746
  * the chat by class rather than by the order its elements happen to come in.
986
747
  */
987
748
  const CHAT_CLASS = "vv-ai-chat";
988
749
  const CONVERSATION_CONTEXT = "conversationId";
750
+ function firstName(name) {
751
+ return name.trim().split(/\s+/)[0] ?? name;
752
+ }
753
+ function initials(name) {
754
+ const words = name.trim().split(/\s+/).filter(Boolean);
755
+ return (words.length > 1 ? [words[0], words[words.length - 1]] : words).map((word) => [...word][0] ?? "").join("").toUpperCase();
756
+ }
989
757
  function part(name) {
990
758
  return `${CHAT_CLASS}__${name}`;
991
759
  }
@@ -998,6 +766,10 @@ function readLabels(root, labels) {
998
766
  for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
999
767
  return read;
1000
768
  }
769
+ function stringRecord(value) {
770
+ if (!isPlainObject(value)) return {};
771
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
772
+ }
1001
773
  function dataString(data, name) {
1002
774
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
1003
775
  const value = data[name];
@@ -1020,6 +792,8 @@ function bindChat(root, options = {}) {
1020
792
  const token = options.antiforgeryToken ?? root.dataset.aiChatAntiforgeryToken;
1021
793
  const headers = header && token ? { [header]: token } : void 0;
1022
794
  const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
795
+ const handoverEndpoint = options.handoverEndpoint ?? root.dataset.aiChatHandoverEndpoint;
796
+ const storageKey = options.storageKey ?? root.dataset.aiChatStorageKey;
1023
797
  let activeAssistant = null;
1024
798
  let activeText = null;
1025
799
  let activeTextContent = "";
@@ -1028,6 +802,22 @@ function bindChat(root, options = {}) {
1028
802
  let destroyed = false;
1029
803
  const formContexts = /* @__PURE__ */ new Map();
1030
804
  const cleanups = [];
805
+ let entries = [];
806
+ let activeEntry = null;
807
+ let activeEntryText = null;
808
+ let mode = "ai";
809
+ let isOpen = root.hasAttribute("data-ai-chat-open");
810
+ let live = null;
811
+ let handoverInFlight = null;
812
+ let handoverRuns = 0;
813
+ let pendingSurvey = null;
814
+ let typingIndicator = null;
815
+ let typingTimer = null;
816
+ let typingSentAt = 0;
817
+ let draftTimer = null;
818
+ let waitingCard = null;
819
+ const placeholder = input.placeholder;
820
+ const eventListeners = /* @__PURE__ */ new Map();
1031
821
  const session = createChatSession({
1032
822
  endpoint,
1033
823
  provider: options.provider ?? root.dataset.aiChatProvider,
@@ -1110,26 +900,23 @@ function bindChat(root, options = {}) {
1110
900
  if (status) status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
1111
901
  }
1112
902
  }
1113
- function renderResult(event) {
1114
- if (!activeAssistant) return;
1115
- activeText = null;
1116
- activeTextContent = "";
903
+ function renderResult(parent, result) {
1117
904
  const context = {
1118
905
  document: root.ownerDocument,
1119
906
  root,
1120
- tool: event.data.name,
1121
- data: event.data.data,
1122
- reply: event.data.reply,
907
+ tool: result.name,
908
+ data: result.data,
909
+ reply: result.reply,
1123
910
  labels
1124
911
  };
1125
912
  let content = null;
1126
913
  try {
1127
- const templateName = dataString(event.data.data, "template");
1128
- const surfaceName = dataString(event.data.data, "surface");
914
+ const templateName = dataString(result.data, "template");
915
+ const surfaceName = dataString(result.data, "surface");
1129
916
  if (templateName) content = root.querySelector(`template[data-template="${CSS.escape(templateName)}"]`)?.content.cloneNode(true) ?? null;
1130
917
  if (!content && surfaceName) content = registryEntries(options.registry)?.surfaces.get(surfaceName)?.(context) ?? root.querySelector(`template[data-ai-surface="${CSS.escape(surfaceName)}"]`)?.content.cloneNode(true) ?? null;
1131
- if (!content) content = registryEntries(options.registry)?.renderers.get(event.data.name)?.(context) ?? null;
1132
- content ??= renderAnswerCard(root.ownerDocument, event.data.data, labels);
918
+ if (!content) content = registryEntries(options.registry)?.renderers.get(result.name)?.(context) ?? null;
919
+ content ??= renderAnswerCard(root.ownerDocument, result.data, labels);
1133
920
  } catch (caught) {
1134
921
  options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat extension failed"));
1135
922
  }
@@ -1138,21 +925,39 @@ function bindChat(root, options = {}) {
1138
925
  wrapper.dataset.aiChatCard = "true";
1139
926
  wrapper.className = part("result");
1140
927
  wrapper.append(content);
1141
- activeAssistant.append(wrapper);
928
+ parent.append(wrapper);
1142
929
  options.onEmbedded?.(wrapper);
1143
- } else if (event.data.reply) appendMarkdown(activeAssistant, event.data.reply);
930
+ } else if (result.reply) appendMarkdown(parent, result.reply);
1144
931
  }
1145
932
  const unsubscribe = session.subscribe((event) => {
1146
933
  if (destroyed) return;
1147
934
  if (event.name === "delta" && activeAssistant) {
1148
935
  clearPendingTool();
1149
936
  appendStreamedMarkdown(event.data.text);
937
+ if (activeEntry) {
938
+ if (!activeEntryText) {
939
+ activeEntryText = { text: "" };
940
+ activeEntry.parts.push(activeEntryText);
941
+ }
942
+ activeEntryText.text += event.data.text;
943
+ }
1150
944
  } else if (event.name === "tool") {
1151
945
  clearPendingTool();
1152
946
  tool(event.data.id, event.data.name);
1153
947
  } else if (event.name === "tool_result") {
1154
948
  clearPendingTool();
1155
- renderResult(event);
949
+ if (activeAssistant) {
950
+ activeText = null;
951
+ activeTextContent = "";
952
+ const result = {
953
+ name: event.data.name,
954
+ data: event.data.data,
955
+ reply: event.data.reply
956
+ };
957
+ renderResult(activeAssistant, result);
958
+ activeEntry?.parts.push({ result });
959
+ activeEntryText = null;
960
+ }
1156
961
  } else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
1157
962
  else if (event.name === "suggestions") followUps = event.data.suggestions;
1158
963
  else if (event.name === "done" || event.name === "error") clearPendingTool();
@@ -1234,26 +1039,418 @@ function bindChat(root, options = {}) {
1234
1039
  input.style.height = "auto";
1235
1040
  input.style.height = `${input.scrollHeight}px`;
1236
1041
  };
1237
- const submit = async (event) => {
1238
- event?.preventDefault();
1239
- const question = input.value.trim();
1240
- if (!question || session.status !== "idle") return;
1241
- input.value = "";
1242
- resizeInput();
1243
- updateCounter();
1042
+ function emit(name, detail) {
1043
+ for (const listener of eventListeners.get(name) ?? []) listener(detail);
1044
+ }
1045
+ function save() {
1046
+ if (!storageKey) return;
1047
+ const thread = {
1048
+ version: 1,
1049
+ conversationId: session.context[CONVERSATION_CONTEXT] ?? null,
1050
+ history: [...session.history],
1051
+ entries,
1052
+ open: isOpen,
1053
+ live: live?.resume ? {
1054
+ resume: live.resume,
1055
+ seen: [...live.seen],
1056
+ agent: live.agent
1057
+ } : null
1058
+ };
1059
+ writeThread(storageKey, thread);
1060
+ }
1061
+ function record(entry) {
1062
+ entries.push(entry);
1063
+ save();
1064
+ }
1065
+ function scrollToEnd() {
1066
+ const scroller = root.querySelector("[data-ai-chat-scroll]");
1067
+ scroller?.scrollTo({ top: scroller.scrollHeight });
1068
+ }
1069
+ function clearStart() {
1244
1070
  for (const node of initialNodes) node.remove();
1245
1071
  for (const list of chatThread.querySelectorAll("[data-ai-chat-follow-ups]")) list.remove();
1246
1072
  followUps = [];
1073
+ }
1074
+ const clearInput = () => {
1075
+ input.value = "";
1076
+ resizeInput();
1077
+ updateCounter();
1078
+ };
1079
+ function appendNotice(text, modifier) {
1080
+ const notice = root.ownerDocument.createElement("p");
1081
+ notice.dataset.aiChatNotice = modifier;
1082
+ notice.className = `${part("notice")} ${part(`notice--${modifier}`)}`;
1083
+ notice.setAttribute("role", modifier === "failed" ? "alert" : "status");
1084
+ notice.append(text);
1085
+ chatThread.append(notice);
1086
+ scrollToEnd();
1087
+ }
1088
+ function notify(text, modifier) {
1089
+ appendNotice(text, modifier);
1090
+ record({
1091
+ kind: "notice",
1092
+ text,
1093
+ modifier
1094
+ });
1095
+ }
1096
+ function appendInitials(parent, name) {
1097
+ const avatar = root.ownerDocument.createElement("span");
1098
+ avatar.className = part("initials");
1099
+ avatar.setAttribute("aria-hidden", "true");
1100
+ avatar.append(initials(name || labels.liveChatAgent));
1101
+ parent.append(avatar);
1102
+ }
1103
+ function appendPerson(name, text) {
1104
+ const message = appendMessage("person");
1105
+ appendInitials(message, name);
1106
+ const sender = root.ownerDocument.createElement("span");
1107
+ sender.className = part("sender");
1108
+ const shown = name ? firstName(name) : labels.liveChatAgent;
1109
+ sender.append(labels.liveChatTeam ? `${shown} · ${labels.liveChatTeam}` : shown);
1110
+ message.append(sender);
1111
+ appendMarkdown(message, text);
1112
+ scrollToEnd();
1113
+ }
1114
+ function notifyAgent(template, name, modifier) {
1115
+ const time = new Intl.DateTimeFormat(root.ownerDocument.documentElement.lang || void 0, {
1116
+ hour: "2-digit",
1117
+ minute: "2-digit"
1118
+ }).format(/* @__PURE__ */ new Date());
1119
+ notify(`${template.replace("{name}", firstName(name))} · ${time}`, modifier);
1120
+ }
1121
+ function showWaiting() {
1122
+ if (waitingCard) return;
1123
+ waitingCard = root.ownerDocument.createElement("div");
1124
+ waitingCard.className = part("waiting");
1125
+ waitingCard.setAttribute("role", "status");
1126
+ const title = root.ownerDocument.createElement("p");
1127
+ title.className = part("waiting-title");
1128
+ title.append(labels.liveChatWaiting);
1129
+ waitingCard.append(title);
1130
+ if (labels.liveChatWaitingText) {
1131
+ const text = root.ownerDocument.createElement("p");
1132
+ text.className = part("waiting-text");
1133
+ text.append(labels.liveChatWaitingText);
1134
+ waitingCard.append(text);
1135
+ }
1136
+ chatThread.append(waitingCard);
1137
+ scrollToEnd();
1138
+ }
1139
+ function hideWaiting() {
1140
+ waitingCard?.remove();
1141
+ waitingCard = null;
1142
+ }
1143
+ function showAgent(name) {
1144
+ if (live) root.dataset.aiChatLive = name ? "agent" : "waiting";
1145
+ else delete root.dataset.aiChatLive;
1146
+ for (const element of root.querySelectorAll("[data-ai-chat-agent-name]")) element.textContent = name ?? "";
1147
+ for (const element of root.querySelectorAll("[data-ai-chat-agent-initials]")) element.textContent = name ? initials(name) : "";
1148
+ }
1149
+ function hideTyping() {
1150
+ if (typingTimer) clearTimeout(typingTimer);
1151
+ typingTimer = null;
1152
+ typingIndicator?.remove();
1153
+ typingIndicator = null;
1154
+ }
1155
+ function showTyping() {
1156
+ if (!typingIndicator) {
1157
+ typingIndicator = root.ownerDocument.createElement("div");
1158
+ typingIndicator.dataset.aiChatTyping = "true";
1159
+ typingIndicator.className = part("typing");
1160
+ typingIndicator.setAttribute("role", "status");
1161
+ appendInitials(typingIndicator, live?.agent ?? null);
1162
+ const dots = root.ownerDocument.createElement("span");
1163
+ dots.className = part("typing-dots");
1164
+ dots.setAttribute("aria-hidden", "true");
1165
+ for (let dot = 0; dot < 3; dot++) {
1166
+ const span = root.ownerDocument.createElement("span");
1167
+ span.className = part("typing-dot");
1168
+ dots.append(span);
1169
+ }
1170
+ const label = root.ownerDocument.createElement("span");
1171
+ label.className = part("typing-label");
1172
+ label.append(labels.liveChatTyping);
1173
+ typingIndicator.append(dots, label);
1174
+ }
1175
+ chatThread.append(typingIndicator);
1176
+ if (typingTimer) clearTimeout(typingTimer);
1177
+ typingTimer = setTimeout(hideTyping, TYPING_SHOWN_MS);
1178
+ scrollToEnd();
1179
+ }
1180
+ function renderEntry(entry) {
1181
+ if (entry.kind === "user" && typeof entry.text === "string") appendMarkdown(appendMessage("user"), entry.text);
1182
+ else if (entry.kind === "assistant" && Array.isArray(entry.parts)) {
1183
+ const message = appendMessage("assistant");
1184
+ for (const item of entry.parts) if ("text" in item && typeof item.text === "string") appendMarkdown(message, item.text);
1185
+ else if ("result" in item && isPlainObject(item.result) && typeof item.result.name === "string") renderResult(message, item.result);
1186
+ appendReplyActions(message, typeof entry.turn === "string" ? entry.turn : null);
1187
+ } else if (entry.kind === "person" && typeof entry.text === "string") appendPerson(typeof entry.name === "string" ? entry.name : null, entry.text);
1188
+ else if (entry.kind === "notice" && typeof entry.text === "string" && typeof entry.modifier === "string") appendNotice(entry.text, entry.modifier);
1189
+ }
1190
+ const setMode = (next) => {
1191
+ mode = next;
1192
+ root.dataset.aiChatMode = next;
1193
+ input.disabled = next === "handover";
1194
+ for (const button of root.querySelectorAll("[data-ai-chat-end]")) button.hidden = next !== "live";
1195
+ input.placeholder = next === "live" ? input.dataset.aiChatLivePlaceholder ?? placeholder : next === "handover" ? input.dataset.aiChatHandoverPlaceholder ?? placeholder : placeholder;
1196
+ };
1197
+ function setOpen(next) {
1198
+ if (next === isOpen) return;
1199
+ isOpen = next;
1200
+ root.toggleAttribute("data-ai-chat-open", next);
1201
+ save();
1202
+ emit(next ? "open" : "close", void 0);
1203
+ if (next) {
1204
+ scrollToEnd();
1205
+ focusInput();
1206
+ }
1207
+ }
1208
+ function receiveLive(message) {
1209
+ if (!live || live.seen.has(message.id)) return;
1210
+ live.seen.add(message.id);
1211
+ hideTyping();
1212
+ if (message.sender === "agent" && !live.agent) agentJoined({ name: message.name });
1213
+ if (message.sender === "system") notify(message.text, "system");
1214
+ else {
1215
+ appendPerson(message.name, message.text);
1216
+ record({
1217
+ kind: "person",
1218
+ id: message.id,
1219
+ text: message.text,
1220
+ name: message.name
1221
+ });
1222
+ }
1223
+ }
1224
+ function agentJoined(agent) {
1225
+ if (!live) return;
1226
+ const name = agent.name?.trim() || labels.liveChatAgent;
1227
+ if (live.agent === name) return;
1228
+ live.agent = name;
1229
+ hideWaiting();
1230
+ showAgent(name);
1231
+ notifyAgent(labels.liveChatJoined, name, "joined");
1232
+ emit("agent", { name: agent.name?.trim() || null });
1233
+ }
1234
+ function connect(provider, resume, seen, agent = null) {
1235
+ live = {
1236
+ provider,
1237
+ resume,
1238
+ seen: new Set(seen),
1239
+ agent,
1240
+ unsubscribes: [
1241
+ provider.onMessage(receiveLive),
1242
+ provider.onTyping(showTyping),
1243
+ provider.onEnded(() => finishLive("agent")),
1244
+ ...provider.onAgent ? [provider.onAgent(agentJoined)] : []
1245
+ ]
1246
+ };
1247
+ showAgent(agent);
1248
+ }
1249
+ function disconnect() {
1250
+ for (const unsubscribe of live?.unsubscribes ?? []) unsubscribe();
1251
+ live = null;
1252
+ hideTyping();
1253
+ hideWaiting();
1254
+ showAgent(null);
1255
+ }
1256
+ function finishLive(reason) {
1257
+ if (!live) return;
1258
+ const agent = live.agent;
1259
+ disconnect();
1260
+ setMode("ai");
1261
+ if (reason === "agent" && agent) notifyAgent(labels.liveChatAgentEnded, agent, "agent-ended");
1262
+ notify(labels.liveChatEnded, "ended");
1263
+ emit("end", { reason });
1264
+ }
1265
+ async function requestHandover() {
1266
+ if (!handoverEndpoint) return {
1267
+ transcript: null,
1268
+ context: {}
1269
+ };
1270
+ try {
1271
+ const response = await fetch(handoverEndpoint, {
1272
+ method: "POST",
1273
+ headers: {
1274
+ "Content-Type": "application/json",
1275
+ ...headers
1276
+ },
1277
+ body: JSON.stringify({
1278
+ conversationId: session.context[CONVERSATION_CONTEXT],
1279
+ culture: session.context.culture,
1280
+ messages: session.history
1281
+ })
1282
+ });
1283
+ if (!response.ok) throw new Error(`AI chat handover request failed with ${response.status}`);
1284
+ const body = await response.json();
1285
+ return {
1286
+ transcript: (isPlainObject(body) && typeof body.transcript === "string" ? body.transcript.trim() : "") || null,
1287
+ context: stringRecord(isPlainObject(body) ? body.context : null)
1288
+ };
1289
+ } catch (caught) {
1290
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover request failed"));
1291
+ return {
1292
+ transcript: null,
1293
+ context: {}
1294
+ };
1295
+ }
1296
+ }
1297
+ async function runHandover(handover) {
1298
+ const provider = handover.provider ?? options.liveChat;
1299
+ if (!provider) throw new Error("AI chat handover needs a live chat provider");
1300
+ const run = ++handoverRuns;
1301
+ const stale = () => destroyed || run !== handoverRuns;
1302
+ session.cancel();
1303
+ clearStart();
1304
+ setMode("handover");
1305
+ let started = false;
1306
+ try {
1307
+ const availability = await provider.availability();
1308
+ if (stale()) return { status: "canceled" };
1309
+ if (availability.status === "closed") {
1310
+ notify(labels.liveChatClosed, "closed");
1311
+ setMode("ai");
1312
+ return availability;
1313
+ }
1314
+ const handoff = requestHandover();
1315
+ const fields = await provider.survey();
1316
+ let answers = {};
1317
+ if (fields?.length && !stale()) {
1318
+ const survey = renderSurveyForm(root.ownerDocument, fields, {
1319
+ labels: {
1320
+ submit: labels.surveySubmit,
1321
+ cancel: labels.surveyCancel,
1322
+ required: labels.surveyRequired,
1323
+ invalidEmail: labels.surveyInvalidEmail,
1324
+ title: labels.surveyTitle,
1325
+ intro: labels.surveyIntro,
1326
+ prefilled: labels.surveyPrefilled
1327
+ },
1328
+ prefill: handover.prefill
1329
+ });
1330
+ pendingSurvey = survey;
1331
+ const wrapper = root.ownerDocument.createElement("div");
1332
+ wrapper.className = part("survey");
1333
+ wrapper.append(survey.form);
1334
+ chatThread.append(wrapper);
1335
+ scrollToEnd();
1336
+ survey.form.querySelector("input, textarea, select")?.focus({ preventScroll: true });
1337
+ const submitted = await survey.answers;
1338
+ pendingSurvey = null;
1339
+ wrapper.remove();
1340
+ if (!submitted) {
1341
+ if (!stale()) setMode("ai");
1342
+ return { status: "canceled" };
1343
+ }
1344
+ answers = submitted;
1345
+ }
1346
+ if (stale()) return { status: "canceled" };
1347
+ notify(labels.liveChatConnecting, "connecting");
1348
+ const server = await handoff;
1349
+ connect(provider, null, []);
1350
+ started = true;
1351
+ await provider.start({
1352
+ answers,
1353
+ context: {
1354
+ ...server.context,
1355
+ ...handover.context
1356
+ },
1357
+ openingMessage: server.transcript ?? void 0
1358
+ });
1359
+ if (stale()) {
1360
+ await provider.end();
1361
+ return { status: "canceled" };
1362
+ }
1363
+ const resume = await provider.resumeToken();
1364
+ if (live) live.resume = resume;
1365
+ setMode("live");
1366
+ notify(labels.liveChatStarted, "started");
1367
+ if (!live?.agent) showWaiting();
1368
+ emit("handover", void 0);
1369
+ return { status: "live" };
1370
+ } catch (caught) {
1371
+ const error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover failed");
1372
+ options.onError?.(error);
1373
+ if (started) disconnect();
1374
+ if (!stale()) {
1375
+ notify(labels.liveChatFailed, "failed");
1376
+ setMode("ai");
1377
+ }
1378
+ return {
1379
+ status: "failed",
1380
+ error
1381
+ };
1382
+ }
1383
+ }
1384
+ function resumeLive(stored) {
1385
+ const provider = options.liveChat;
1386
+ if (!provider) {
1387
+ notify(labels.liveChatEnded, "ended");
1388
+ return;
1389
+ }
1390
+ connect(provider, stored.resume, stored.seen, stored.agent ?? null);
1391
+ setMode("live");
1392
+ if (!stored.agent) showWaiting();
1393
+ provider.start({ resume: stored.resume }).catch((caught) => {
1394
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat live chat could not reconnect"));
1395
+ if (live?.provider === provider) finishLive("disconnected");
1396
+ });
1397
+ }
1398
+ async function sendLive(text) {
1399
+ if (!live) return;
1400
+ if (draftTimer) {
1401
+ clearTimeout(draftTimer);
1402
+ draftTimer = null;
1403
+ }
1404
+ clearInput();
1405
+ clearStart();
1406
+ appendMarkdown(appendMessage("user"), text);
1407
+ record({
1408
+ kind: "user",
1409
+ text
1410
+ });
1411
+ scrollToEnd();
1412
+ await live.provider.send(text);
1413
+ }
1414
+ const submit = async (event) => {
1415
+ event?.preventDefault();
1416
+ const question = input.value.trim();
1417
+ if (!question || mode === "handover") return;
1418
+ if (mode === "live") {
1419
+ sendLive(question).catch(report);
1420
+ return;
1421
+ }
1422
+ if (session.status !== "idle") return;
1423
+ clearInput();
1424
+ clearStart();
1247
1425
  appendMarkdown(appendMessage("user"), question);
1426
+ entries.push({
1427
+ kind: "user",
1428
+ text: question
1429
+ });
1430
+ activeEntry = {
1431
+ kind: "assistant",
1432
+ parts: [],
1433
+ turn: null
1434
+ };
1435
+ activeEntryText = null;
1436
+ entries.push(activeEntry);
1248
1437
  activeAssistant = appendMessage("assistant");
1249
1438
  activeText = null;
1250
1439
  activeTextContent = "";
1251
1440
  pendingTool = tool("pending", "");
1252
1441
  setBusy(true);
1253
1442
  const assistant = activeAssistant;
1443
+ const entry = activeEntry;
1254
1444
  const result = await session.send(question);
1255
1445
  if (destroyed) return;
1256
1446
  setBusy(false);
1447
+ entry.turn = result.turn;
1448
+ if (!entry.parts.length) entries = entries.filter((item) => item !== entry);
1449
+ if (activeEntry === entry) {
1450
+ activeEntry = null;
1451
+ activeEntryText = null;
1452
+ }
1453
+ save();
1257
1454
  if (result.error && !result.canceled) report(result.error);
1258
1455
  if (!result.error && assistant.isConnected && assistant.childNodes.length) {
1259
1456
  appendReplyActions(assistant, result.turn);
@@ -1286,7 +1483,28 @@ function bindChat(root, options = {}) {
1286
1483
  sendFeedback(feedback).catch(report);
1287
1484
  return;
1288
1485
  }
1486
+ if (target?.closest("[data-ai-chat-close]")) {
1487
+ setOpen(false);
1488
+ return;
1489
+ }
1490
+ if (target?.closest("[data-ai-chat-end]")) {
1491
+ binding.endLiveChat().catch(report);
1492
+ return;
1493
+ }
1289
1494
  if (target?.closest("[data-ai-chat-reset]")) {
1495
+ const provider = live?.provider;
1496
+ disconnect();
1497
+ handoverRuns += 1;
1498
+ pendingSurvey?.cancel();
1499
+ setMode("ai");
1500
+ if (provider) {
1501
+ emit("end", { reason: "visitor" });
1502
+ provider.end().catch(report);
1503
+ }
1504
+ if (storageKey) clearThread(storageKey);
1505
+ entries = [];
1506
+ activeEntry = null;
1507
+ activeEntryText = null;
1290
1508
  session.reset();
1291
1509
  chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
1292
1510
  initialNodes = Array.from(chatThread.childNodes);
@@ -1372,24 +1590,65 @@ function bindChat(root, options = {}) {
1372
1590
  listen(form, "submit", submit);
1373
1591
  listen(root, "click", click);
1374
1592
  listen(input, "keydown", keydown);
1593
+ const typingFailed = (caught) => {
1594
+ options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat typing event failed"));
1595
+ };
1375
1596
  listen(input, "input", () => {
1376
1597
  resizeInput();
1377
1598
  updateCounter();
1599
+ if (!live || mode !== "live") return;
1600
+ if (live.provider.draft) draftTimer ??= setTimeout(() => {
1601
+ draftTimer = null;
1602
+ if (live && mode === "live") live.provider.draft?.(input.value.trim()).catch(typingFailed);
1603
+ }, DRAFT_SENT_MS);
1604
+ else if (input.value && Date.now() - typingSentAt > TYPING_SENT_MS) {
1605
+ typingSentAt = Date.now();
1606
+ live.provider.typing().catch(typingFailed);
1607
+ }
1378
1608
  });
1379
1609
  setBusy(false);
1610
+ setMode("ai");
1380
1611
  updateCounter();
1381
1612
  followAnswer();
1382
1613
  trackKeyboard();
1383
1614
  trackOffset();
1384
- startConversation();
1615
+ const stored = storageKey ? readThread(storageKey) : null;
1616
+ if (stored) {
1617
+ session.restoreHistory(stored.history);
1618
+ if (stored.entries.length) {
1619
+ clearStart();
1620
+ for (const entry of stored.entries) renderEntry(entry);
1621
+ entries = [...stored.entries];
1622
+ }
1623
+ isOpen = stored.open === true;
1624
+ root.toggleAttribute("data-ai-chat-open", isOpen);
1625
+ scrollToEnd();
1626
+ }
1627
+ if (stored?.conversationId) session.setContext(CONVERSATION_CONTEXT, stored.conversationId);
1628
+ else startConversation();
1629
+ if (stored?.live) resumeLive(stored.live);
1385
1630
  const binding = {
1386
1631
  session,
1387
1632
  labels,
1633
+ get mode() {
1634
+ return mode;
1635
+ },
1636
+ get isOpen() {
1637
+ return isOpen;
1638
+ },
1639
+ get liveChat() {
1640
+ return live?.provider ?? null;
1641
+ },
1388
1642
  appendAssistantReply(text) {
1389
1643
  const content = text.trim();
1390
1644
  if (!content) return;
1391
1645
  appendMarkdown(appendMessage("assistant"), content);
1392
1646
  session.addAssistantReply(content);
1647
+ record({
1648
+ kind: "assistant",
1649
+ parts: [{ text: content }],
1650
+ turn: null
1651
+ });
1393
1652
  },
1394
1653
  setFormContext(name, summary, followUp) {
1395
1654
  const content = summary.trim();
@@ -1398,10 +1657,45 @@ function bindChat(root, options = {}) {
1398
1657
  formContexts.set(name, content);
1399
1658
  session.setContextMessage(name, content);
1400
1659
  if (first && followUp) binding.appendAssistantReply(followUp);
1660
+ else save();
1661
+ },
1662
+ open() {
1663
+ setOpen(true);
1664
+ },
1665
+ close() {
1666
+ setOpen(false);
1667
+ },
1668
+ handover(handover = {}) {
1669
+ if (mode === "live") return Promise.resolve({ status: "live" });
1670
+ handoverInFlight ??= runHandover(handover).finally(() => {
1671
+ handoverInFlight = null;
1672
+ });
1673
+ return handoverInFlight;
1674
+ },
1675
+ async endLiveChat() {
1676
+ const provider = live?.provider;
1677
+ if (!provider) return;
1678
+ finishLive("visitor");
1679
+ await provider.end();
1680
+ },
1681
+ on(name, listener) {
1682
+ let listeners = eventListeners.get(name);
1683
+ if (!listeners) {
1684
+ listeners = /* @__PURE__ */ new Set();
1685
+ eventListeners.set(name, listeners);
1686
+ }
1687
+ const added = listener;
1688
+ listeners.add(added);
1689
+ return () => {
1690
+ listeners.delete(added);
1691
+ };
1401
1692
  },
1402
1693
  destroy() {
1403
1694
  if (destroyed) return;
1404
1695
  destroyed = true;
1696
+ pendingSurvey?.cancel();
1697
+ disconnect();
1698
+ eventListeners.clear();
1405
1699
  unsubscribe();
1406
1700
  session.dispose();
1407
1701
  for (const cleanup of cleanups.splice(0)) cleanup();