@vettvangur/ai-sdk 0.7.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -153,7 +153,13 @@ takes it, which the provider reports through its optional `onAgent`, or the firs
153
153
  does. Then an `__notice--joined` divider names them, the `agent` event fires, `data-ai-chat-live`
154
154
  on the root goes from `waiting` to `agent`, and elements marked `data-ai-chat-agent-name` and
155
155
  `data-ai-chat-agent-initials` are filled in. An agent's messages are `__message--person` with
156
- `__initials` and a `__sender` (their first name, then the `live-chat-team` label when set); the
156
+ `__initials` and a `__sender` (their first name, then the `live-chat-team` label when set), and
157
+ the buttons a message carries (`actions`) under it in `renderActions` markup, the first primary. A
158
+ link button opens in a new tab. A `sheet` button opens its page in a `__sheet` dialog appended to
159
+ the root: a `__sheet-header` with a `__sheet-title` (the button's text) and a `__sheet-close`
160
+ button (the `sheet-close` label), and the page in a `__sheet-frame`. Escape closes it too, and
161
+ focus goes back to the button. A provider with `connectSheet(frame, { send, close })` connects the
162
+ page to its own app protocol, so the page can send the visitor's message and close the sheet. The
157
163
  provider's own messages are `__notice--system`. While live the input shows its
158
164
  `data-ai-chat-live-placeholder`, and while the survey is asked its
159
165
  `data-ai-chat-handover-placeholder`. When the agent ends the chat (an `__notice--agent-ended` divider),
@@ -167,7 +173,7 @@ binding read. `binding.liveChat` is the provider in use, for a host to offer its
167
173
  `live-chat-typing`, `live-chat-agent`, `live-chat-started`, `live-chat-joined` and
168
174
  `live-chat-agent-ended` (with `{name}`), `live-chat-waiting`, `live-chat-waiting-text`,
169
175
  `live-chat-team`, `survey-title`, `survey-intro`, `survey-prefilled`, `survey-submit`,
170
- `survey-cancel`, `survey-required`, `survey-invalid-email`.
176
+ `survey-cancel`, `survey-required`, `survey-invalid-email`, `sheet-close`.
171
177
 
172
178
  `@vettvangur/ai-sdk/live-chat` exports the provider contract (`AiLiveChatProvider`) and
173
179
  `renderSurveyForm`. `@vettvangur/ai-sdk/live-chat/omnichannel` exports
@@ -197,7 +203,11 @@ the answers to the agent as a filled form, sets the visitor's name and email fro
197
203
  and email fields (prefill them as `name` and `email`), and gives the agent the handover context as
198
204
  session fields. Agents see what the visitor types through `draft`. LiveChat allows a visitor one
199
205
  chat, so a second handover starts a new thread in it; the resume token is the chat id. A form with
200
- any field the window cannot ask, such as a rating, is refused rather than shortened.
206
+ any field the window cannot ask, such as a rating, is refused rather than shortened. An agent's
207
+ card (a rich message) shows as its titles and subtitles with its `url` and `webview` buttons; a
208
+ webview button opens in the sheet, where the provider hosts LiveChat's Moments protocol, so an agent
209
+ app such as a sign-in works as it does in LiveChat's own widget: its `sendMessage` goes into the
210
+ chat as the visitor's message and its `close` closes the sheet.
201
211
 
202
212
  ```ts
203
213
  import { createLiveChatProvider } from '@vettvangur/ai-sdk/live-chat/livechat'
@@ -310,7 +320,9 @@ needs, not a look. It keeps `hidden` on `data-ai-chat-send`, `-stop`, `-end`,
310
320
  `data-ai-launcher-teaser` and survey errors whatever display a host gives them, pulses the tool and
311
321
  typing dots (and stops under reduced motion), hides the typing label for all but screen readers,
312
322
  draws the `started`, `joined`, `agent-ended`, `ended` and `system` notices as dividers, scrolls a
313
- wide answer-card table inside its region, and draws the survey's toggle as a switch. Load it before
323
+ wide answer-card table inside its region, draws the survey's toggle as a switch, and lays a sheet
324
+ over the root, its frame filling what the header leaves. The root needs a position for the sheet to
325
+ cover it. Load it before
314
326
  the host's own styles; its selectors are as plain as each rule allows, so a later host rule of the
315
327
  same weight wins. Colours and sizes come from custom properties, set on the root or any ancestor:
316
328
 
@@ -322,6 +334,7 @@ same weight wins. Colours and sizes come from custom properties, set on the root
322
334
  | `--vv-ai-chat-divider-gap` | `0.625rem` |
323
335
  | `--vv-ai-survey-toggle-width`, `-height`, `-inset` | `2.125rem`, `1.25rem`, `0.125rem` |
324
336
  | `--vv-ai-survey-toggle-off`, `-on`, `-knob` | `#9ca3af`, `currentColor`, `#fff` |
337
+ | `--vv-ai-chat-sheet-background` | `#fff` |
325
338
 
326
339
  The package accepts protocol-v1 events (`delta`, `tool`, `tool_result`, `tool_done`, `suggestions`,
327
340
  `done` with an optional `turn` token, and `error`) and ignores any other. Host-specific card
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, t as AiLiveChatAnswers } from "./provider.js";
1
+ import { n as AiLiveChatAnswers, o as AiLiveChatProvider } from "./provider.js";
2
2
  //#region src/contracts.d.ts
3
3
  type AiChatMessage = {
4
4
  role: 'user' | 'assistant';
@@ -152,6 +152,8 @@ type AiChatLabels = AiAnswerCardLabels & {
152
152
  surveyIntro: string;
153
153
  /** Under a field the host's prefill filled in, when not empty. */
154
154
  surveyPrefilled: string;
155
+ /** The button that closes a page an agent's message opened in a sheet over the thread. */
156
+ sheetClose: string;
155
157
  error: string;
156
158
  timeout: string;
157
159
  toolRunning: string;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, i as AiLiveChatMessage, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, s as AiLiveChatSurveyField, t as AiLiveChatAnswers } from "./provider.js";
1
+ import { a as AiLiveChatMessage, c as AiLiveChatStartOptions, l as AiLiveChatSurveyField, n as AiLiveChatAnswers, o as AiLiveChatProvider, r as AiLiveChatAvailability, s as AiLiveChatSheetHost, t as AiLiveChatAction } from "./provider.js";
2
2
  import { A as AiHandoverPayload, C as AiChatSession, D as AiChatStreamEvent, E as AiChatSessionStatus, M as AiLiveChatFactoryContext, N as AiTemplateItemSurfaceOptions, O as AiChatSurface, P as AiTemplateUrlSurfaceOptions, S as AiChatRequest, T as AiChatSessionResult, _ as AiChatLabels, a as AiAnswerCardSection, b as AiChatRegistry, c as AiChatAction, d as AiChatBindings, f as AiChatContext, g as AiChatHandoverResult, h as AiChatHandoverOptions, i as AiAnswerCardLink, j as AiLauncherTeaserOptions, k as AiFormContextOptions, l as AiChatActionItem, m as AiChatExtensionContext, n as AiAnswerCardFact, o as AiAnswerCardTable, p as AiChatEventMap, r as AiAnswerCardLabels, s as AiCardImage, t as AiAnswerCard, u as AiChatBinding, v as AiChatMessage, w as AiChatSessionOptions, x as AiChatRenderer, y as AiChatMode } from "./contracts.js";
3
3
  //#region src/answer-card.d.ts
4
4
  declare const MAX_ANSWER_CARD_SECTIONS = 12;
@@ -133,4 +133,4 @@ declare function bindChatWindow(binding: AiChatBinding): () => void;
133
133
  */
134
134
  declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
135
135
  //#endregion
136
- export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiCardImage, type AiChatAction, type AiChatActionItem, type AiChatBinding, type AiChatBindings, type AiChatContext, type AiChatEventMap, type AiChatExtensionContext, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiFormContextOptions, type AiHandoverPayload, type AiLauncherTeaserOptions, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, type AiTemplateUrlSurfaceOptions, 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 };
136
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiCardImage, type AiChatAction, type AiChatActionItem, type AiChatBinding, type AiChatBindings, type AiChatContext, type AiChatEventMap, type AiChatExtensionContext, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiFormContextOptions, type AiHandoverPayload, type AiLauncherTeaserOptions, type AiLiveChatAction, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatSheetHost, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, type AiTemplateUrlSurfaceOptions, 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 };
package/dist/index.js CHANGED
@@ -364,6 +364,61 @@ function assertAnswerCardContract(card) {
364
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
365
  }
366
366
  //#endregion
