@vettvangur/ai-sdk 0.14.0 → 0.16.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
@@ -1,11 +1,16 @@
1
1
  # @vettvangur/ai-sdk
2
2
 
3
- Framework-agnostic AI chat primitives for server-rendered shells.
3
+ Framework-agnostic AI primitives for server-rendered pages, and an AI chat built on them.
4
4
 
5
- It exports protocol-v1 contracts, parsing and SSE stream-reading primitives, a headless chat session,
6
- a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool results with. It
7
- ships no styles by default: every element it renders carries a BEM class. An opt-in stylesheet lays
8
- out and draws the chat, its window and launcher, themed by custom properties (see [Styles](#styles)).
5
+ The package root is the core: reading a streamed response, rendering model text as safe DOM, and the
6
+ link and image rules every renderer keeps (see [The core](#the-core)). It knows nothing of chat, so a
7
+ page that streams a generated product text or a classification uses it alone.
8
+
9
+ `@vettvangur/ai-sdk/chat` is the chat: protocol-v1 contracts, parsing and stream reading, a headless
10
+ chat session, a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool
11
+ results with. It ships no styles by default: every element it renders carries a BEM class. An opt-in
12
+ stylesheet lays out and draws the chat, its window and launcher, themed by custom properties (see
13
+ [Styles](#styles)).
9
14
 
10
15
  ```html
11
16
  <section data-ai-chat data-ai-chat-endpoint="/webapi/aichat/stream"
@@ -24,7 +29,7 @@ out and draws the chat, its window and launcher, themed by custom properties (se
24
29
  ```
25
30
 
26
31
  ```ts
27
- import { bindChat, createAiChatRegistry } from '@vettvangur/ai-sdk'
32
+ import { bindChat, createAiChatRegistry } from '@vettvangur/ai-sdk/chat'
28
33
 
29
34
  const registry = createAiChatRegistry()
30
35
  registry.registerRenderer('weather', ({ document, data }) => {
@@ -37,6 +42,39 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
37
42
  // Call chat.destroy() when its server-rendered shell is removed.
38
43
  ```
39
44
 
45
+ ## The core
46
+
47
+ `readServerEvents(response, signal)` yields each record of a server-sent event stream as
48
+ `{ name, data }`, with `data` as the text of its `data:` lines. It knows no protocol: a record
49
+ without an `event:` name or `data:` line is skipped, the stream ends with the response, and breaking
50
+ out of the loop or aborting `signal` cancels the response body. A record that grows past 1 MiB
51
+ without closing throws.
52
+
53
+ ```ts
54
+ import { readServerEvents, renderMarkdown } from '@vettvangur/ai-sdk'
55
+
56
+ const controller = new AbortController()
57
+ const response = await fetch('/webapi/products/describe', { method: 'POST', body: form, signal: controller.signal })
58
+ let text = ''
59
+ for await (const { name, data } of readServerEvents(response, controller.signal)) {
60
+ if (name === 'delta') {
61
+ text += JSON.parse(data).text
62
+ output.replaceChildren(renderMarkdown(document, text))
63
+ }
64
+ }
65
+ ```
66
+
67
+ `renderMarkdown(document, source)` draws the Markdown subset a model writes as DOM nodes, never as
68
+ HTML, and keeps to `MAX_MARKDOWN_CHARACTERS`. `isSafeLinkUrl`, `createSafeLink`, `createSafeImage`
69
+ and `createPart` are described under [Cards](#cards).
70
+
71
+ ### Upgrading from 0.14
72
+
73
+ Everything the package root exported except `createPart`, `createSafeImage`, `createSafeLink` and
74
+ `isSafeLinkUrl` moved to `@vettvangur/ai-sdk/chat`: import `bindChat`, `createAiChatRegistry`,
75
+ `createChatSession`, `readEventStream`, `renderAnswerCard` and the `AiChat*` types from there. The
76
+ `live-chat`, `mount`, `binmx` and `styles.css` subpaths are unchanged.
77
+
40
78
  ## The shell
41
79
 
42
80
  `bindChat` needs the form, input and thread; the rest is optional.
@@ -62,12 +100,20 @@ working inside the thread, so a phone's keyboard does not cover the answer.
62
100
 
63
101
  A `suggestions` event lists questions to ask next. They are drawn under the finished answer as
64
102
  `__follow-up` buttons in a `__follow-ups` group labelled `follow-ups`, ask themselves when clicked,
65
- and are removed when the next question is asked.
103
+ and are removed when the next question is asked. A question the server gave an `action`
104
+ (Vettvangur.AiChat 3.1 and later) keeps it in `data-ai-chat-follow-up-action` and sends it as the
105
+ request's `followUpAction`, so the server runs the call it stands for instead of matching the words.
106
+ `session.send(question, { followUpAction })` does the same outside the binding.
107
+
108
+ Each finished answer is read out once through a `__announcer` element the binding adds to the root
109
+ (`role="status"`, `aria-live="polite"`), with the same text the copy button copies, so a screen
110
+ reader hears the answer without the thread announcing every streamed word. It is for screen readers
111
+ only: hide it visually as `styles.css` does, or the host's stylesheet must.
66
112
 
67
113
  Elements it adds carry classes under `CHAT_CLASS` (`vv-ai-chat`): `__message` with `--user` or
68
114
  `--assistant`, `__text`, `__tool` with `--done` and `--failed`, `__tool-dot`, `__tool-label`,
69
115
  `__tool-status`, `__result` around a rendered tool result, `__reply-actions`, `__follow-ups`,
70
- `__follow-up` and `__error`.
116
+ `__follow-up`, `__announcer` and `__error`.
71
117
 
72
118
  `binding.setFormContext(name, summary, followUp)` sends what a visitor entered into an embedded form
73
119
  with every later question. An unchanged summary is not sent again, and `followUp` is added as an
@@ -200,7 +246,7 @@ hours from the widget's config and turns the Adaptive Card survey into text, cho
200
246
  fields, refusing a card with any other input rather than leaving a question out.
201
247
 
202
248
  ```ts
203
- import { bindChat } from '@vettvangur/ai-sdk'
249
+ import { bindChat } from '@vettvangur/ai-sdk/chat'
204
250
  import { createOmnichannelProvider } from '@vettvangur/ai-sdk/live-chat/omnichannel'
205
251
 
206
252
  const liveChat = createOmnichannelProvider({ orgId, orgUrl, widgetId })
@@ -275,7 +321,7 @@ answers through `liveChatFromAttributes` unless they name a `liveChat`:
275
321
  | `data-ai-chat-live-endpoint` | The AiChat Live desk, as `liveChatFromRoot` |
276
322
 
277
323
  ```ts
278
- import { createAiChatRegistry } from '@vettvangur/ai-sdk'
324
+ import { createAiChatRegistry } from '@vettvangur/ai-sdk/chat'
279
325
  import { mountAiChat } from '@vettvangur/ai-sdk/mount'
280
326
 
281
327
  const registry = createAiChatRegistry()
@@ -332,7 +378,7 @@ project; build them with the helpers below rather than adding them here.
332
378
 
333
379
  `createSafeImage` (web and site-relative URLs only, with srcset and size when given),
334
380
  `createSafeLink` (the `isSafeLinkUrl` rule, new tab for web URLs) and `createPart` (an element with
335
- a BEM class and text) are exported for a host's own renderers.
381
+ a BEM class and text) are exported from the package root for a host's own renderers.
336
382
 
337
383
  ## Answer cards
338
384
 
@@ -381,6 +427,11 @@ Every `vv-ai-chat__` class above is under the root. The page pins the root betwe
381
427
  corner from `36rem` up and fills the screen below it. The thread is the `vv-ai-chat-thread`
382
428
  container, so a host's cards can lay out by its width with `@container vv-ai-chat-thread`.
383
429
 
430
+ In the window, buttons and fields in the thread keep to the window's control size, whatever the host
431
+ draws them at elsewhere. That covers the package's own, `.button`, `.btn` and `.bttn` and any class
432
+ starting `button-`, `btn-` or `bttn-`, every `input` but checkboxes, radios, ranges, hidden and file
433
+ inputs, `select` and `textarea`. The composer is not in the thread and keeps its own.
434
+
384
435
  The theme's custom properties, set on the root or any ancestor of the chat and the launcher:
385
436
 
386
437
  | Property | Default |
@@ -399,6 +450,7 @@ The theme's custom properties, set on the root or any ancestor of the chat and t
399
450
  | `--vv-ai-chat-window-width`, `-height`, `-inset`, `-radius`, `-shadow` | `23.75rem`, `38.75rem`, `1.25rem`, `1rem`, a soft drop |
400
451
  | `--vv-ai-chat-window-header`, `-header-agent`, `-header-text`, `-header-muted`, `-header-hover` | the accent, its hover, on-accent, the header text at 85% and 15% |
401
452
  | `--vv-ai-chat-assistant-avatar` (an image in the window's assistant avatar) | `none` |
453
+ | `--vv-ai-chat-window-control-height`, `-control-font-size` (buttons and fields in the window's thread) | `2.25rem`, `0.875rem` |
402
454
  | `--vv-ai-launcher-shadow`, `--vv-ai-launcher-teaser-shadow`, `--vv-ai-menu-shadow` | soft drops |
403
455
  | `--vv-ai-chat-spring`, `--vv-ai-launcher-spring`, `--vv-ai-launcher-wind-up` | the window's and launcher's easings |
404
456
  | `--vv-ai-chat-window-delay` (the window opens once the launcher has mostly spun away) | `0.35s` |
package/dist/binmx.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { P as AiTemplateUrlSurfaceOptions, m as AiChatExtensionContext } from "./contracts.js";
1
+ import { F as AiTemplateUrlSurfaceOptions, p as AiChatExtensionContext } from "./contracts.js";
2
2
  //#region src/binmx.d.ts
3
3
  /**
4
4
  * Makes cloned markup live. binmx processes only the page it started on and what it swaps in
package/dist/chat.d.ts ADDED
@@ -0,0 +1,132 @@
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
+ import { t as AiCardImage } from "./dom.js";
3
+ import { A as AiFormContextOptions, C as AiChatSendOptions, D as AiChatSessionStatus, E as AiChatSessionResult, F as AiTemplateUrlSurfaceOptions, M as AiLauncherTeaserOptions, N as AiLiveChatFactoryContext, O as AiChatStreamEvent, P as AiTemplateItemSurfaceOptions, S as AiChatRequest, T as AiChatSessionOptions, _ as AiChatLabels, a as AiAnswerCardSection, b as AiChatRegistry, c as AiChatActionItem, d as AiChatContext, f as AiChatEventMap, g as AiChatHandoverResult, h as AiChatHandoverOptions, i as AiAnswerCardLink, j as AiHandoverPayload, k as AiChatSurface, l as AiChatBinding, m as AiChatFollowUp, n as AiAnswerCardFact, o as AiAnswerCardTable, p as AiChatExtensionContext, r as AiAnswerCardLabels, s as AiChatAction, t as AiAnswerCard, u as AiChatBindings, v as AiChatMessage, w as AiChatSession, x as AiChatRenderer, y as AiChatMode } from "./contracts.js";
4
+ //#region src/answer-card.d.ts
5
+ declare const MAX_ANSWER_CARD_SECTIONS = 12;
6
+ declare const MAX_ANSWER_CARD_FACTS = 24;
7
+ declare const MAX_ANSWER_CARD_LINKS = 24;
8
+ declare const MAX_ANSWER_CARD_TABLES = 8;
9
+ declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
10
+ declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
11
+ declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
12
+ declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
13
+ declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
14
+ declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
15
+ declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
16
+ /**
17
+ * Every element an answer card renders carries a class under this block, so a host styles the card
18
+ * by class rather than by the order its elements happen to come in.
19
+ */
20
+ declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
21
+ /**
22
+ * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
23
+ * server or a test, can hold its output to the same limits the renderer applies.
24
+ */
25
+ declare function isAnswerCard(value: unknown): value is AiAnswerCard;
26
+ declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
27
+ /**
28
+ * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
29
+ * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
30
+ * a server's or a test's own cards; the message names what is wrong.
31
+ */
32
+ declare function assertAnswerCardContract(card: unknown): asserts card is AiAnswerCard;
33
+ //#endregion
34
+ //#region src/bind.d.ts
35
+ /**
36
+ * Every element the binding adds to the thread carries a class under this block, so a host styles
37
+ * the chat by class rather than by the order its elements happen to come in.
38
+ */
39
+ declare const CHAT_CLASS = "vv-ai-chat";
40
+ declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
41
+ //#endregion
42
+ //#region src/cards.d.ts
43
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
44
+ declare const CARD_LIST_CLASS = "vv-ai-card-list";
45
+ declare const ACTIONS_CLASS = "vv-ai-actions";
46
+ /**
47
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
48
+ * Items that render nothing are skipped, and a list with nothing in it is null.
49
+ */
50
+ declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
51
+ /**
52
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
53
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
54
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
55
+ */
56
+ declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
57
+ //#endregion
58
+ //#region src/chat.d.ts
59
+ declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
60
+ //#endregion
61
+ //#region src/form-context.d.ts
62
+ /**
63
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
64
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
65
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
66
+ * something the visitor said. Returns a function that stops watching.
67
+ */
68
+ declare function watchFormContext(binding: AiChatBinding, element: HTMLElement, options: AiFormContextOptions): () => void;
69
+ //#endregion
70
+ //#region src/handover.d.ts
71
+ /** The action the handover card's button runs; the binding hands over to a person with it. */
72
+ declare const LIVE_CHAT_ACTION = "livechat";
73
+ /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
74
+ declare const HANDOVER_TOOL = "request_human_agent";
75
+ /** A payload of kind `handover`, or one from the handover tool that names no kind. */
76
+ declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
77
+ /**
78
+ * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
79
+ * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
80
+ * goes on the button as its value. Null when neither applies.
81
+ */
82
+ declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
83
+ /**
84
+ * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
85
+ * no one can take the chat. The contact link stays.
86
+ */
87
+ declare function closeHandoverCard(parent: ParentNode, text: string): void;
88
+ //#endregion
89
+ //#region src/protocol.d.ts
90
+ declare const AI_CHAT_PROTOCOL_VERSION = 1;
91
+ declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
92
+ //#endregion
93
+ //#region src/registry.d.ts
94
+ declare function createAiChatRegistry(): AiChatRegistry;
95
+ //#endregion
96
+ //#region src/stream.d.ts
97
+ declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
98
+ //#endregion
99
+ //#region src/surfaces.d.ts
100
+ /**
101
+ * A surface that shows one item out of an authored list template. The template is cloned, every
102
+ * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
103
+ * rest of the template stays as authored, so one item is the same markup the whole list shows.
104
+ * Null when the template is missing or no item matches.
105
+ */
106
+ declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
107
+ /**
108
+ * A surface of which only the latest copy stays in the thread, for an embedded component whose
109
+ * script binds to the first match in the document or whose fields share ids. What it draws is
110
+ * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
111
+ */
112
+ declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
113
+ //#endregion
114
+ //#region src/window.d.ts
115
+ /**
116
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
117
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
118
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
119
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
120
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
121
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
122
+ */
123
+ declare function bindChatWindow(binding: AiChatBinding): () => void;
124
+ /**
125
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
126
+ * started a chat: not while the window is open or its thread has messages. A
127
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
128
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
129
+ */
130
+ declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
131
+ //#endregion
132
+ 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 AiChatFollowUp, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSendOptions, 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, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
package/dist/chat.js ADDED
@@ -0,0 +1,33 @@
1
+ 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";
2
+ import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
3
+ //#region src/form-context.ts
4
+ /**
5
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
6
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
7
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
8
+ * something the visitor said. Returns a function that stops watching.
9
+ */
10
+ function watchFormContext(binding, element, options) {
11
+ const record = () => {
12
+ const form = element.querySelector(options.form);
13
+ if (!form) return;
14
+ const values = new FormData(form);
15
+ const parts = options.fields.map(([field, label]) => {
16
+ const raw = String(values.get(field) ?? "").trim();
17
+ const value = options.values?.[raw] ?? raw;
18
+ return value ? `${label}: ${value}` : "";
19
+ }).filter(Boolean);
20
+ if (!parts.length) return;
21
+ const note = options.note ? ` ${options.note}` : "";
22
+ binding.setFormContext(options.name, `Context, not a message from the visitor: they filled in ${options.title} with ${parts.join(", ")}.${note}`, options.followUp);
23
+ };
24
+ const observer = new MutationObserver(record);
25
+ observer.observe(element, {
26
+ childList: true,
27
+ subtree: true
28
+ });
29
+ record();
30
+ return () => observer.disconnect();
31
+ }
32
+ //#endregion
33
+ 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, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
@@ -10,6 +10,19 @@ type AiChatRequest = {
10
10
  messages: AiChatMessage[];
11
11
  provider?: string;
12
12
  context?: Record<string, string>;
13
+ /** The action of the follow-up the visitor picked, sent with the question it was offered with. */
14
+ followUpAction?: string;
15
+ };
16
+ /**
17
+ * A question the server suggests asking next. `action` is what picking it sends back, so the
18
+ * server runs the call it stands for; it is null for a question the model answers.
19
+ */
20
+ type AiChatFollowUp = {
21
+ text: string;
22
+ action: string | null;
23
+ };
24
+ type AiChatSendOptions = {
25
+ followUpAction?: string | null;
13
26
  };
14
27
  type AiChatContext = Record<string, string>;
15
28
  type AiChatSessionStatus = 'idle' | 'sending' | 'disposed';
@@ -30,7 +43,7 @@ type AiChatSession = {
30
43
  readonly history: readonly AiChatMessage[];
31
44
  readonly context: Readonly<AiChatContext>;
32
45
  readonly status: AiChatSessionStatus;
33
- send(message: string): Promise<AiChatSessionResult>;
46
+ send(message: string, options?: AiChatSendOptions): Promise<AiChatSessionResult>;
34
47
  cancel(): void;
35
48
  reset(): void;
36
49
  setContext(name: string, value: string): void;
@@ -113,6 +126,7 @@ type AiChatStreamEvent = {
113
126
  name: 'suggestions';
114
127
  data: {
115
128
  suggestions: string[];
129
+ followUps: AiChatFollowUp[];
116
130
  };
117
131
  } | {
118
132
  name: 'done';
@@ -280,13 +294,6 @@ type AiChatBinding = {
280
294
  on<K extends keyof AiChatEventMap>(name: K, listener: (detail: AiChatEventMap[K]) => void): () => void;
281
295
  destroy(): void;
282
296
  };
283
- type AiCardImage = {
284
- url: string;
285
- url2x?: string | null;
286
- alt?: string | null;
287
- width?: number | null;
288
- height?: number | null;
289
- };
290
297
  type AiChatActionItem = {
291
298
  label: string;
292
299
  action?: string | null;
@@ -342,4 +349,4 @@ type AiLauncherTeaserOptions = {
342
349
  storageKey?: string;
343
350
  };
344
351
  //#endregion
345
- export { AiHandoverPayload as A, AiChatSession as C, AiChatStreamEvent as D, AiChatSessionStatus as E, AiLiveChatFactoryContext as M, AiTemplateItemSurfaceOptions as N, AiChatSurface as O, AiTemplateUrlSurfaceOptions as P, AiChatRequest as S, AiChatSessionResult as T, AiChatLabels as _, AiAnswerCardSection as a, AiChatRegistry as b, AiChatAction as c, AiChatBindings as d, AiChatContext as f, AiChatHandoverResult as g, AiChatHandoverOptions as h, AiAnswerCardLink as i, AiLauncherTeaserOptions as j, AiFormContextOptions as k, AiChatActionItem as l, AiChatExtensionContext as m, AiAnswerCardFact as n, AiAnswerCardTable as o, AiChatEventMap as p, AiAnswerCardLabels as r, AiCardImage as s, AiAnswerCard as t, AiChatBinding as u, AiChatMessage as v, AiChatSessionOptions as w, AiChatRenderer as x, AiChatMode as y };
352
+ export { AiFormContextOptions as A, AiChatSendOptions as C, AiChatSessionStatus as D, AiChatSessionResult as E, AiTemplateUrlSurfaceOptions as F, AiLauncherTeaserOptions as M, AiLiveChatFactoryContext as N, AiChatStreamEvent as O, AiTemplateItemSurfaceOptions as P, AiChatRequest as S, AiChatSessionOptions as T, AiChatLabels as _, AiAnswerCardSection as a, AiChatRegistry as b, AiChatActionItem as c, AiChatContext as d, AiChatEventMap as f, AiChatHandoverResult as g, AiChatHandoverOptions as h, AiAnswerCardLink as i, AiHandoverPayload as j, AiChatSurface as k, AiChatBinding as l, AiChatFollowUp as m, AiAnswerCardFact as n, AiAnswerCardTable as o, AiChatExtensionContext as p, AiAnswerCardLabels as r, AiChatAction as s, AiAnswerCard as t, AiChatBindings as u, AiChatMessage as v, AiChatSession as w, AiChatRenderer as x, AiChatMode as y };
package/dist/dom.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ //#region src/dom.d.ts
2
+ /** An image a card or answer may show. */
3
+ type AiCardImage = {
4
+ url: string;
5
+ url2x?: string | null;
6
+ alt?: string | null;
7
+ width?: number | null;
8
+ height?: number | null;
9
+ };
10
+ declare function isSafeLinkUrl(url: string): boolean;
11
+ declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
12
+ /**
13
+ * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
14
+ * width and height, when given, let the browser reserve the space before the image arrives.
15
+ */
16
+ declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
17
+ /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
18
+ declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
19
+ //#endregion
20
+ export { isSafeLinkUrl as a, createSafeLink as i, createPart as n, createSafeImage as r, AiCardImage as t };
package/dist/events.js ADDED
@@ -0,0 +1,76 @@
1
+ //#region src/events.ts
2
+ const MAX_RECORD_LENGTH = 1048576;
3
+ function findRecordBoundary(buffer) {
4
+ const lfIndex = buffer.indexOf("\n\n");
5
+ const crlfIndex = buffer.indexOf("\r\n\r\n");
6
+ if (lfIndex === -1 && crlfIndex === -1) return null;
7
+ if (lfIndex === -1 || crlfIndex !== -1 && crlfIndex < lfIndex) return {
8
+ index: crlfIndex,
9
+ length: 4
10
+ };
11
+ return {
12
+ index: lfIndex,
13
+ length: 2
14
+ };
15
+ }
16
+ function fieldValue(value) {
17
+ return value.startsWith(" ") ? value.slice(1) : value;
18
+ }
19
+ function parseRecord(record) {
20
+ let name;
21
+ const dataLines = [];
22
+ for (const line of record.split(/\r?\n/)) if (line.startsWith("event:")) name = fieldValue(line.slice(6));
23
+ else if (line.startsWith("data:")) dataLines.push(fieldValue(line.slice(5)));
24
+ if (!name || dataLines.length === 0) return null;
25
+ return {
26
+ name,
27
+ data: dataLines.join("\n")
28
+ };
29
+ }
30
+ function abortError() {
31
+ return /* @__PURE__ */ new Error("AI event stream was aborted");
32
+ }
33
+ /**
34
+ * The named records of a streamed response, as they arrive. A record without an `event:` name or
35
+ * `data:` line is skipped. The stream ends with the response; stopping early, by breaking out of
36
+ * the loop or aborting `signal`, cancels the response body.
37
+ */
38
+ async function* readServerEvents(response, signal) {
39
+ if (!response.body) throw new Error("AI response has no body");
40
+ if (signal.aborted) throw abortError();
41
+ const decoder = new TextDecoder();
42
+ const reader = response.body.getReader();
43
+ let buffer = "";
44
+ let readerDone = false;
45
+ const cancelReader = () => {
46
+ reader.cancel().catch(() => void 0);
47
+ };
48
+ signal.addEventListener("abort", cancelReader, { once: true });
49
+ try {
50
+ while (!readerDone) {
51
+ if (signal.aborted) throw abortError();
52
+ const { done, value } = await reader.read();
53
+ if (signal.aborted) throw abortError();
54
+ if (done) {
55
+ readerDone = true;
56
+ buffer += decoder.decode();
57
+ } else buffer += decoder.decode(value, { stream: true });
58
+ let boundary = findRecordBoundary(buffer);
59
+ while (boundary) {
60
+ const record = parseRecord(buffer.slice(0, boundary.index));
61
+ buffer = buffer.slice(boundary.index + boundary.length);
62
+ if (record) yield record;
63
+ boundary = findRecordBoundary(buffer);
64
+ }
65
+ if (buffer.length > MAX_RECORD_LENGTH) throw new Error("AI event stream sent an event that is too large");
66
+ }
67
+ } finally {
68
+ signal.removeEventListener("abort", cancelReader);
69
+ if (!readerDone) try {
70
+ await reader.cancel();
71
+ } catch {}
72
+ reader.releaseLock();
73
+ }
74
+ }
75
+ //#endregion
76
+ export { readServerEvents as t };
package/dist/index.d.ts CHANGED
@@ -1,142 +1,19 @@
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
- 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
- //#region src/answer-card.d.ts
4
- declare const MAX_ANSWER_CARD_SECTIONS = 12;
5
- declare const MAX_ANSWER_CARD_FACTS = 24;
6
- declare const MAX_ANSWER_CARD_LINKS = 24;
7
- declare const MAX_ANSWER_CARD_TABLES = 8;
8
- declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
9
- declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
10
- declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
11
- declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
12
- declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
13
- declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
14
- declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
1
+ import { a as isSafeLinkUrl, i as createSafeLink, n as createPart, r as createSafeImage, t as AiCardImage } from "./dom.js";
2
+ //#region src/events.d.ts
3
+ /** One record of a server-sent event stream: its `event:` name and its `data:` lines joined. */
4
+ type AiServerEvent = {
5
+ name: string;
6
+ data: string;
7
+ };
15
8
  /**
16
- * Every element an answer card renders carries a class under this block, so a host styles the card
17
- * by class rather than by the order its elements happen to come in.
9
+ * The named records of a streamed response, as they arrive. A record without an `event:` name or
10
+ * `data:` line is skipped. The stream ends with the response; stopping early, by breaking out of
11
+ * the loop or aborting `signal`, cancels the response body.
18
12
  */
19
- declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
20
- /**
21
- * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
22
- * server or a test, can hold its output to the same limits the renderer applies.
23
- */
24
- declare function isAnswerCard(value: unknown): value is AiAnswerCard;
25
- declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
26
- /**
27
- * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
28
- * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
29
- * a server's or a test's own cards; the message names what is wrong.
30
- */
31
- declare function assertAnswerCardContract(card: unknown): asserts card is AiAnswerCard;
32
- //#endregion
33
- //#region src/bind.d.ts
34
- /**
35
- * Every element the binding adds to the thread carries a class under this block, so a host styles
36
- * the chat by class rather than by the order its elements happen to come in.
37
- */
38
- declare const CHAT_CLASS = "vv-ai-chat";
39
- declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
40
- //#endregion
41
- //#region src/cards.d.ts
42
- /** Block classes of the cards below. Every element a card renders carries a class under its block. */
43
- declare const CARD_LIST_CLASS = "vv-ai-card-list";
44
- declare const ACTIONS_CLASS = "vv-ai-actions";
45
- /**
46
- * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
47
- * Items that render nothing are skipped, and a list with nothing in it is null.
48
- */
49
- declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
50
- /**
51
- * A row of things the visitor can do next. An item with `action` is a button that runs the action
52
- * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
53
- * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
54
- */
55
- declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
56
- //#endregion
57
- //#region src/chat.d.ts
58
- declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
59
- //#endregion
60
- //#region src/dom.d.ts
61
- declare function isSafeLinkUrl(url: string): boolean;
62
- declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
63
- /**
64
- * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
65
- * width and height, when given, let the browser reserve the space before the image arrives.
66
- */
67
- declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
68
- /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
69
- declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
70
- //#endregion
71
- //#region src/form-context.d.ts
72
- /**
73
- * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
74
- * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
75
- * sent with every later question through `binding.setFormContext`, framed as context rather than
76
- * something the visitor said. Returns a function that stops watching.
77
- */
78
- declare function watchFormContext(binding: AiChatBinding, element: HTMLElement, options: AiFormContextOptions): () => void;
79
- //#endregion
80
- //#region src/handover.d.ts
81
- /** The action the handover card's button runs; the binding hands over to a person with it. */
82
- declare const LIVE_CHAT_ACTION = "livechat";
83
- /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
84
- declare const HANDOVER_TOOL = "request_human_agent";
85
- /** A payload of kind `handover`, or one from the handover tool that names no kind. */
86
- declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
87
- /**
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. The payload's `prefill`
90
- * goes on the button as its value. Null when neither applies.
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;
98
- //#endregion
99
- //#region src/protocol.d.ts
100
- declare const AI_CHAT_PROTOCOL_VERSION = 1;
101
- declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
102
- //#endregion
103
- //#region src/registry.d.ts
104
- declare function createAiChatRegistry(): AiChatRegistry;
105
- //#endregion
106
- //#region src/stream.d.ts
107
- declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
13
+ declare function readServerEvents(response: Response, signal: AbortSignal): AsyncGenerator<AiServerEvent>;
108
14
  //#endregion
109
- //#region src/surfaces.d.ts
110
- /**
111
- * A surface that shows one item out of an authored list template. The template is cloned, every
112
- * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
113
- * rest of the template stays as authored, so one item is the same markup the whole list shows.
114
- * Null when the template is missing or no item matches.
115
- */
116
- declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
117
- /**
118
- * A surface of which only the latest copy stays in the thread, for an embedded component whose
119
- * script binds to the first match in the document or whose fields share ids. What it draws is
120
- * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
121
- */
122
- declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
123
- //#endregion
124
- //#region src/window.d.ts
125
- /**
126
- * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
127
- * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
128
- * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
129
- * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
130
- * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
131
- * next page does not open it again from the stored thread. Returns a function that undoes it all.
132
- */
133
- declare function bindChatWindow(binding: AiChatBinding): () => void;
134
- /**
135
- * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
136
- * started a chat: not while the window is open or its thread has messages. A
137
- * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
138
- * cannot be read the teaser is not shown. Returns a function that undoes it.
139
- */
140
- declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
15
+ //#region src/markdown.d.ts
16
+ declare const MAX_MARKDOWN_CHARACTERS = 8000;
17
+ declare function renderMarkdown(document: Document, source: string): DocumentFragment;
141
18
  //#endregion
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 };
19
+ export { type AiCardImage, type AiServerEvent, MAX_MARKDOWN_CHARACTERS, createPart, createSafeImage, createSafeLink, isSafeLinkUrl, readServerEvents, renderMarkdown };