@vettvangur/ai-sdk 0.11.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,12 +126,17 @@ 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
142
  option, or the `data-ai-chat-live-prefill` attribute as a JSON object of answers, with `prefill`
@@ -163,7 +168,9 @@ the buttons a message carries (`actions`) in its `__text` bubble (or in the mess
163
168
  no text) in `renderActions` markup, the first primary. A
164
169
  link button opens in a new tab. A `sheet` button opens its page in a `__sheet` dialog appended to
165
170
  the root: a `__sheet-header` with a `__sheet-title` (the button's text) and a `__sheet-close`
166
- 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
167
174
  focus goes back to the button. A provider with `connectSheet(frame, { send, close })` connects the
168
175
  page to its own app protocol, so the page can send the visitor's message and close the sheet. The
169
176
  provider's own messages are `__notice--system`. While live the input shows its
@@ -227,7 +234,10 @@ section. `endpoint` is the prefix the site maps with `MapAiChat`, and `headers`
227
234
  request, so pass the antiforgery header the chat sends. It reports `no-agents` while nobody has the
228
235
  Live view open, and its resume token is the visitor's chat token. Given `survey` fields, it asks
229
236
  them before the chat starts and sends the answers to the agent by field name, a choice by its label
230
- 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.
231
241
 
232
242
  ```ts
233
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';
@@ -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
@@ -840,6 +840,10 @@ body:has(.vv-ai-chat:not(.vv-ai-chat--window)) {
840
840
  background: var(--vv-ai-chat-window-header);
841
841
  }
842
842
 
843
+ .vv-ai-chat__sheet-heading {
844
+ min-width: 0;
845
+ }
846
+
843
847
  .vv-ai-chat__sheet-title {
844
848
  min-width: 0;
845
849
  margin: 0;
@@ -852,6 +856,16 @@ body:has(.vv-ai-chat:not(.vv-ai-chat--window)) {
852
856
  text-overflow: ellipsis;
853
857
  }
854
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
+
855
869
  /* The close label is for screen readers; a cross shows it. */
856
870
  .vv-ai-chat__sheet-close {
857
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");
@@ -812,10 +833,11 @@ function registryEntries(registry) {
812
833
  /** The `data-ai-action` of a button that opens its `data-ai-action-value` in a sheet. */
813
834
  const SHEET_ACTION = "sheet";
814
835
  const SHEET_CLASS = "vv-ai-chat";
836
+ const SHEET_SANDBOX = "allow-scripts allow-forms allow-popups allow-same-origin";
815
837
  /**
816
- * A page in a sheet over the chat: a dialog with a title, a close button and the page in a frame,
817
- * appended to `root`. Escape closes it too, and focus goes back to where it was. Null for a URL
818
- * 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.
819
841
  */
820
842
  function openSheet(root, options) {
821
843
  if (!isSafeLinkUrl(options.url)) return null;
@@ -828,13 +850,18 @@ function openSheet(root, options) {
828
850
  sheet.setAttribute("aria-modal", "true");
829
851
  sheet.setAttribute("aria-labelledby", titleId);
830
852
  const header = createPart(document, "div", SHEET_CLASS, "sheet-header");
853
+ const heading = createPart(document, "div", SHEET_CLASS, "sheet-heading");
831
854
  const title = createPart(document, "p", SHEET_CLASS, "sheet-title", options.title);
832
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));
833
859
  const close = createPart(document, "button", SHEET_CLASS, "sheet-close", options.closeLabel);
834
860
  close.type = "button";
835
- header.append(title, close);
861
+ header.append(heading, close);
836
862
  const frame = createPart(document, "iframe", SHEET_CLASS, "sheet-frame");
837
863
  frame.title = options.title;
864
+ frame.setAttribute("sandbox", SHEET_SANDBOX);
838
865
  frame.src = options.url;
839
866
  sheet.append(header, frame);
840
867
  let open = true;
@@ -1514,7 +1541,8 @@ function bindChat(root, options = {}) {
1514
1541
  async function requestHandover() {
1515
1542
  if (!handoverEndpoint) return {
1516
1543
  transcript: null,
1517
- context: {}
1544
+ context: {},
1545
+ ticket: null
1518
1546
  };
1519
1547
  try {
1520
1548
  const response = await fetch(handoverEndpoint, {
@@ -1531,15 +1559,19 @@ function bindChat(root, options = {}) {
1531
1559
  });
1532
1560
  if (!response.ok) throw new Error(`AI chat handover request failed with ${response.status}`);
1533
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;
1534
1564
  return {
1535
- transcript: (isPlainObject(body) && typeof body.transcript === "string" ? body.transcript.trim() : "") || null,
1536
- context: stringRecord(isPlainObject(body) ? body.context : null)
1565
+ transcript: transcript || null,
1566
+ context: stringRecord(isPlainObject(body) ? body.context : null),
1567
+ ticket
1537
1568
  };
1538
1569
  } catch (caught) {
1539
1570
  options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover request failed"));
1540
1571
  return {
1541
1572
  transcript: null,
1542
- context: {}
1573
+ context: {},
1574
+ ticket: null
1543
1575
  };
1544
1576
  }
1545
1577
  }
@@ -1606,7 +1638,9 @@ function bindChat(root, options = {}) {
1606
1638
  ...server.context,
1607
1639
  ...handover.context
1608
1640
  },
1609
- openingMessage: server.transcript ?? void 0
1641
+ openingMessage: server.transcript ?? void 0,
1642
+ ticket: server.ticket ?? void 0,
1643
+ addedContext: { ...handover.context }
1610
1644
  });
1611
1645
  if (stale()) {
1612
1646
  await provider.end();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.11.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",