367
+ //#region src/cards.ts
368
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
369
+ const CARD_LIST_CLASS = "vv-ai-card-list";
370
+ const ACTIONS_CLASS = "vv-ai-actions";
371
+ function text(value) {
372
+ return typeof value === "string" && value.trim() ? value : null;
373
+ }
374
+ /**
375
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
376
+ * Items that render nothing are skipped, and a list with nothing in it is null.
377
+ */
378
+ function renderCardList(document, items, render, modifier) {
379
+ if (!Array.isArray(items)) return null;
380
+ const cards = items.map(render).filter((card) => card !== null);
381
+ if (!cards.length) return null;
382
+ const list = createPart(document, "div", CARD_LIST_CLASS);
383
+ if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
384
+ list.append(...cards);
385
+ return list;
386
+ }
387
+ /**
388
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
389
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
390
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
391
+ */
392
+ function renderActions(document, items) {
393
+ const elements = [];
394
+ for (const item of items) {
395
+ const label = text(item?.label);
396
+ if (!label) continue;
397
+ let element = null;
398
+ const action = text(item.action);
399
+ const url = text(item.url);
400
+ if (action) {
401
+ const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
402
+ button.type = "button";
403
+ button.dataset.aiAction = action;
404
+ const value = text(item.value);
405
+ if (value) button.dataset.aiActionValue = value;
406
+ element = button;
407
+ } else if (url) {
408
+ element = createSafeLink(document, label, url.trim());
409
+ if (element) element.className = `${ACTIONS_CLASS}__action`;
410
+ }
411
+ if (element) {
412
+ element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
413
+ elements.push(element);
414
+ }
415
+ }
416
+ if (!elements.length) return null;
417
+ const actions = createPart(document, "div", ACTIONS_CLASS);
418
+ actions.append(...elements);
419
+ return actions;
420
+ }
421
+ //#endregion
367
422
  //#region src/protocol.ts
368
423
  const AI_CHAT_PROTOCOL_VERSION = 1;
369
424
  const MAX_TURN_TOKEN_LENGTH = 1024;
@@ -678,61 +733,6 @@ function createChatSession(options) {
678
733
  return session;
679
734
  }
680
735
  //#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
736
  //#region src/handover.ts
737
737
  /** The action the handover card's button runs; the binding hands over to a person with it. */
738
738
  const LIVE_CHAT_ACTION = "livechat";
@@ -784,6 +784,60 @@ function registryEntries(registry) {
784
784
  return registry ? entries.get(registry) : void 0;
785
785
  }
786
786
  //#endregion
787
+ //#region src/sheet.ts
788
+ /** The `data-ai-action` of a button that opens its `data-ai-action-value` in a sheet. */
789
+ const SHEET_ACTION = "sheet";
790
+ const SHEET_CLASS = "vv-ai-chat";
791
+ /**
792
+ * A page in a sheet over the chat: a dialog with a title, a close button and the page in a frame,
793
+ * appended to `root`. Escape closes it too, and focus goes back to where it was. Null for a URL
794
+ * a link could not open either.
795
+ */
796
+ function openSheet(root, options) {
797
+ if (!isSafeLinkUrl(options.url)) return null;
798
+ const document = root.ownerDocument;
799
+ const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
800
+ const titleId = `vv-ai-chat-sheet-${crypto.randomUUID()}`;
801
+ const sheet = createPart(document, "div", SHEET_CLASS, "sheet");
802
+ sheet.dataset.aiChatSheet = "";
803
+ sheet.setAttribute("role", "dialog");
804
+ sheet.setAttribute("aria-modal", "true");
805
+ sheet.setAttribute("aria-labelledby", titleId);
806
+ const header = createPart(document, "div", SHEET_CLASS, "sheet-header");
807
+ const title = createPart(document, "p", SHEET_CLASS, "sheet-title", options.title);
808
+ title.id = titleId;
809
+ const close = createPart(document, "button", SHEET_CLASS, "sheet-close", options.closeLabel);
810
+ close.type = "button";
811
+ header.append(title, close);
812
+ const frame = createPart(document, "iframe", SHEET_CLASS, "sheet-frame");
813
+ frame.title = options.title;
814
+ frame.src = options.url;
815
+ sheet.append(header, frame);
816
+ let open = true;
817
+ function dismiss() {
818
+ if (!open) return;
819
+ open = false;
820
+ sheet.removeEventListener("keydown", keydown);
821
+ sheet.remove();
822
+ returnFocus?.focus({ preventScroll: true });
823
+ options.onClose();
824
+ }
825
+ function keydown(event) {
826
+ if (event.key === "Escape") {
827
+ event.stopPropagation();
828
+ dismiss();
829
+ }
830
+ }
831
+ close.addEventListener("click", dismiss);
832
+ sheet.addEventListener("keydown", keydown);
833
+ root.append(sheet);
834
+ close.focus({ preventScroll: true });
835
+ return {
836
+ frame,
837
+ close: dismiss
838
+ };
839
+ }
840
+ //#endregion
787
841
  //#region src/thread-store.ts
