@vettvangur/ai-sdk 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,6 +83,85 @@ from authored `data-ai-action` markup and receive an optional authored `data-ai-
83
83
  Neither server payloads nor model output become executable markup. Generic answer cards, links and
84
84
  Markdown are rendered as safe DOM nodes. Host callbacks must return DOM nodes, not HTML strings.
85
85
 
86
+ ## A small window, a stored thread and a person
87
+
88
+ The same binding drives a compact window on every page. `binding.open()` and `binding.close()` set
89
+ `data-ai-chat-open` on the root, a `data-ai-chat-close` button closes it, and `binding.isOpen` says
90
+ which it is. `binding.on('open' | 'close' | 'handover' | 'end', listener)` returns an unsubscribe;
91
+ the binding knows nothing of analytics or page classes, so the host does those from these events.
92
+
93
+ With `storageKey` (or `data-ai-chat-storage-key`), the thread is kept in `sessionStorage` under that
94
+ key: the questions, each answer's text and tool results, the people's messages, the notices, the
95
+ conversation id, the open state and a live chat's resume token. The next page in the same tab draws
96
+ it again and carries on. A reset clears it. Without storage, the chat works as before.
97
+
98
+ `binding.handover({ provider, context, prefill })` hands the thread to a person through a live
99
+ chat provider (`provider` defaults to the `liveChat` option). It asks the provider whether anyone is
100
+ there, shows its pre-chat survey in the thread as a `vv-ai-survey` form with `prefill` values in it
101
+ (by field name or id), and starts the chat. The form has an optional `survey-title` and
102
+ `survey-intro` above its fields, a `survey-prefilled` note under each field filled in for the
103
+ visitor, and checks that an email field holds an address (`survey-invalid-email`). With `handoverEndpoint` (or
104
+ `data-ai-chat-handover-endpoint`), it first posts `{ conversationId, culture, messages }` with the
105
+ antiforgery header and expects `{ transcript, context }`: the transcript is sent as the visitor's
106
+ opening message and the context goes to the agent, under the `context` the host passes. A failed
107
+ request hands over without them, so a visitor always reaches a person. It resolves to `live`,
108
+ `closed` with a reason, `canceled` or `failed`.
109
+
110
+ `binding.mode`, also `data-ai-chat-mode` on the root, is `ai`, `handover` (the input is disabled
111
+ while the survey is asked) or `live`. While live, the composer sends to the provider and the
112
+ agent's typing shows as `__typing`, three `__typing-dot`s. The visitor's typing is passed on: as
113
+ their draft through the provider's optional `draft(text)`, for an agent's preview, or otherwise as
114
+ `typing()`. A started chat adds an `__notice--started` divider and a `__waiting` card until an agent
115
+ takes it, which the provider reports through its optional `onAgent`, or the first agent message
116
+ does. Then an `__notice--joined` divider names them, the `agent` event fires, `data-ai-chat-live`
117
+ on the root goes from `waiting` to `agent`, and elements marked `data-ai-chat-agent-name` and
118
+ `data-ai-chat-agent-initials` are filled in. An agent's messages are `__message--person` with
119
+ `__initials` and a `__sender` (their first name, then the `live-chat-team` label when set); the
120
+ provider's own messages are `__notice--system`. While live the input shows its
121
+ `data-ai-chat-live-placeholder`, and while the survey is asked its
122
+ `data-ai-chat-handover-placeholder`. When the agent ends the chat (an `__notice--agent-ended` divider),
123
+ or the visitor does with a `data-ai-chat-end` button (shown only while live) or
124
+ `binding.endLiveChat()`, the thread returns to the AI under an `__notice--ended`. A stored live chat
125
+ reconnects on the next page through the `liveChat` option, leaving out messages already shown.
126
+ `binding.liveChat` is the provider in use, for a host to offer its optional `emailTranscript` and
127
+ `upload`. Labels: `live-chat-connecting`, `live-chat-closed`, `live-chat-ended`, `live-chat-failed`,
128
+ `live-chat-typing`, `live-chat-agent`, `live-chat-started`, `live-chat-joined` and
129
+ `live-chat-agent-ended` (with `{name}`), `live-chat-waiting`, `live-chat-waiting-text`,
130
+ `live-chat-team`, `survey-title`, `survey-intro`, `survey-prefilled`, `survey-submit`,
131
+ `survey-cancel`, `survey-required`, `survey-invalid-email`.
132
+
133
+ `@vettvangur/ai-sdk/live-chat` exports the provider contract (`AiLiveChatProvider`) and
134
+ `renderSurveyForm`. `@vettvangur/ai-sdk/live-chat/omnichannel` exports
135
+ `createOmnichannelProvider({ orgId, orgUrl, widgetId })` over Dynamics 365 Omnichannel. It needs
136
+ the optional peer dependency `@microsoft/omnichannel-chat-sdk` and imports it only when the
137
+ provider is first used, so a page pays for it when a visitor asks for a person. It reads opening
138
+ hours from the widget's config and turns the Adaptive Card survey into text, choice and toggle
139
+ fields, refusing a card with any other input rather than leaving a question out.
140
+
141
+ ```ts
142
+ import { bindChat } from '@vettvangur/ai-sdk'
143
+ import { createOmnichannelProvider } from '@vettvangur/ai-sdk/live-chat/omnichannel'
144
+
145
+ const liveChat = createOmnichannelProvider({ orgId, orgUrl, widgetId })
146
+ const chat = bindChat(root, { storageKey: 'site-chat', handoverEndpoint: '/webapi/aichat/handover', liveChat })
147
+ chat.on('end', ({ reason }) => track('chat_end', reason))
148
+ await chat.handover({ context: { aiShipment: 'L26000008' }, prefill: { Email: email } })
149
+ ```
150
+
151
+ `@vettvangur/ai-sdk/live-chat/aichat` exports `createAiChatLiveProvider({ endpoint, headers })` for
152
+ sites without a contact centre: agents answer from the Live view of the Vettvangur.AiChat backoffice
153
+ section. `endpoint` is the prefix the site maps with `MapAiChat`, and `headers` go with every
154
+ request, so pass the antiforgery header the chat sends. It reports `no-agents` while nobody has the
155
+ Live view open, and its resume token is the visitor's chat token. Given `survey` fields, it asks
156
+ them before the chat starts and sends the answers to the agent by field name, a choice by its label
157
+ and a toggle as `yes` or `no` (`true` and `false` when not given).
158
+
159
+ ```ts
160
+ import { createAiChatLiveProvider } from '@vettvangur/ai-sdk/live-chat/aichat'
161
+
162
+ const liveChat = createAiChatLiveProvider({ endpoint: '/webapi/aichat', headers: { RequestVerificationToken: token } })
163
+ ```
164
+
86
165
  ## Surfaces
87
166
 
88
167
  `createTemplateItemSurface({ template, attribute, key })` shows one item from an authored list
package/dist/dom.js ADDED
@@ -0,0 +1,62 @@
1
+ //#region src/dom.ts
2
+ function hasUnsafeLinkCharacter(value) {
3
+ for (const character of value) {
4
+ const code = character.charCodeAt(0);
5
+ if (/\s/.test(character) || character === "\\" || code <= 31 || code >= 127 && code <= 159) return true;
6
+ }
7
+ return false;
8
+ }
9
+ function isSafeLinkUrl(url) {
10
+ if (url.length === 0 || hasUnsafeLinkCharacter(url)) return false;
11
+ if (url.startsWith("/") || url.startsWith("#")) return !url.startsWith("//");
12
+ if (/^https?:\/\//i.test(url)) try {
13
+ const parsed = new URL(url);
14
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
15
+ } catch {
16
+ return false;
17
+ }
18
+ return /^(?:mailto|tel):[^:]+$/i.test(url);
19
+ }
20
+ function createSafeLink(document, label, url) {
21
+ if (!isSafeLinkUrl(url)) return null;
22
+ const link = document.createElement("a");
23
+ link.href = url;
24
+ link.append(document.createTextNode(label));
25
+ if (/^https?:\/\//i.test(url)) {
26
+ link.target = "_blank";
27
+ link.rel = "noopener noreferrer";
28
+ }
29
+ return link;
30
+ }
31
+ function isPlainObject(value) {
32
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
33
+ const prototype = Object.getPrototypeOf(value);
34
+ return prototype === Object.prototype || prototype === null;
35
+ }
36
+ /**
37
+ * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
38
+ * width and height, when given, let the browser reserve the space before the image arrives.
39
+ */
40
+ function createSafeImage(document, image) {
41
+ if (!image || typeof image.url !== "string" || !/^(https?:\/\/|\/)/i.test(image.url) || !isSafeLinkUrl(image.url)) return null;
42
+ const element = document.createElement("img");
43
+ element.src = image.url;
44
+ element.alt = typeof image.alt === "string" ? image.alt : "";
45
+ element.loading = "lazy";
46
+ element.decoding = "async";
47
+ if (typeof image.url2x === "string" && /^(https?:\/\/|\/)/i.test(image.url2x) && isSafeLinkUrl(image.url2x)) element.srcset = `${image.url} 1x, ${image.url2x} 2x`;
48
+ if (image.width && image.height) {
49
+ element.width = image.width;
50
+ element.height = image.height;
51
+ }
52
+ return element;
53
+ }
54
+ /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
55
+ function createPart(document, tag, block, part, text) {
56
+ const element = document.createElement(tag);
57
+ element.className = part ? `${block}__${part}` : block;
58
+ if (text) element.textContent = text;
59
+ return element;
60
+ }
61
+ //#endregion
62
+ export { isSafeLinkUrl as a, isPlainObject as i, createSafeImage as n, createSafeLink as r, createPart as t };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { a as AiLiveChatProvider, i as AiLiveChatMessage, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, s as AiLiveChatSurveyField, t as AiLiveChatAnswers } from "./provider.js";
1
2
  //#region src/contracts.d.ts
2
3
  type AiChatMessage = {
3
4
  role: 'user' | 'assistant';
@@ -33,6 +34,8 @@ type AiChatSession = {
33
34
  setContext(name: string, value: string): void;
34
35
  setContextMessage(name: string, content: string): void;
35
36
  addAssistantReply(content: string): void;
37
+ /** Replaces the history with messages kept from an earlier page, such as a stored thread. */
38
+ restoreHistory(messages: readonly AiChatMessage[]): void;
36
39
  clearContext(name: string): void;
37
40
  subscribe(listener: (event: AiChatStreamEvent) => void): () => void;
38
41
  dispose(): void;
@@ -120,6 +123,32 @@ type AiChatStreamEvent = {
120
123
  };
121
124
  type AiChatLabels = AiAnswerCardLabels & {
122
125
  followUps: string;
126
+ liveChatConnecting: string;
127
+ liveChatClosed: string;
128
+ liveChatEnded: string;
129
+ liveChatFailed: string;
130
+ liveChatTyping: string;
131
+ liveChatAgent: string;
132
+ /** A divider once the chat has started. */
133
+ liveChatStarted: string;
134
+ /** A divider when the agent joins; `{name}` is their first name. */
135
+ liveChatJoined: string;
136
+ /** A divider when the agent ends the chat; `{name}` is their first name. */
137
+ liveChatAgentEnded: string;
138
+ /** The card shown while the visitor waits for an agent, and the text under it when not empty. */
139
+ liveChatWaiting: string;
140
+ liveChatWaitingText: string;
141
+ /** Shown after the agent's name above their messages when not empty, such as their team. */
142
+ liveChatTeam: string;
143
+ surveySubmit: string;
144
+ surveyCancel: string;
145
+ surveyRequired: string;
146
+ surveyInvalidEmail: string;
147
+ /** Above the survey's fields, each left out when empty. */
148
+ surveyTitle: string;
149
+ surveyIntro: string;
150
+ /** Under a field the host's prefill filled in, when not empty. */
151
+ surveyPrefilled: string;
123
152
  error: string;
124
153
  timeout: string;
125
154
  toolRunning: string;
@@ -162,16 +191,63 @@ type AiChatBindings = {
162
191
  labels?: Partial<AiChatLabels>;
163
192
  toolLabels?: Record<string, string>;
164
193
  feedbackEndpoint?: string;
194
+ /** Where `handover()` asks the server for the transcript and context to give the agent. */
195
+ handoverEndpoint?: string;
196
+ /** Keeps the thread in sessionStorage under this key, so it carries on across page loads. */
197
+ storageKey?: string;
198
+ /** The provider a stored live chat reconnects through, and `handover()` uses by default. */
199
+ liveChat?: AiLiveChatProvider;
165
200
  offsetElement?: HTMLElement | null;
166
201
  registry?: AiChatRegistry;
167
202
  onEmbedded?: (element: HTMLElement) => void;
168
203
  onError?: (error: Error) => void;
169
204
  };
205
+ /** Who the composer talks to: the AI, a handover on its way, or a person. */
206
+ type AiChatMode = 'ai' | 'handover' | 'live';
207
+ type AiChatHandoverOptions = {
208
+ provider?: AiLiveChatProvider;
209
+ /** Values for the agent, over those the handover endpoint returns. */
210
+ context?: Record<string, string>;
211
+ /** Survey answers to start with, by field name or id. */
212
+ prefill?: AiLiveChatAnswers;
213
+ };
214
+ type AiChatHandoverResult = {
215
+ status: 'live';
216
+ } | {
217
+ status: 'closed';
218
+ reason: 'out-of-hours' | 'no-agents';
219
+ } | {
220
+ status: 'canceled';
221
+ } | {
222
+ status: 'failed';
223
+ error: Error;
224
+ };
225
+ type AiChatEventMap = {
226
+ open: undefined;
227
+ close: undefined;
228
+ handover: undefined;
229
+ /** An agent took the chat; `name` is their full display name when the provider has one. */
230
+ agent: {
231
+ name: string | null;
232
+ };
233
+ end: {
234
+ reason: 'agent' | 'visitor' | 'disconnected';
235
+ };
236
+ };
170
237
  type AiChatBinding = {
171
238
  session: AiChatSession;
172
239
  labels: Readonly<AiChatLabels>;
240
+ readonly mode: AiChatMode;
241
+ readonly isOpen: boolean;
242
+ /** The provider of the live chat in progress, so a host can offer its optional capabilities. */
243
+ readonly liveChat: AiLiveChatProvider | null;
173
244
  appendAssistantReply(text: string): void;
174
245
  setFormContext(name: string, summary: string, followUp?: string | null): void;
246
+ open(): void;
247
+ close(): void;
248
+ handover(options?: AiChatHandoverOptions): Promise<AiChatHandoverResult>;
249
+ endLiveChat(): Promise<void>;
250
+ on<K extends keyof AiChatEventMap>(name: K, listener: (detail: AiChatEventMap[K]) => void): () => void;
175
251
  destroy(): void;
176
252
  };
177
253
  type AiCardImage = {
@@ -275,4 +351,4 @@ declare function readEventStream(response: Response, signal: AbortSignal): Async
275
351
  */
276
352
  declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: AiChatExtensionContext) => DocumentFragment | null;
277
353
  //#endregion
278
- 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 AiChatExtensionContext, type AiChatMessage, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiTemplateItemSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, 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, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList };
354
+ 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 AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, 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, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList };