@vettvangur/ai-sdk 0.10.0 → 0.13.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
@@ -126,23 +126,33 @@ it again and carries on. A reset clears it. Without storage, the chat works as b
126
126
  `binding.handover({ provider, context, prefill })` hands the thread to a person through a live
127
127
  chat provider (`provider` defaults to the `liveChat` option). It asks the provider whether anyone is
128
128
  there, shows its pre-chat survey in the thread as a `vv-ai-survey` form with `prefill` values in it
129
- (by field name or id), and starts the chat. The form has an optional `survey-title` and
129
+ (by field name or id), and starts the chat. A toggle is never ticked from `prefill`: consent is
130
+ the visitor's to give. The form has an optional `survey-title` and
130
131
  `survey-intro` above its fields, a `survey-prefilled` note under each field filled in for the
131
132
  visitor, and checks that an email field holds an address (`survey-invalid-email`). With `handoverEndpoint` (or
132
133
  `data-ai-chat-handover-endpoint`), it first posts `{ conversationId, culture, messages }` with the
133
- antiforgery header and expects `{ transcript, context }`: the transcript is sent as the visitor's
134
- opening message and the context goes to the agent, under the `context` the host passes. A failed
134
+ antiforgery header and expects `{ transcript, context, ticket }`: the transcript is sent as the
135
+ visitor's opening message and the context goes to the agent, under the `context` the host passes.
136
+ Each assistant message carries the `signature` the stream gave it (`replySignature` on a
137
+ `tool_result`, `signature` on `done`), and Vettvangur.AiChat 2.0 leaves out of the transcript any
138
+ assistant line whose signature does not hold, so a visitor cannot write the assistant's side. The
139
+ `ticket` is what the AiChat Live desk starts from. A failed
135
140
  request hands over without them, so a visitor always reaches a person. It resolves to `live`,
136
141
  `closed` with a reason, `canceled` or `failed`. Every handover starts from the `handoverPrefill`
137
- option, or the `data-ai-chat-live-prefill` attribute as a JSON object of answers, when `prefill` is
138
- not passed; JSON that does not parse is reported to `onError` and left out.
142
+ option, or the `data-ai-chat-live-prefill` attribute as a JSON object of answers, with `prefill`
143
+ over it; JSON that does not parse is reported to `onError` and left out.
139
144
 
140
145
  A `tool_result` with `kind: 'handover'`, or from the `request_human_agent` tool (`HANDOVER_TOOL`)
141
146
  without a kind, is drawn as a handover card when no renderer is registered for the tool:
142
147
  `{ liveChatAvailable, contactUrl }` become a primary `live-chat` button and a `contact` link, in
143
148
  `renderActions` markup. The button's action is `livechat` (`LIVE_CHAT_ACTION`), which the binding
144
- runs as `handover()` unless the host registers its own. `isHandoverPayload` and
145
- `renderHandoverCard(document, data, labels)` are exported for a host that draws it elsewhere.
149
+ runs as `handover()` unless the host registers its own, with the payload's optional `prefill` (survey
150
+ answers by field name or id, such as a department) as the handover's `prefill`. A card that arrives
151
+ in the stream asks the `liveChat` provider's `availability()` at once, and when it is closed the
152
+ button gives way to a `vv-ai-actions__note` with the `live-chat-closed` label; a card drawn again
153
+ from the stored thread keeps its button, and the click asks again. `isHandoverPayload`,
154
+ `renderHandoverCard(document, data, labels)` and `closeHandoverCard(parent, text)` are exported for a
155
+ host that draws it elsewhere.
146
156
 
147
157
  `binding.mode`, also `data-ai-chat-mode` on the root, is `ai`, `handover` (the input is disabled
148
158
  while the survey is asked) or `live`. While live, the composer sends to the provider and the
@@ -158,7 +168,9 @@ the buttons a message carries (`actions`) in its `__text` bubble (or in the mess
158
168
  no text) in `renderActions` markup, the first primary. A
159
169
  link button opens in a new tab. A `sheet` button opens its page in a `__sheet` dialog appended to