788
842
  function storage() {
789
843
  try {
@@ -846,7 +900,8 @@ const defaultLabels = {
846
900
  surveyInvalidEmail: "Please enter an email address",
847
901
  surveyTitle: "",
848
902
  surveyIntro: "",
849
- surveyPrefilled: ""
903
+ surveyPrefilled: "",
904
+ sheetClose: "Close"
850
905
  };
851
906
  const NEAR_LIMIT = .9;
852
907
  const TYPING_SHOWN_MS = 5e3;
@@ -885,6 +940,10 @@ function stringRecord(value) {
885
940
  if (!isPlainObject(value)) return {};
886
941
  return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
887
942
  }
943
+ function storedActions(value) {
944
+ if (!Array.isArray(value)) return [];
945
+ return value.filter((item) => isPlainObject(item) && typeof item.label === "string" && typeof item.url === "string" && typeof item.sheet === "boolean");
946
+ }
888
947
  function dataString(data, name) {
889
948
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
890
949
  const value = data[name];
@@ -937,6 +996,7 @@ function bindChat(root, options = {}) {
937
996
  let typingSentAt = 0;
938
997
  let draftTimer = null;
939
998
  let waitingCard = null;
999
+ let sheet = null;
940
1000
  const placeholder = input.placeholder;
941
1001
  const eventListeners = /* @__PURE__ */ new Map();
942
1002
  const session = createChatSession({
@@ -1227,7 +1287,7 @@ function bindChat(root, options = {}) {
1227
1287
  avatar.append(initials(name || labels.liveChatAgent));
1228
1288
  parent.append(avatar);
1229
1289
  }
1230
- function appendPerson(name, text) {
1290
+ function appendPerson(name, text, actions = []) {
1231
1291
  const message = appendMessage("person");
1232
1292
  appendInitials(message, name);
1233
1293
  const sender = root.ownerDocument.createElement("span");
@@ -1235,9 +1295,39 @@ function bindChat(root, options = {}) {
1235
1295
  const shown = name ? firstName(name) : labels.liveChatAgent;
1236
1296
  sender.append(labels.liveChatTeam ? `${shown} · ${labels.liveChatTeam}` : shown);
1237
1297
  message.append(sender);
1238
- appendMarkdown(message, text);
1298
+ if (text) appendMarkdown(message, text);
1299
+ const buttons = renderActions(root.ownerDocument, actions.map((action, index) => action.sheet ? {
1300
+ label: action.label,
1301
+ action: SHEET_ACTION,
1302
+ value: action.url,
1303
+ primary: index === 0
1304
+ } : {
1305
+ label: action.label,
1306
+ url: action.url,
1307
+ primary: index === 0
1308
+ }));
1309
+ if (buttons) message.append(buttons);
1239
1310
  scrollToEnd();
1240
1311
  }
1312
+ function showSheet(url, title) {
1313
+ sheet?.close();
1314
+ let disconnectSheet = () => {};
1315
+ const opened = openSheet(root, {
1316
+ url,
1317
+ title,
1318
+ closeLabel: labels.sheetClose,
1319
+ onClose: () => {
1320
+ disconnectSheet();
1321
+ if (sheet === opened) sheet = null;
1322
+ }
1323
+ });
1324
+ sheet = opened;
1325
+ const provider = live?.provider ?? liveChat;
1326
+ if (opened && provider?.connectSheet) disconnectSheet = provider.connectSheet(opened.frame, {
1327
+ send: sendLive,
1328
+ close: opened.close
1329
+ });
1330
+ }
1241
1331
  function notifyAgent(template, name, modifier) {
1242
1332
  const time = new Intl.DateTimeFormat(root.ownerDocument.documentElement.lang || void 0, {
1243
1333
  hour: "2-digit",
@@ -1311,7 +1401,7 @@ function bindChat(root, options = {}) {
1311
1401
  for (const item of entry.parts) if ("text" in item && typeof item.text === "string") appendMarkdown(message, item.text);
1312
1402
  else if ("result" in item && isPlainObject(item.result) && typeof item.result.name === "string") renderResult(message, item.result);
1313
1403
  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);
1404
+ } else if (entry.kind === "person" && typeof entry.text === "string") appendPerson(typeof entry.name === "string" ? entry.name : null, entry.text, storedActions(entry.actions));
1315
1405
  else if (entry.kind === "notice" && typeof entry.text === "string" && typeof entry.modifier === "string") appendNotice(entry.text, entry.modifier);
1316
1406
  }
1317
1407
  const setMode = (next) => {
@@ -1339,12 +1429,13 @@ function bindChat(root, options = {}) {
1339
1429
  if (message.sender === "agent" && !live.agent) agentJoined({ name: message.name });
1340
1430
  if (message.sender === "system") notify(message.text, "system");
1341
1431
  else {
1342
- appendPerson(message.name, message.text);
1432
+ appendPerson(message.name, message.text, message.actions);
1343
1433
  record({
1344
1434
  kind: "person",
1345
1435
  id: message.id,
1346
1436
  text: message.text,
1347
- name: message.name
1437
+ name: message.name,
1438
+ ...message.actions?.length ? { actions: message.actions } : {}
1348
1439
  });
1349
1440
  }
1350
1441
  }
@@ -1527,11 +1618,6 @@ function bindChat(root, options = {}) {
1527
1618
  }
1528
1619
  async function sendLive(text) {
1529
1620
  if (!live) return;
1530
- if (draftTimer) {
1531
- clearTimeout(draftTimer);
1532
- draftTimer = null;
1533
- }
1534
- clearInput();
1535
1621
  clearStart();
1536
1622
  appendMarkdown(appendMessage("user"), text);
1537
1623
  record({
@@ -1546,6 +1632,11 @@ function bindChat(root, options = {}) {
1546
1632
  const question = input.value.trim();
1547
1633
  if (!question || mode === "handover") return;
1548
1634
  if (mode === "live") {
1635
+ if (draftTimer) {
1636
+ clearTimeout(draftTimer);
1637
+ draftTimer = null;
1638
+ }
1639
+ clearInput();
1549
1640
  sendLive(question).catch(report);
1550
1641
  return;
1551
1642
  }
@@ -1623,6 +1714,7 @@ function bindChat(root, options = {}) {
1623
1714
  }
1624
1715
  if (target?.closest("[data-ai-chat-reset]")) {
1625
1716
  const provider = live?.provider;
1717
+ sheet?.close();
1626
1718
  disconnect();
1627
1719
  handoverRuns += 1;
1628
1720
  pendingSurvey?.cancel();
@@ -1654,6 +1746,7 @@ function bindChat(root, options = {}) {
1654
1746
  const actionElement = target?.closest("[data-ai-action]");
1655
1747
  const action = actionElement ? registryEntries(options.registry)?.actions.get(actionElement.dataset.aiAction ?? "") : void 0;
1656
1748
  if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover().catch(report);
1749
+ else if (!action && actionElement?.dataset.aiAction === "sheet") showSheet(actionElement.dataset.aiActionValue ?? "", actionElement.textContent?.trim() ?? "");
1657
1750
  else if (action && actionElement) Promise.resolve(action({
1658
1751
  root,
1659
1752
  element: actionElement,
@@ -1827,6 +1920,7 @@ function bindChat(root, options = {}) {
1827
1920
  destroy() {
1828
1921
  if (destroyed) return;
1829
1922
  destroyed = true;
1923
+ sheet?.close();
1830
1924
  pendingSurvey?.cancel();
1831
1925
  disconnect();
1832
1926
  eventListeners.clear();
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, s as AiLiveChatSurveyField } from "../provider.js";
1
+ import { l as AiLiveChatSurveyField, o as AiLiveChatProvider } from "../provider.js";
2
2
  import { M as AiLiveChatFactoryContext } from "../contracts.js";
3
3
  //#region src/live-chat/aichat.d.ts
4
4
  type AiChatLiveConfig = {
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider } from "../provider.js";
1
+ import { o as AiLiveChatProvider } from "../provider.js";
2
2
  //#region src/live-chat/livechat.d.ts
3
3
  type AiLiveChatConfig = {
4
4
  organizationId: string;
@@ -1,3 +1,124 @@
1
+ //#region src/live-chat/moments.ts
2
+ const FINGERPRINT = "@@livechat/postmessenger";
3
+ const FOUR_WAY_HANDSHAKE = "@@livechat/4way";
4
+ const HANDSHAKE_INTERVAL_MS = 500;
5
+ const HANDSHAKE_TRIES = 10;
6
+ const ECHO_REQUEST = 0;
7
+ const SUPPORTED_METHODS = ["sendMessage", "close"];
8
+ function isEnvelope(value, owner) {
9
+ return typeof value === "object" && value !== null && value[FINGERPRINT] === true && value.owner === owner && value.instance === 0;
10
+ }
11
+ function call(data) {
12
+ if (typeof data !== "object" || data === null) return null;
13
+ const { method, args } = data;
14
+ return typeof method === "string" ? {
15
+ method,
16
+ args: Array.isArray(args) ? args : []
17
+ } : null;
18
+ }
19
+ function messageText(arg) {
20
+ const text = typeof arg === "object" && arg !== null ? arg.text : null;
21
+ return typeof text === "string" ? text.trim() : "";
22
+ }
23
+ /**
24
+ * Hosts a LiveChat Moments app in `frame`: its `sendMessage` goes into the chat as the visitor's
25
+ * message and its `close` closes the sheet. A page that is not a Moments app never answers the
26
+ * handshake and is left alone. Each load of the frame is a new handshake. Returns a disconnect.
27
+ */
28
+ function hostMoments(frame, host) {
29
+ const view = frame.ownerDocument.defaultView;
30
+ if (!view) return () => {};
31
+ const owner = crypto.randomUUID();
32
+ const origin = new URL(frame.src, frame.ownerDocument.baseURI).origin;
33
+ let state = "handshake";
34
+ let timer = null;
35
+ function post(message) {
36
+ frame.contentWindow?.postMessage(message, origin);
37
+ }
38
+ function envelope(type, data, request) {
39
+ return {
40
+ [FINGERPRINT]: true,
41
+ owner,
42
+ instance: 0,
43
+ type,
44
+ data,
45
+ request
46
+ };
47
+ }
48
+ function stopHandshake() {
49
+ if (timer) clearInterval(timer);
50
+ timer = null;
51
+ }
52
+ function handshake() {
53
+ stopHandshake();
54
+ state = "handshake";
55
+ let tries = 0;
56
+ const send = () => {
57
+ tries += 1;
58
+ if (state !== "handshake" || tries > HANDSHAKE_TRIES) {
59
+ stopHandshake();
60
+ return;
61
+ }
62
+ post(envelope("handshake", { supportedMethods: SUPPORTED_METHODS }, null));
63
+ };
64
+ send();
65
+ timer = setInterval(send, HANDSHAKE_INTERVAL_MS);
66
+ }
67
+ async function run(method, args) {
68
+ switch (method) {
69
+ case "sendMessage": {
70
+ const text = messageText(args[0]);
71
+ if (text) await host.send(text);
72
+ return null;
73
+ }
74
+ case "close":
75
+ host.close();
76
+ return null;
77
+ default: throw new Error(`The chat window does not support ${method}`);
78
+ }
79
+ }
80
+ function receive(event) {
81
+ if (event.source !== frame.contentWindow || event.origin !== origin || !isEnvelope(event.data, owner)) return;
82
+ const message = event.data;
83
+ if (message.type === "response" && state === "handshake" && message.request === null) {
84
+ stopHandshake();
85
+ const result = message.data?.result;
86
+ if (typeof result === "object" && result !== null && FOUR_WAY_HANDSHAKE in result) {
87
+ state = "echo";
88
+ post(envelope("handshake_echo", void 0, ECHO_REQUEST));
89
+ } else state = "connected";
90
+ return;
91
+ }
92
+ if (message.type === "response" && state === "echo" && message.request === ECHO_REQUEST) {
93
+ state = "connected";
94
+ return;
95
+ }
96
+ const request = message.type === "call" && state === "connected" ? call(message.data) : null;
97
+ if (!request) return;
98
+ run(request.method, request.args).then((result) => {
99
+ post(envelope("response", {
100
+ error: false,
101
+ result
102
+ }, message.request ?? null));
103
+ }, (caught) => {
104
+ post(envelope("response", {
105
+ error: true,
106
+ result: {
107
+ real: true,
108
+ error: { message: caught instanceof Error ? caught.message : String(caught) }
109
+ }
110
+ }, message.request ?? null));
111
+ });
112
+ }
113
+ view.addEventListener("message", receive);
114
+ frame.addEventListener("load", handshake);
115
+ return () => {
116
+ stopHandshake();
117
+ view.removeEventListener("message", receive);
118
+ frame.removeEventListener("load", handshake);
119
+ };
120
+ }
121
+ //#endregion
1
122
  //#region src/live-chat/livechat.ts
2
123
  function on(sdk, method, type, handler) {
3
124
  sdk[method](type, handler);
@@ -136,6 +257,28 @@ function filledFormFields(form, answers) {
136
257
  }
137
258
  return filled;
138
259
  }
260
+ /**
261
+ * A rich message as an agent message: each card's title and subtitle as its text, and its link
262
+ * buttons as its buttons. A webview button, such as an agent app's sign-in, opens in a sheet over
263
+ * the thread, as LiveChat's own widget does; buttons that post back to the agent are left out.
264
+ */
265
+ function richMessage(event) {
266
+ const parts = [];
267
+ const actions = [];
268
+ for (const element of event.elements) {
269
+ if (element.title?.trim()) parts.push(`**${element.title.trim()}**`);
270
+ if (element.subtitle?.trim()) parts.push(element.subtitle.trim());
271
+ for (const button of element.buttons ?? []) if ((button.type === "url" || button.type === "open_external" || button.type === "webview") && button.text.trim()) actions.push({
272
+ label: button.text.trim(),
273
+ url: button.value,
274
+ sheet: button.type === "webview"
275
+ });
276
+ }
277
+ return {
278
+ text: parts.join("\n\n"),
279
+ actions
280
+ };
281
+ }
139
282
  function errorCode(caught) {
140
283
  return caught && typeof caught === "object" && "code" in caught ? String(caught.code) : null;
141
284
  }
@@ -162,15 +305,20 @@ function createLiveChatProvider(config) {
162
305
  for (const listener of agentListeners) listener({ name: user.name.trim() || null });
163
306
  }
164
307
  function receive(event) {
165
- if (!event || event.authorId === customerId || event.type !== "message" && event.type !== "system_message") return;
166
- const text = event.text.trim();
167
- if (!text) return;
308
+ if (!event || event.authorId === customerId) return;
309
+ if (event.type !== "message" && event.type !== "system_message" && event.type !== "rich_message") return;
310
+ const { text, actions } = event.type === "rich_message" ? richMessage(event) : {
311
+ text: event.text.trim(),
312
+ actions: []
313
+ };
314
+ if (!text && !actions.length) return;
168
315
  const system = event.type === "system_message";
169
316
  const item = {
170
317
  id: event.id,
171
318
  text,
172
319
  sender: system ? "system" : "agent",
173
- name: system ? null : agentNames.get(event.authorId)?.trim() || null
320
+ name: system ? null : agentNames.get(event.authorId)?.trim() || null,
321
+ ...actions.length ? { actions } : {}
174
322
  };
175
323
  for (const listener of messageListeners) listener(item);
176
324
  }
@@ -376,6 +524,9 @@ function createLiveChatProvider(config) {
376
524
  properties: {}
377
525
  }
378
526
  });
527
+ },
528
+ connectSheet(frame, host) {
529
+ return hostMoments(frame, host);
379
530
  }
380
531
  };
381
532
  }
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider } from "../provider.js";
1
+ import { o as AiLiveChatProvider } from "../provider.js";
2
2
  //#region src/live-chat/omnichannel.d.ts
3
3
  type AiOmnichannelConfig = {
4
4
  orgId: string;
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, c as AiLiveChatSurveyNote, i as AiLiveChatMessage, l as AiLiveChatTextField, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, r as AiLiveChatChoiceField, s as AiLiveChatSurveyField, t as AiLiveChatAnswers, u as AiLiveChatToggleField } from "./provider.js";
1
+ import { a as AiLiveChatMessage, c as AiLiveChatStartOptions, d as AiLiveChatTextField, f as AiLiveChatToggleField, i as AiLiveChatChoiceField, l as AiLiveChatSurveyField, n as AiLiveChatAnswers, o as AiLiveChatProvider, r as AiLiveChatAvailability, s as AiLiveChatSheetHost, t as AiLiveChatAction, u as AiLiveChatSurveyNote } from "./provider.js";
2
2
  //#region src/live-chat/survey.d.ts
3
3
  /** Every element of the survey form carries a class under this block. */
4
4
  declare const SURVEY_CLASS = "vv-ai-survey";
@@ -33,4 +33,4 @@ type AiLiveChatSurveyForm = {
33
33
  */
34
34
  declare function renderSurveyForm(document: Document, fields: readonly AiLiveChatSurveyField[], options: AiLiveChatSurveyOptions): AiLiveChatSurveyForm;
35
35
  //#endregion
36
- export { type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatChoiceField, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiLiveChatSurveyForm, type AiLiveChatSurveyLabels, type AiLiveChatSurveyNote, type AiLiveChatSurveyOptions, type AiLiveChatTextField, type AiLiveChatToggleField, SURVEY_CLASS, renderSurveyForm };
36
+ export { type AiLiveChatAction, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatChoiceField, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatSheetHost, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiLiveChatSurveyForm, type AiLiveChatSurveyLabels, type AiLiveChatSurveyNote, type AiLiveChatSurveyOptions, type AiLiveChatTextField, type AiLiveChatToggleField, SURVEY_CLASS, renderSurveyForm };
@@ -56,12 +56,28 @@ type AiLiveChatStartOptions = {
56
56
  /** A token from `resumeToken()`: reconnect to that chat instead of starting a new one. */
57
57
  resume?: string;
58
58
  };
59
+ /**
60
+ * A button under an agent's message: a link that opens in a new tab, or, with `sheet`, a page the
61
+ * window opens in a sheet over the thread, such as an agent app's sign-in.
62
+ */
63
+ type AiLiveChatAction = {
64
+ label: string;
65
+ url: string;
66
+ sheet: boolean;
67
+ };
59
68
  type AiLiveChatMessage = {
60
69
  id: string;
61
70
  text: string;
62
71
  sender: 'agent' | 'system';
63
72
  /** The agent's display name, when the provider has one. */
64
73
  name: string | null;
74
+ actions?: AiLiveChatAction[];
75
+ };
76
+ /** What a page in a sheet can ask of the window. */
77
+ type AiLiveChatSheetHost = {
78
+ /** Sends text into the live chat as the visitor's message. */
79
+ send(text: string): Promise<void>;
80
+ close(): void;
65
81
  };
66
82
  /**
67
83
  * What the chat window needs from a live chat service. `onMessage`, `onTyping` and `onEnded` may
@@ -97,6 +113,11 @@ type AiLiveChatProvider = {
97
113
  message?: string;
98
114
  }): Promise<void>;
99
115
  upload?(file: File): Promise<void>;
116
+ /**
117
+ * Connects a page the window opened in a sheet to the provider's own app protocol, so the page
118
+ * can send the visitor's message and close the sheet. Returns a disconnect.
119
+ */
120
+ connectSheet?(frame: HTMLIFrameElement, host: AiLiveChatSheetHost): () => void;
100
121
  };
101
122
  //#endregion
102
- export { AiLiveChatProvider as a, AiLiveChatSurveyNote as c, AiLiveChatMessage as i, AiLiveChatTextField as l, AiLiveChatAvailability as n, AiLiveChatStartOptions as o, AiLiveChatChoiceField as r, AiLiveChatSurveyField as s, AiLiveChatAnswers as t, AiLiveChatToggleField as u };
123
+ export { AiLiveChatMessage as a, AiLiveChatStartOptions as c, AiLiveChatTextField as d, AiLiveChatToggleField as f, AiLiveChatChoiceField as i, AiLiveChatSurveyField as l, AiLiveChatAnswers as n, AiLiveChatProvider as o, AiLiveChatAvailability as r, AiLiveChatSheetHost as s, AiLiveChatAction as t, AiLiveChatSurveyNote as u };
package/dist/styles.css CHANGED
@@ -15,6 +15,7 @@
15
15
  * --vv-ai-survey-toggle-off the switch's track when off (#9ca3af)
16
16
  * --vv-ai-survey-toggle-on the switch's track when on (currentColor)
17
17
  * --vv-ai-survey-toggle-knob the knob (#fff)
18
+ * --vv-ai-chat-sheet-background the sheet an agent's button opens (#fff)
18
19
  */
19
20
 
20
21
  /* What the binding shows and hides with `hidden` stays hidden whatever display a host gives it. */
@@ -111,6 +112,32 @@
111
112
  overscroll-behavior-x: contain;
112
113
  }
113
114
 
115
+ /*
116
+ * A page an agent's button opens, over the whole root, which needs a position for it to cover. The
117
+ * frame fills what the header leaves.
118
+ */
119
+ .vv-ai-chat__sheet {
120
+ position: absolute;
121
+ inset: 0;
122
+ z-index: 1;
123
+ display: flex;
124
+ flex-direction: column;
125
+ background: var(--vv-ai-chat-sheet-background, #fff);
126
+ }
127
+
128
+ .vv-ai-chat__sheet-header {
129
+ display: flex;
130
+ align-items: center;
131
+ justify-content: space-between;
132
+ }
133
+
134
+ .vv-ai-chat__sheet-frame {
135
+ flex: 1;
136
+ width: 100%;
137
+ min-height: 0;
138
+ border: 0;
139
+ }
140
+
114
141
  /*
115
142
  * The survey's yes-or-no question as a switch. The input selector outweighs a host's own rule for
116
143
  * every survey input, which would otherwise draw the switch as a text box.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.7.4",
3
+ "version": "0.8.0",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",