160
170
  the root: a `__sheet-header` with a `__sheet-title` (the button's text) and a `__sheet-close`
161
- button (the `sheet-close` label), and the page in a `__sheet-frame`. Escape closes it too, and
171
+ button (the `sheet-close` label), and the page in a `__sheet-frame`, sandboxed to scripts, forms,
172
+ popups and its own origin. When the page is on another host, a `__sheet-host` line under the title
173
+ names it, so the visitor sees where they are signing in. Escape closes it too, and
162
174
  focus goes back to the button. A provider with `connectSheet(frame, { send, close })` connects the
163
175
  page to its own app protocol, so the page can send the visitor's message and close the sheet. The
164
176
  provider's own messages are `__notice--system`. While live the input shows its
@@ -222,7 +234,10 @@ section. `endpoint` is the prefix the site maps with `MapAiChat`, and `headers`
222
234
  request, so pass the antiforgery header the chat sends. It reports `no-agents` while nobody has the
223
235
  Live view open, and its resume token is the visitor's chat token. Given `survey` fields, it asks
224
236
  them before the chat starts and sends the answers to the agent by field name, a choice by its label
225
- and a toggle as `yes` or `no` (`true` and `false` when not given).
237
+ and a toggle as `yes` or `no` (`true` and `false` when not given). It starts the chat from the
238
+ handover's `ticket`, so the transcript and context the agent sees are the ones the server signed,
239
+ and the window's own context goes as added details. It needs Vettvangur.AiChat 2.0 or later. The
240
+ events stream reconnects when it drops and stops when the server answers 401, 403 or 404.
226
241
 
227
242
  ```ts
228
243
  import { createAiChatLiveProvider } from '@vettvangur/ai-sdk/live-chat/aichat'
@@ -3,6 +3,8 @@ import { n as AiLiveChatAnswers, o as AiLiveChatProvider } from "./provider.js";
3
3
  type AiChatMessage = {
4
4
  role: 'user' | 'assistant';
5
5
  content: string;
6
+ /** The server's signature on an assistant reply, which a handover needs to pass it to an agent. */
7
+ signature?: string;
6
8
  };
7
9
  type AiChatRequest = {
8
10
  messages: AiChatMessage[];
@@ -97,6 +99,7 @@ type AiChatStreamEvent = {
97
99
  name: string;
98
100
  data: unknown;
99
101
  reply: string | null;
102
+ replySignature?: string | null;
100
103
  };
101
104
  } | {
102
105
  name: 'tool_done';
@@ -114,6 +117,7 @@ type AiChatStreamEvent = {
114
117
  name: 'done';
115
118
  data: {
116
119
  turn: string | null;
120
+ signature?: string | null;
117
121
  };
118
122
  } | {
119
123
  name: 'error';
@@ -228,7 +232,7 @@ type AiChatHandoverOptions = {
228
232
  provider?: AiLiveChatProvider;
229
233
  /** Values for the agent, over those the handover endpoint returns. */
230
234
  context?: Record<string, string>;
231
- /** Survey answers to start with, by field name or id. */
235
+ /** Survey answers to start with, by field name or id, over the binding's `handoverPrefill`. */
232
236
  prefill?: AiLiveChatAnswers;
233
237
  };
234
238
  type AiChatHandoverResult = {
@@ -299,6 +303,8 @@ type AiHandoverPayload = {
299
303
  kind?: 'handover';
300
304
  liveChatAvailable?: boolean;
301
305
  contactUrl?: string | null;
306
+ /** Survey answers the live chat button starts with, by field name or id, such as a department. */
307
+ prefill?: AiLiveChatAnswers | null;
302
308
  };
303
309
  type AiTemplateUrlSurfaceOptions = {
304
310
  /** The `template[data-template]` to clone. */
package/dist/index.d.ts CHANGED
@@ -86,9 +86,15 @@ declare const HANDOVER_TOOL = "request_human_agent";
86
86
  declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
87
87
  /**
88
88
  * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
89
- * a live chat is available, and a `contact` link to a safe contact URL. Null when neither applies.
89
+ * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
90
+ * goes on the button as its value. Null when neither applies.
90
91
  */
91
92
  declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
93
+ /**
94
+ * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
95
+ * no one can take the chat. The contact link stays.
96
+ */
97
+ declare function closeHandoverCard(parent: ParentNode, text: string): void;
92
98
  //#endregion
93
99
  //#region src/protocol.d.ts
94
100
  declare const AI_CHAT_PROTOCOL_VERSION = 1;
@@ -133,4 +139,4 @@ declare function bindChatWindow(binding: AiChatBinding): () => void;
133
139
  */
134
140
  declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
135
141
  //#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 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 };
142
+ 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, closeHandoverCard, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as isSafeLinkUrl, n as createSafeImage, r as createSafeLink, t as createPart } from "./dom.js";
2
- import { A as assertAnswerCardContract, C as MAX_ANSWER_CARD_TABLE_CELLS, D as MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, E as MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, M as renderAnswerCard, O as MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, S as MAX_ANSWER_CARD_TABLES, T as MAX_ANSWER_CARD_TEXT_LENGTH, _ as renderCardList, a as createAiChatRegistry, b as MAX_ANSWER_CARD_LINKS, c as isHandoverPayload, d as readEventStream, f as AI_CHAT_PROTOCOL_VERSION, g as renderActions, h as CARD_LIST_CLASS, i as bindChat, j as isAnswerCard, k as MAX_ANSWER_CARD_URL_LENGTH, l as renderHandoverCard, m as ACTIONS_CLASS, n as bindLauncherTeaser, o as HANDOVER_TOOL, p as parseStreamEvent, r as CHAT_CLASS, s as LIVE_CHAT_ACTION, t as bindChatWindow, u as createChatSession, v as ANSWER_CARD_CLASS, w as MAX_ANSWER_CARD_TABLE_ROWS, x as MAX_ANSWER_CARD_SECTIONS, y as MAX_ANSWER_CARD_FACTS } from "./window.js";
2
+ import { A as MAX_ANSWER_CARD_URL_LENGTH, C as MAX_ANSWER_CARD_TABLES, D as MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, E as MAX_ANSWER_CARD_TEXT_LENGTH, M as isAnswerCard, N as renderAnswerCard, O as MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, S as MAX_ANSWER_CARD_SECTIONS, T as MAX_ANSWER_CARD_TABLE_ROWS, _ as renderActions, a as createAiChatRegistry, b as MAX_ANSWER_CARD_FACTS, c as closeHandoverCard, d as createChatSession, f as readEventStream, g as CARD_LIST_CLASS, h as ACTIONS_CLASS, i as bindChat, j as assertAnswerCardContract, k as MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, l as isHandoverPayload, m as parseStreamEvent, n as bindLauncherTeaser, o as HANDOVER_TOOL, p as AI_CHAT_PROTOCOL_VERSION, r as CHAT_CLASS, s as LIVE_CHAT_ACTION, t as bindChatWindow, u as renderHandoverCard, v as renderCardList, w as MAX_ANSWER_CARD_TABLE_CELLS, x as MAX_ANSWER_CARD_LINKS, y as ANSWER_CARD_CLASS } from "./window.js";
3
3
  import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
4
4
  //#region src/form-context.ts
5
5
  /**
@@ -31,4 +31,4 @@ function watchFormContext(binding, element, options) {
31
31
  return () => observer.disconnect();
32
32
  }
33
33
  //#endregion
34
- export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, HANDOVER_TOOL, LIVE_CHAT_ACTION, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, assertAnswerCardContract, bindChat, bindChatWindow, bindLauncherTeaser, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
34
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, HANDOVER_TOOL, LIVE_CHAT_ACTION, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, assertAnswerCardContract, bindChat, bindChatWindow, bindLauncherTeaser, closeHandoverCard, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
@@ -4,6 +4,7 @@ import { i as isPlainObject, o as readJsonAttribute } from "../dom.js";
4
4
  const TOKEN_HEADER = "X-AiChat-Live";
5
5
  const RETRY_MS = 1e3;
6
6
  const RETRY_LIMIT_MS = 15e3;
7
+ const MAX_RECORD_LENGTH = 1048576;
7
8
  function details(config, answers) {
8
9
  const result = {};
9
10
  for (const field of config.survey ?? []) {
@@ -49,6 +50,7 @@ async function* readEvents(body) {
49
50
  if (event) yield event;
50
51
  boundary = buffer.indexOf("\n\n");
51
52
  }
53
+ if (buffer.length > MAX_RECORD_LENGTH) throw new Error("AI chat live event is too large");
52
54
  }
53
55
  } finally {
54
56
  reader.cancel().catch(() => void 0);
@@ -117,7 +119,7 @@ function createAiChatLiveProvider(config) {
117
119
  headers: headers({ Accept: "text/event-stream" }),
118
120
  signal: controller.signal
119
121
  });
120
- if (response.status === 404) throw Object.assign(/* @__PURE__ */ new Error("AI chat live chat no longer exists"), { gone: true });
122
+ if (response.status === 404 || response.status === 401 || response.status === 403) throw Object.assign(/* @__PURE__ */ new Error("AI chat live chat no longer exists"), { gone: true });
121
123
  if (!response.ok || !response.body) throw new Error(`AI chat live events failed with ${response.status}`);
122
124
  return response.body;
123
125
  };
@@ -175,16 +177,12 @@ function createAiChatLiveProvider(config) {
175
177
  async start(options) {
176
178
  stop();
177
179
  if (options.resume) token = options.resume;
178
- else {
179
- const context = options.context ?? {};
180
- token = (await (await post("start", {
181
- conversationId: context.aiConversationId,
182
- culture: context.aiLanguage ?? document.documentElement.lang,
183
- context,
184
- details: details(config, options.answers),
185
- openingMessage: options.openingMessage
186
- })).json()).token;
187
- }
180
+ else token = (await (await post("start", {
181
+ ticket: options.ticket,
182
+ culture: options.context?.aiLanguage ?? document.documentElement.lang,
183
+ context: options.addedContext ?? {},
184
+ details: details(config, options.answers)
185
+ })).json()).token;
188
186
  try {
189
187
  await follow();
190
188
  } catch (caught) {
@@ -53,6 +53,13 @@ type AiLiveChatStartOptions = {
53
53
  context?: Record<string, string>;
54
54
  /** Sent as the visitor's first message once the chat has started. */
55
55
  openingMessage?: string;
56
+ /**
57
+ * The handover endpoint's ticket, which carries the transcript and `context` it gave. A
58
+ * provider on the same server starts from it in place of `openingMessage` and `context`.
59
+ */
60
+ ticket?: string;
61
+ /** What the window adds to `context`, over the handover endpoint's. */
62
+ addedContext?: Record<string, string>;
56
63
  /** A token from `resumeToken()`: reconnect to that chat instead of starting a new one. */
57
64
  resume?: string;
58
65
  };
package/dist/styles.css CHANGED
@@ -447,6 +447,15 @@ body:has(.vv-ai-chat:not(.vv-ai-chat--window)) {
447
447
  background: var(--vv-ai-color-accent);
448
448
  }
449
449
 
450
+ /* In place of the live chat button when no one can take the chat. */
451
+ .vv-ai-actions__note {
452
+ flex-basis: 100%;
453
+ margin: 0;
454
+ font-size: 0.875rem;
455
+ line-height: 1.5;
456
+ color: var(--vv-ai-color-text-muted);
457
+ }
458
+
450
459
  .vv-ai-chat__error {
451
460
  align-self: flex-start;
452
461
  padding: 0.75rem 1rem;
@@ -831,6 +840,10 @@ body:has(.vv-ai-chat:not(.vv-ai-chat--window)) {
831
840
  background: var(--vv-ai-chat-window-header);
832
841
  }
833
842
 
843
+ .vv-ai-chat__sheet-heading {
844
+ min-width: 0;
845
+ }
846
+
834
847
  .vv-ai-chat__sheet-title {
835
848
  min-width: 0;
836
849
  margin: 0;
@@ -843,6 +856,16 @@ body:has(.vv-ai-chat:not(.vv-ai-chat--window)) {
843
856
  text-overflow: ellipsis;
844
857
  }
845
858
 
859
+ .vv-ai-chat__sheet-host {
860
+ margin: 0.125rem 0 0;
861
+ font-size: 0.75rem;
862
+ line-height: 1.2;
863
+ opacity: 0.8;
864
+ white-space: nowrap;
865
+ overflow: hidden;
866
+ text-overflow: ellipsis;
867
+ }
868
+
846
869
  /* The close label is for screen readers; a cross shows it. */
847
870
  .vv-ai-chat__sheet-close {
848
871
  position: relative;
package/dist/survey.js CHANGED
@@ -306,7 +306,6 @@ function renderSurveyForm(document, fields, options) {
306
306
  else {
307
307
  input = createPart(document, "input", SURVEY_CLASS, "input");
308
308
  input.type = "checkbox";
309
- input.checked = value === true || value === "true";
310
309
  }
311
310
  input.id = id;
312
311
  input.name = field.name;
package/dist/window.js CHANGED
@@ -421,6 +421,7 @@ function renderActions(document, items) {
421
421
  //#region src/protocol.ts
422
422
  const AI_CHAT_PROTOCOL_VERSION = 1;
423
423
  const MAX_TURN_TOKEN_LENGTH = 1024;
424
+ const MAX_SIGNATURE_LENGTH = 1024;
424
425
  function isRecord(value) {
425
426
  return typeof value === "object" && value !== null && !Array.isArray(value);
426
427
  }
@@ -428,6 +429,10 @@ function stringValue(data, key) {
428
429
  const value = data[key];
429
430
  return typeof value === "string" ? value : null;
430
431
  }
432
+ function signatureEntry(data, key) {
433
+ const value = stringValue(data, key);
434
+ return value && value.length <= MAX_SIGNATURE_LENGTH ? { [key]: value } : {};
435
+ }
431
436
  function parseStreamEvent(name, data) {
432
437
  if (!isRecord(data)) return null;
433
438
  switch (name) {
@@ -460,7 +465,8 @@ function parseStreamEvent(name, data) {
460
465
  id,
461
466
  name: toolName,
462
467
  data: data.data,
463
- reply
468
+ reply,
469
+ ...signatureEntry(data, "replySignature")
464
470
  }
465
471
  };
466
472
  }
@@ -489,7 +495,10 @@ function parseStreamEvent(name, data) {
489
495
  const turn = stringValue(data, "turn");
490
496
  return {
491
497
  name,
492
- data: { turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null }
498
+ data: {
499
+ turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null,
500
+ ...signatureEntry(data, "signature")
501
+ }
493
502
  };
494
503
  }
495
504
  case "error": {
@@ -504,6 +513,7 @@ function parseStreamEvent(name, data) {
504
513
  }
505
514
  //#endregion
506
515
  //#region src/stream.ts
516
+ const MAX_RECORD_LENGTH = 1048576;
507
517
  function findRecordBoundary(buffer) {
508
518
  const lfIndex = buffer.indexOf("\n\n");
509
519
  const crlfIndex = buffer.indexOf("\r\n\r\n");
@@ -568,6 +578,7 @@ async function* readEventStream(response, signal) {
568
578
  }
569
579
  boundary = findRecordBoundary(buffer);
570
580
  }
581
+ if (buffer.length > MAX_RECORD_LENGTH) throw new Error("AI chat event stream sent an event that is too large");
571
582
  if (readerDone) throw new Error("AI chat event stream ended before a terminal event");
572
583
  }
573
584
  } finally {
@@ -589,6 +600,16 @@ function afterNextPaint() {
589
600
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
590
601
  });
591
602
  }
603
+ function signed(content, signature) {
604
+ return signature ? {
605
+ role: "assistant",
606
+ content,
607
+ signature
608
+ } : {
609
+ role: "assistant",
610
+ content
611
+ };
612
+ }
592
613
  function createChatSession(options) {
593
614
  const history = [];
594
615
  const context = {};
@@ -628,6 +649,7 @@ function createChatSession(options) {
628
649
  let error = null;
629
650
  let canceled = false;
630
651
  let answer = "";
652
+ let answerSignature = null;
631
653
  let replies = [];
632
654
  timeout = setTimeout(() => requestController.abort(new DOMException("AI chat request timed out", "TimeoutError")), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
633
655
  try {
@@ -647,18 +669,17 @@ function createChatSession(options) {
647
669
  for (const listener of listeners) listener(event);
648
670
  if (event.name === "tool") await afterNextPaint();
649
671
  if (event.name === "delta") answer += event.data.text;
650
- else if (event.name === "tool_result" && event.data.reply) replies.push(event.data.reply);
651
- else if (event.name === "done") turn = event.data.turn;
652
- else if (event.name === "error") throw new Error(event.data.message);
672
+ else if (event.name === "tool_result" && event.data.reply) replies.push(signed(event.data.reply, event.data.replySignature));
673
+ else if (event.name === "done") {
674
+ turn = event.data.turn;
675
+ answerSignature = event.data.signature ?? null;
676
+ } else if (event.name === "error") throw new Error(event.data.message);
653
677
  }
654
- if (answer.trim()) replies = [...replies, answer.trim()];
678
+ if (answer.trim()) replies = [...replies, signed(answer.trim(), answerSignature)];
655
679
  history.push({
656
680
  role: "user",
657
681
  content
658
- }, ...replies.map((reply) => ({
659
- role: "assistant",
660
- content: reply
661
- })));
682
+ }, ...replies);
662
683
  } catch (caught) {
663
684
  canceled = requestController.signal.aborted;
664
685
  error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat request failed");
@@ -741,20 +762,45 @@ const HANDOVER_TOOL = "request_human_agent";
741
762
  function isHandoverPayload(tool, data) {
742
763
  return isPlainObject(data) && (data.kind === "handover" || tool === "request_human_agent" && data.kind === void 0);
743
764
  }
765
+ function surveyAnswers(value) {
766
+ if (!isPlainObject(value)) return;
767
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" || typeof entry[1] === "boolean"));
768
+ }
744
769
  /**
745
770
  * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
746
- * a live chat is available, and a `contact` link to a safe contact URL. Null when neither applies.
771
+ * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
772
+ * goes on the button as its value. Null when neither applies.
747
773
  */
748
774
  function renderHandoverCard(document, data, labels) {
775
+ const prefill = surveyAnswers(data.prefill);
776
+ const value = prefill && Object.keys(prefill).length ? JSON.stringify(prefill) : null;
749
777
  return renderActions(document, [...data.liveChatAvailable === true ? [{
750
778
  label: labels.liveChat,
751
779
  action: LIVE_CHAT_ACTION,
780
+ value,
752
781
  primary: true
753
782
  }] : [], ...typeof data.contactUrl === "string" ? [{
754
783
  label: labels.contact,
755
784
  url: data.contactUrl
756
785
  }] : []]);
757
786
  }
787
+ /** The survey answers a live chat button carries, or undefined when it carries none. */
788
+ function buttonPrefill(button) {
789
+ const value = button.dataset.aiActionValue;
790
+ if (!value) return;
791
+ try {
792
+ return surveyAnswers(JSON.parse(value));
793
+ } catch {
794
+ return;
795
+ }
796
+ }
797
+ /**
798
+ * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
799
+ * no one can take the chat. The contact link stays.
800
+ */
801
+ function closeHandoverCard(parent, text) {
802
+ for (const button of parent.querySelectorAll(`[data-ai-action="${LIVE_CHAT_ACTION}"]`)) button.replaceWith(createPart(button.ownerDocument, "p", ACTIONS_CLASS, "note", text));
803
+ }
758
804
  //#endregion
759
805
  //#region src/registry.ts
760
806
  const entries = /* @__PURE__ */ new WeakMap();
@@ -787,10 +833,11 @@ function registryEntries(registry) {
787
833
  /** The `data-ai-action` of a button that opens its `data-ai-action-value` in a sheet. */
788
834
  const SHEET_ACTION = "sheet";
789
835
  const SHEET_CLASS = "vv-ai-chat";
836
+ const SHEET_SANDBOX = "allow-scripts allow-forms allow-popups allow-same-origin";
790
837
  /**
791
- * A page in a sheet over the chat: a dialog with a title, a close button and the page in a frame,
792
- * appended to `root`. Escape closes it too, and focus goes back to where it was. Null for a URL
793
- * a link could not open either.
838
+ * A page in a sheet over the chat: a dialog with a title, the page's host under it, a close
839
+ * button and the page in a sandboxed frame, appended to `root`. Escape closes it too, and focus
840
+ * goes back to where it was. Null for a URL a link could not open either.
794
841
  */
795
842
  function openSheet(root, options) {
796
843
  if (!isSafeLinkUrl(options.url)) return null;
@@ -803,13 +850,18 @@ function openSheet(root, options) {
803
850
  sheet.setAttribute("aria-modal", "true");
804
851
  sheet.setAttribute("aria-labelledby", titleId);
805
852
  const header = createPart(document, "div", SHEET_CLASS, "sheet-header");
853
+ const heading = createPart(document, "div", SHEET_CLASS, "sheet-heading");
806
854
  const title = createPart(document, "p", SHEET_CLASS, "sheet-title", options.title);
807
855
  title.id = titleId;
856
+ const url = new URL(options.url, document.baseURI);
857
+ heading.append(title);
858
+ if (url.origin !== document.location?.origin) heading.append(createPart(document, "p", SHEET_CLASS, "sheet-host", url.host));
808
859
  const close = createPart(document, "button", SHEET_CLASS, "sheet-close", options.closeLabel);
809
860
  close.type = "button";
810
- header.append(title, close);
861
+ header.append(heading, close);
811
862
  const frame = createPart(document, "iframe", SHEET_CLASS, "sheet-frame");
812
863
  frame.title = options.title;
864
+ frame.setAttribute("sandbox", SHEET_SANDBOX);
813
865
  frame.src = options.url;
814
866
  sheet.append(header, frame);
815
867
  let open = true;
@@ -931,10 +983,6 @@ function readLabels(root, labels) {
931
983
  for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
932
984
  return read;
933
985
  }
934
- function answers(value) {
935
- if (!isPlainObject(value)) return;
936
- return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" || typeof entry[1] === "boolean"));
937
- }
938
986
  function stringRecord(value) {
939
987
  if (!isPlainObject(value)) return {};
940
988
  return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
@@ -967,7 +1015,7 @@ function bindChat(root, options = {}) {
967
1015
  const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
968
1016
  const handoverEndpoint = options.handoverEndpoint ?? root.dataset.aiChatHandoverEndpoint;
969
1017
  const storageKey = options.storageKey ?? root.dataset.aiChatStorageKey;
970
- const handoverPrefill = options.handoverPrefill ?? answers(readJsonAttribute(root, "data-ai-chat-live-prefill", options.onError));
1018
+ const handoverPrefill = options.handoverPrefill ?? surveyAnswers(readJsonAttribute(root, "data-ai-chat-live-prefill", options.onError));
971
1019
  const liveChat = typeof options.liveChat === "function" ? options.liveChat({
972
1020
  root,
973
1021
  headers,
@@ -1114,7 +1162,16 @@ function bindChat(root, options = {}) {
1114
1162
  wrapper.append(content);
1115
1163
  parent.append(wrapper);
1116
1164
  options.onEmbedded?.(wrapper);
1117
- } else if (result.reply) appendMarkdown(parent, result.reply);
1165
+ return wrapper;
1166
+ }
1167
+ if (result.reply) appendMarkdown(parent, result.reply);
1168
+ return null;
1169
+ }
1170
+ function checkLiveChat(card) {
1171
+ if (!liveChat || !card.querySelector(`[data-ai-action="livechat"]`)) return;
1172
+ liveChat.availability().then((availability) => {
1173
+ if (!destroyed && availability.status === "closed") closeHandoverCard(card, labels.liveChatClosed);
1174
+ }, (caught) => options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat availability failed")));
1118
1175
  }
1119
1176
  const unsubscribe = session.subscribe((event) => {
1120
1177
  if (destroyed) return;
@@ -1141,7 +1198,8 @@ function bindChat(root, options = {}) {
1141
1198
  data: event.data.data,
1142
1199
  reply: event.data.reply
1143
1200
  };
1144
- renderResult(activeAssistant, result);
1201
+ const card = renderResult(activeAssistant, result);
1202
+ if (card && isHandoverPayload(result.name, result.data)) checkLiveChat(card);
1145
1203
  activeEntry?.parts.push({ result });
1146
1204
  activeEntryText = null;
1147
1205
  }
@@ -1483,7 +1541,8 @@ function bindChat(root, options = {}) {
1483
1541
  async function requestHandover() {
1484
1542
  if (!handoverEndpoint) return {
1485
1543
  transcript: null,
1486
- context: {}
1544
+ context: {},
1545
+ ticket: null
1487
1546
  };
1488
1547
  try {
1489
1548
  const response = await fetch(handoverEndpoint, {
@@ -1500,15 +1559,19 @@ function bindChat(root, options = {}) {
1500
1559
  });
1501
1560
  if (!response.ok) throw new Error(`AI chat handover request failed with ${response.status}`);
1502
1561
  const body = await response.json();
1562
+ const transcript = isPlainObject(body) && typeof body.transcript === "string" ? body.transcript.trim() : "";
1563
+ const ticket = isPlainObject(body) && typeof body.ticket === "string" && body.ticket ? body.ticket : null;
1503
1564
  return {
1504
- transcript: (isPlainObject(body) && typeof body.transcript === "string" ? body.transcript.trim() : "") || null,
1505
- context: stringRecord(isPlainObject(body) ? body.context : null)
1565
+ transcript: transcript || null,
1566
+ context: stringRecord(isPlainObject(body) ? body.context : null),
1567
+ ticket
1506
1568
  };
1507
1569
  } catch (caught) {
1508
1570
  options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover request failed"));
1509
1571
  return {
1510
1572
  transcript: null,
1511
- context: {}
1573
+ context: {},
1574
+ ticket: null
1512
1575
  };
1513
1576
  }
1514
1577
  }
@@ -1543,7 +1606,10 @@ function bindChat(root, options = {}) {
1543
1606
  intro: labels.surveyIntro,
1544
1607
  prefilled: labels.surveyPrefilled
1545
1608
  },
1546
- prefill: handover.prefill ?? handoverPrefill
1609
+ prefill: {
1610
+ ...handoverPrefill,
1611
+ ...handover.prefill
1612
+ }
1547
1613
  });
1548
1614
  pendingSurvey = survey;
1549
1615
  const wrapper = root.ownerDocument.createElement("div");
@@ -1572,7 +1638,9 @@ function bindChat(root, options = {}) {
1572
1638
  ...server.context,
1573
1639
  ...handover.context
1574
1640
  },
1575
- openingMessage: server.transcript ?? void 0
1641
+ openingMessage: server.transcript ?? void 0,
1642
+ ticket: server.ticket ?? void 0,
1643
+ addedContext: { ...handover.context }
1576
1644
  });
1577
1645
  if (stale()) {
1578
1646
  await provider.end();
@@ -1745,7 +1813,7 @@ function bindChat(root, options = {}) {
1745
1813
  }
1746
1814
  const actionElement = target?.closest("[data-ai-action]");
1747
1815
  const action = actionElement ? registryEntries(options.registry)?.actions.get(actionElement.dataset.aiAction ?? "") : void 0;
1748
- if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover().catch(report);
1816
+ if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover({ prefill: buttonPrefill(actionElement) }).catch(report);
1749
1817
  else if (!action && actionElement?.dataset.aiAction === "sheet") showSheet(actionElement.dataset.aiActionValue ?? "", actionElement.textContent?.trim() ?? "");
1750
1818
  else if (action && actionElement) Promise.resolve(action({
1751
1819
  root,
@@ -2019,4 +2087,4 @@ function bindLauncherTeaser(binding, container, options = {}) {
2019
2087
  };
2020
2088
  }
2021
2089
  //#endregion
2022
- export { assertAnswerCardContract as A, MAX_ANSWER_CARD_TABLE_CELLS as C, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS as D, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS as E, renderAnswerCard as M, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS as O, MAX_ANSWER_CARD_TABLES as S, MAX_ANSWER_CARD_TEXT_LENGTH as T, renderCardList as _, createAiChatRegistry as a, MAX_ANSWER_CARD_LINKS as b, isHandoverPayload as c, readEventStream as d, AI_CHAT_PROTOCOL_VERSION as f, renderActions as g, CARD_LIST_CLASS as h, bindChat as i, isAnswerCard as j, MAX_ANSWER_CARD_URL_LENGTH as k, renderHandoverCard as l, ACTIONS_CLASS as m, bindLauncherTeaser as n, HANDOVER_TOOL as o, parseStreamEvent as p, CHAT_CLASS as r, LIVE_CHAT_ACTION as s, bindChatWindow as t, createChatSession as u, ANSWER_CARD_CLASS as v, MAX_ANSWER_CARD_TABLE_ROWS as w, MAX_ANSWER_CARD_SECTIONS as x, MAX_ANSWER_CARD_FACTS as y };
2090
+ export { MAX_ANSWER_CARD_URL_LENGTH as A, MAX_ANSWER_CARD_TABLES as C, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS as D, MAX_ANSWER_CARD_TEXT_LENGTH as E, isAnswerCard as M, renderAnswerCard as N, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS as O, MAX_ANSWER_CARD_SECTIONS as S, MAX_ANSWER_CARD_TABLE_ROWS as T, renderActions as _, createAiChatRegistry as a, MAX_ANSWER_CARD_FACTS as b, closeHandoverCard as c, createChatSession as d, readEventStream as f, CARD_LIST_CLASS as g, ACTIONS_CLASS as h, bindChat as i, assertAnswerCardContract as j, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS as k, isHandoverPayload as l, parseStreamEvent as m, bindLauncherTeaser as n, HANDOVER_TOOL as o, AI_CHAT_PROTOCOL_VERSION as p, CHAT_CLASS as r, LIVE_CHAT_ACTION as s, bindChatWindow as t, renderHandoverCard as u, renderCardList as v, MAX_ANSWER_CARD_TABLE_CELLS as w, MAX_ANSWER_CARD_LINKS as x, ANSWER_CARD_CLASS as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.10.0",
3
+ "version": "0.13.0",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",