@vettvangur/ai-sdk 0.1.14 → 0.4.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 +56 -3
- package/dist/index.d.ts +63 -10
- package/dist/index.js +232 -44
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,12 +3,20 @@
|
|
|
3
3
|
Framework-agnostic, unstyled AI chat primitives for server-rendered shells.
|
|
4
4
|
|
|
5
5
|
It exports protocol-v1 contracts, parsing and SSE stream-reading primitives, a headless chat session,
|
|
6
|
-
|
|
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: every element it renders carries a BEM class, and the project styles those.
|
|
7
8
|
|
|
8
9
|
```html
|
|
9
10
|
<section data-ai-chat data-ai-chat-endpoint="/webapi/aichat/stream"
|
|
10
|
-
data-ai-chat-antiforgery-header="RequestVerificationToken" data-ai-chat-antiforgery-token="…"
|
|
11
|
-
|
|
11
|
+
data-ai-chat-antiforgery-header="RequestVerificationToken" data-ai-chat-antiforgery-token="…"
|
|
12
|
+
data-ai-chat-offset=".header"
|
|
13
|
+
data-ai-chat-label-error="Something went wrong."
|
|
14
|
+
data-ai-chat-tool-find-offices="Looking up offices">
|
|
15
|
+
<div data-ai-chat-scroll>
|
|
16
|
+
<div data-ai-chat-thread>
|
|
17
|
+
<button type="button" data-ai-chat-suggestion="Where is my shipment?">Where is my shipment?</button>
|
|
18
|
+
</div>
|
|
19
|
+
</div>
|
|
12
20
|
<form data-ai-chat-form><textarea data-ai-chat-input></textarea><button data-ai-chat-send>Send</button></form>
|
|
13
21
|
<button type="button" data-ai-chat-reset>Reset</button>
|
|
14
22
|
</section>
|
|
@@ -28,6 +36,32 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
|
|
|
28
36
|
// Call chat.destroy() when its server-rendered shell is removed.
|
|
29
37
|
```
|
|
30
38
|
|
|
39
|
+
## The shell
|
|
40
|
+
|
|
41
|
+
`bindChat` needs the form, input and thread; the rest is optional.
|
|
42
|
+
|
|
43
|
+
| Markup | What the binding does with it |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `data-ai-chat-suggestion` | Asks its value (or its text) as the question. |
|
|
46
|
+
| `data-ai-chat-reset` | Clears the thread back to how the server rendered it and starts a new conversation. |
|
|
47
|
+
| `data-ai-chat-scroll` | The element the thread scrolls in. While an answer arrives, the latest question is held at its top; scrolling by hand lets go until the next question. |
|
|
48
|
+
| `data-ai-chat-offset` | A selector for the element the shell sits under, such as a fixed header. Its height is kept in `--vv-ai-chat-offset` on the root. `offsetElement` does the same from script. |
|
|
49
|
+
| `data-ai-chat-label-*` | Labels, in kebab case: `error`, `timeout`, `tool-running`, `tool-complete`, `tool-failed`, `tool-interrupted`, `sources`, `details`, `table`, `table-scroll`. The `labels` option wins over the attribute. |
|
|
50
|
+
| `data-ai-chat-tool-*` | The progress label for one tool, with underscores in its name written as hyphens. Other tools show `tool-running`. The `toolLabels` option wins over the attribute. |
|
|
51
|
+
|
|
52
|
+
The binding also keeps `--vv-ai-chat-keyboard` on the root at the height an on-screen keyboard
|
|
53
|
+
covers, grows the input to fit what is typed, sets `aria-busy` on the root while a turn is in flight,
|
|
54
|
+
and sends a `conversationId` context value that changes on every reset.
|
|
55
|
+
|
|
56
|
+
Elements it adds carry classes under `CHAT_CLASS` (`vv-ai-chat`): `__message` with `--user` or
|
|
57
|
+
`--assistant`, `__text`, `__tool` with `--done` and `--failed`, `__tool-dot`, `__tool-label`,
|
|
58
|
+
`__tool-status`, `__result` around a rendered tool result, and `__error`.
|
|
59
|
+
|
|
60
|
+
`binding.setFormContext(name, summary, followUp)` sends what a visitor entered into an embedded form
|
|
61
|
+
with every later question. An unchanged summary is not sent again, and `followUp` is added as an
|
|
62
|
+
assistant reply only the first time. Renderers and surfaces receive the resolved `labels`, as does
|
|
63
|
+
`binding.labels`.
|
|
64
|
+
|
|
31
65
|
`createChatSession()` is available when a host owns its own rendering. It sends JSON POST requests
|
|
32
66
|
to the configured same-origin endpoint and reads its SSE response. Supply the antiforgery header
|
|
33
67
|
through `bindChat` options or the root attributes; blank header names or tokens are omitted.
|
|
@@ -38,6 +72,25 @@ from authored `data-ai-action` markup and receive an optional authored `data-ai-
|
|
|
38
72
|
Neither server payloads nor model output become executable markup. Generic answer cards, links and
|
|
39
73
|
Markdown are rendered as safe DOM nodes. Host callbacks must return DOM nodes, not HTML strings.
|
|
40
74
|
|
|
75
|
+
## Surfaces
|
|
76
|
+
|
|
77
|
+
`createTemplateItemSurface({ template, attribute, key })` shows one item from an authored list
|
|
78
|
+
template: it clones `template[data-template]` and removes every element carrying `attribute` whose
|
|
79
|
+
value is not the payload's `key` field. Register it with `registry.registerSurface`.
|
|
80
|
+
|
|
81
|
+
## Cards
|
|
82
|
+
|
|
83
|
+
Each returns null when there is nothing to show. Cards for a project's own payloads belong to the
|
|
84
|
+
project; build them with the helpers below rather than adding them here.
|
|
85
|
+
|
|
86
|
+
- `renderActions` (`vv-ai-actions`): buttons that run a registered action and safe links, each
|
|
87
|
+
`__action` with `--primary` or `--secondary`.
|
|
88
|
+
- `renderCardList` (`vv-ai-card-list`, `--{modifier}`): several cards from one result.
|
|
89
|
+
|
|
90
|
+
`createSafeImage` (web and site-relative URLs only, with srcset and size when given),
|
|
91
|
+
`createSafeLink` (the `isSafeLinkUrl` rule, new tab for web URLs) and `createPart` (an element with
|
|
92
|
+
a BEM class and text) are exported for a host's own renderers.
|
|
93
|
+
|
|
41
94
|
## Answer cards
|
|
42
95
|
|
|
43
96
|
`renderAnswerCard()` draws a `kind: 'answer'` payload as DOM, or returns null when it breaks any
|
package/dist/index.d.ts
CHANGED
|
@@ -127,6 +127,7 @@ type AiChatExtensionContext = {
|
|
|
127
127
|
tool: string;
|
|
128
128
|
data: unknown;
|
|
129
129
|
reply: string | null;
|
|
130
|
+
labels: AiChatLabels;
|
|
130
131
|
};
|
|
131
132
|
type AiChatRenderer = (context: AiChatExtensionContext) => Node | null;
|
|
132
133
|
type AiChatSurface = (context: AiChatExtensionContext) => Node | null;
|
|
@@ -153,24 +154,38 @@ type AiChatBindings = {
|
|
|
153
154
|
antiforgeryToken?: string;
|
|
154
155
|
timeoutMs?: number;
|
|
155
156
|
labels?: Partial<AiChatLabels>;
|
|
156
|
-
|
|
157
|
+
toolLabels?: Record<string, string>;
|
|
158
|
+
offsetElement?: HTMLElement | null;
|
|
157
159
|
registry?: AiChatRegistry;
|
|
158
160
|
onEmbedded?: (element: HTMLElement) => void;
|
|
159
161
|
onError?: (error: Error) => void;
|
|
160
162
|
};
|
|
161
|
-
type AiChatClasses = {
|
|
162
|
-
messageUser: string;
|
|
163
|
-
messageAssistant: string;
|
|
164
|
-
text: string;
|
|
165
|
-
tool: string;
|
|
166
|
-
card: string;
|
|
167
|
-
error: string;
|
|
168
|
-
};
|
|
169
163
|
type AiChatBinding = {
|
|
170
164
|
session: AiChatSession;
|
|
165
|
+
labels: Readonly<AiChatLabels>;
|
|
171
166
|
appendAssistantReply(text: string): void;
|
|
167
|
+
setFormContext(name: string, summary: string, followUp?: string | null): void;
|
|
172
168
|
destroy(): void;
|
|
173
169
|
};
|
|
170
|
+
type AiCardImage = {
|
|
171
|
+
url: string;
|
|
172
|
+
url2x?: string | null;
|
|
173
|
+
alt?: string | null;
|
|
174
|
+
width?: number | null;
|
|
175
|
+
height?: number | null;
|
|
176
|
+
};
|
|
177
|
+
type AiChatActionItem = {
|
|
178
|
+
label: string;
|
|
179
|
+
action?: string | null;
|
|
180
|
+
value?: string | null;
|
|
181
|
+
url?: string | null;
|
|
182
|
+
primary?: boolean;
|
|
183
|
+
};
|
|
184
|
+
type AiTemplateItemSurfaceOptions = {
|
|
185
|
+
template: string;
|
|
186
|
+
attribute: string;
|
|
187
|
+
key: string;
|
|
188
|
+
};
|
|
174
189
|
//#endregion
|
|
175
190
|
//#region src/answer-card.d.ts
|
|
176
191
|
declare const MAX_ANSWER_CARD_SECTIONS = 12;
|
|
@@ -197,13 +212,42 @@ declare function isAnswerCard(value: unknown): value is AiAnswerCard;
|
|
|
197
212
|
declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
|
|
198
213
|
//#endregion
|
|
199
214
|
//#region src/bind.d.ts
|
|
215
|
+
/**
|
|
216
|
+
* Every element the binding adds to the thread carries a class under this block, so a host styles
|
|
217
|
+
* the chat by class rather than by the order its elements happen to come in.
|
|
218
|
+
*/
|
|
219
|
+
declare const CHAT_CLASS = "vv-ai-chat";
|
|
200
220
|
declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
|
|
201
221
|
//#endregion
|
|
222
|
+
//#region src/cards.d.ts
|
|
223
|
+
/** Block classes of the cards below. Every element a card renders carries a class under its block. */
|
|
224
|
+
declare const CARD_LIST_CLASS = "vv-ai-card-list";
|
|
225
|
+
declare const ACTIONS_CLASS = "vv-ai-actions";
|
|
226
|
+
/**
|
|
227
|
+
* Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
|
|
228
|
+
* Items that render nothing are skipped, and a list with nothing in it is null.
|
|
229
|
+
*/
|
|
230
|
+
declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
|
|
231
|
+
/**
|
|
232
|
+
* A row of things the visitor can do next. An item with `action` is a button that runs the action
|
|
233
|
+
* registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
|
|
234
|
+
* link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
|
|
235
|
+
*/
|
|
236
|
+
declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
|
|
237
|
+
//#endregion
|
|
202
238
|
//#region src/chat.d.ts
|
|
203
239
|
declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
|
|
204
240
|
//#endregion
|
|
205
241
|
//#region src/dom.d.ts
|
|
206
242
|
declare function isSafeLinkUrl(url: string): boolean;
|
|
243
|
+
declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
|
|
244
|
+
/**
|
|
245
|
+
* An image only from a site-relative or web URL; anything else is left out rather than loaded. The
|
|
246
|
+
* width and height, when given, let the browser reserve the space before the image arrives.
|
|
247
|
+
*/
|
|
248
|
+
declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
|
|
249
|
+
/** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
|
|
250
|
+
declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
|
|
207
251
|
//#endregion
|
|
208
252
|
//#region src/protocol.d.ts
|
|
209
253
|
declare const AI_CHAT_PROTOCOL_VERSION = 1;
|
|
@@ -215,4 +259,13 @@ declare function createAiChatRegistry(): AiChatRegistry;
|
|
|
215
259
|
//#region src/stream.d.ts
|
|
216
260
|
declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
|
|
217
261
|
//#endregion
|
|
218
|
-
|
|
262
|
+
//#region src/surfaces.d.ts
|
|
263
|
+
/**
|
|
264
|
+
* A surface that shows one item out of an authored list template. The template is cloned, every
|
|
265
|
+
* element carrying `attribute` whose value is not the payload's `key` field is removed, and the
|
|
266
|
+
* rest of the template stays as authored, so one item is the same markup the whole list shows.
|
|
267
|
+
* Null when the template is missing or no item matches.
|
|
268
|
+
*/
|
|
269
|
+
declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: AiChatExtensionContext) => DocumentFragment | null;
|
|
270
|
+
//#endregion
|
|
271
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -33,6 +33,31 @@ function isPlainObject(value) {
|
|
|
33
33
|
const prototype = Object.getPrototypeOf(value);
|
|
34
34
|
return prototype === Object.prototype || prototype === null;
|
|
35
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
|
+
}
|
|
36
61
|
//#endregion
|
|
37
62
|
//#region src/markdown.ts
|
|
38
63
|
const MAX_MARKDOWN_CHARACTERS = 8e3;
|
|
@@ -936,14 +961,24 @@ const defaultLabels = {
|
|
|
936
961
|
table: "Published table",
|
|
937
962
|
tableScroll: "Scroll sideways to see all columns"
|
|
938
963
|
};
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
}
|
|
964
|
+
/**
|
|
965
|
+
* Every element the binding adds to the thread carries a class under this block, so a host styles
|
|
966
|
+
* the chat by class rather than by the order its elements happen to come in.
|
|
967
|
+
*/
|
|
968
|
+
const CHAT_CLASS = "vv-ai-chat";
|
|
969
|
+
const CONVERSATION_CONTEXT = "conversationId";
|
|
970
|
+
function part(name) {
|
|
971
|
+
return `${CHAT_CLASS}__${name}`;
|
|
972
|
+
}
|
|
973
|
+
function kebab(name) {
|
|
974
|
+
return name.replace(/[A-Z_]/g, (character) => character === "_" ? "-" : `-${character.toLowerCase()}`);
|
|
975
|
+
}
|
|
976
|
+
/** Labels from `data-ai-chat-label-*` on the root, under the options and over the defaults. */
|
|
977
|
+
function readLabels(root, labels) {
|
|
978
|
+
const read = {};
|
|
979
|
+
for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
|
|
980
|
+
return read;
|
|
981
|
+
}
|
|
947
982
|
function dataString(data, name) {
|
|
948
983
|
if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
|
|
949
984
|
const value = data[name];
|
|
@@ -956,14 +991,7 @@ function bindChat(root, options = {}) {
|
|
|
956
991
|
const send = root.querySelector("[data-ai-chat-send]");
|
|
957
992
|
if (!form || !input || !thread) throw new Error("AI chat shell requires form, input and thread elements");
|
|
958
993
|
const chatThread = thread;
|
|
959
|
-
const labels =
|
|
960
|
-
...defaultLabels,
|
|
961
|
-
...options.labels
|
|
962
|
-
};
|
|
963
|
-
const classes = {
|
|
964
|
-
...defaultClasses,
|
|
965
|
-
...options.classes
|
|
966
|
-
};
|
|
994
|
+
const labels = readLabels(root, options.labels);
|
|
967
995
|
const initialThread = chatThread.cloneNode(true);
|
|
968
996
|
let initialNodes = Array.from(chatThread.childNodes);
|
|
969
997
|
const endpoint = options.endpoint ?? root.dataset.aiChatEndpoint ?? form.action;
|
|
@@ -975,23 +1003,32 @@ function bindChat(root, options = {}) {
|
|
|
975
1003
|
let activeTextContent = "";
|
|
976
1004
|
let pendingTool = null;
|
|
977
1005
|
let destroyed = false;
|
|
1006
|
+
const formContexts = /* @__PURE__ */ new Map();
|
|
1007
|
+
const cleanups = [];
|
|
978
1008
|
const session = createChatSession({
|
|
979
1009
|
endpoint,
|
|
980
1010
|
provider: options.provider ?? root.dataset.aiChatProvider,
|
|
981
1011
|
headers,
|
|
982
1012
|
timeoutMs: options.timeoutMs
|
|
983
1013
|
});
|
|
1014
|
+
function startConversation() {
|
|
1015
|
+
session.setContext(CONVERSATION_CONTEXT, crypto.randomUUID());
|
|
1016
|
+
}
|
|
1017
|
+
function listen(target, type, listener, options) {
|
|
1018
|
+
target.addEventListener(type, listener, options);
|
|
1019
|
+
cleanups.push(() => target.removeEventListener(type, listener, options));
|
|
1020
|
+
}
|
|
984
1021
|
function appendMessage(role) {
|
|
985
1022
|
const message = root.ownerDocument.createElement("div");
|
|
986
1023
|
message.dataset.aiChatMessage = role;
|
|
987
|
-
message.className =
|
|
1024
|
+
message.className = `${part("message")} ${part(`message--${role}`)}`;
|
|
988
1025
|
chatThread.append(message);
|
|
989
1026
|
return message;
|
|
990
1027
|
}
|
|
991
1028
|
function appendMarkdown(parent, text) {
|
|
992
1029
|
const bubble = root.ownerDocument.createElement("div");
|
|
993
1030
|
bubble.dataset.aiChatText = "true";
|
|
994
|
-
bubble.className =
|
|
1031
|
+
bubble.className = part("text");
|
|
995
1032
|
bubble.append(renderMarkdown(root.ownerDocument, text));
|
|
996
1033
|
parent.append(bubble);
|
|
997
1034
|
}
|
|
@@ -1000,7 +1037,7 @@ function bindChat(root, options = {}) {
|
|
|
1000
1037
|
if (!activeText) {
|
|
1001
1038
|
activeText = root.ownerDocument.createElement("div");
|
|
1002
1039
|
activeText.dataset.aiChatText = "true";
|
|
1003
|
-
activeText.className =
|
|
1040
|
+
activeText.className = part("text");
|
|
1004
1041
|
activeAssistant.append(activeText);
|
|
1005
1042
|
}
|
|
1006
1043
|
activeTextContent += text;
|
|
@@ -1010,21 +1047,26 @@ function bindChat(root, options = {}) {
|
|
|
1010
1047
|
options.onError?.(error);
|
|
1011
1048
|
const message = root.ownerDocument.createElement("p");
|
|
1012
1049
|
message.setAttribute("role", "alert");
|
|
1013
|
-
message.className =
|
|
1050
|
+
message.className = part("error");
|
|
1014
1051
|
message.append(error.name === "TimeoutError" ? labels.timeout : labels.error);
|
|
1015
1052
|
chatThread.append(message);
|
|
1016
1053
|
}
|
|
1017
|
-
function
|
|
1054
|
+
function toolLabel(name) {
|
|
1055
|
+
if (!/^[\w-]{1,64}$/.test(name)) return labels.toolRunning;
|
|
1056
|
+
return options.toolLabels?.[name] || root.getAttribute(`data-ai-chat-tool-${kebab(name)}`) || labels.toolRunning;
|
|
1057
|
+
}
|
|
1058
|
+
function tool(id, name) {
|
|
1018
1059
|
const element = root.ownerDocument.createElement("div");
|
|
1019
1060
|
element.dataset.aiChatTool = id;
|
|
1020
|
-
element.className =
|
|
1061
|
+
element.className = part("tool");
|
|
1021
1062
|
const dot = root.ownerDocument.createElement("span");
|
|
1022
|
-
dot.className = "
|
|
1063
|
+
dot.className = part("tool-dot");
|
|
1023
1064
|
dot.setAttribute("aria-hidden", "true");
|
|
1024
1065
|
const label = root.ownerDocument.createElement("span");
|
|
1025
|
-
label.
|
|
1066
|
+
label.className = part("tool-label");
|
|
1067
|
+
label.append(root.ownerDocument.createTextNode(toolLabel(name)));
|
|
1026
1068
|
const status = root.ownerDocument.createElement("span");
|
|
1027
|
-
status.className = "
|
|
1069
|
+
status.className = part("tool-status");
|
|
1028
1070
|
element.append(dot, label, status);
|
|
1029
1071
|
activeAssistant?.append(element);
|
|
1030
1072
|
return element;
|
|
@@ -1035,14 +1077,14 @@ function bindChat(root, options = {}) {
|
|
|
1035
1077
|
}
|
|
1036
1078
|
function finishTool(id, failed, interrupted = false) {
|
|
1037
1079
|
const element = activeAssistant?.querySelector(`[data-ai-chat-tool="${CSS.escape(id)}"]`);
|
|
1080
|
+
finishToolElement(element, failed, interrupted);
|
|
1081
|
+
}
|
|
1082
|
+
function finishToolElement(element, failed, interrupted) {
|
|
1038
1083
|
if (element) {
|
|
1039
|
-
element.classList.add("
|
|
1040
|
-
element.classList.toggle("
|
|
1041
|
-
const status = element.querySelector("
|
|
1042
|
-
if (status)
|
|
1043
|
-
status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
|
|
1044
|
-
status.classList.remove("sr-only");
|
|
1045
|
-
}
|
|
1084
|
+
element.classList.add(part("tool--done"));
|
|
1085
|
+
element.classList.toggle(part("tool--failed"), failed || interrupted);
|
|
1086
|
+
const status = element.querySelector(`.${part("tool-status")}`);
|
|
1087
|
+
if (status) status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
|
|
1046
1088
|
}
|
|
1047
1089
|
}
|
|
1048
1090
|
function renderResult(event) {
|
|
@@ -1054,7 +1096,8 @@ function bindChat(root, options = {}) {
|
|
|
1054
1096
|
root,
|
|
1055
1097
|
tool: event.data.name,
|
|
1056
1098
|
data: event.data.data,
|
|
1057
|
-
reply: event.data.reply
|
|
1099
|
+
reply: event.data.reply,
|
|
1100
|
+
labels
|
|
1058
1101
|
};
|
|
1059
1102
|
let content = null;
|
|
1060
1103
|
try {
|
|
@@ -1070,7 +1113,7 @@ function bindChat(root, options = {}) {
|
|
|
1070
1113
|
if (content) {
|
|
1071
1114
|
const wrapper = root.ownerDocument.createElement("div");
|
|
1072
1115
|
wrapper.dataset.aiChatCard = "true";
|
|
1073
|
-
wrapper.className =
|
|
1116
|
+
wrapper.className = part("result");
|
|
1074
1117
|
wrapper.append(content);
|
|
1075
1118
|
activeAssistant.append(wrapper);
|
|
1076
1119
|
options.onEmbedded?.(wrapper);
|
|
@@ -1090,11 +1133,16 @@ function bindChat(root, options = {}) {
|
|
|
1090
1133
|
} else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
|
|
1091
1134
|
else if (event.name === "done" || event.name === "error") clearPendingTool();
|
|
1092
1135
|
});
|
|
1136
|
+
const resizeInput = () => {
|
|
1137
|
+
input.style.height = "auto";
|
|
1138
|
+
input.style.height = `${input.scrollHeight}px`;
|
|
1139
|
+
};
|
|
1093
1140
|
const submit = async (event) => {
|
|
1094
1141
|
event?.preventDefault();
|
|
1095
1142
|
const question = input.value.trim();
|
|
1096
1143
|
if (!question || session.status !== "idle") return;
|
|
1097
1144
|
input.value = "";
|
|
1145
|
+
resizeInput();
|
|
1098
1146
|
for (const node of initialNodes) node.remove();
|
|
1099
1147
|
appendMarkdown(appendMessage("user"), question);
|
|
1100
1148
|
activeAssistant = appendMessage("assistant");
|
|
@@ -1107,8 +1155,8 @@ function bindChat(root, options = {}) {
|
|
|
1107
1155
|
root.removeAttribute("aria-busy");
|
|
1108
1156
|
if (send) send.disabled = false;
|
|
1109
1157
|
if (result.error && !result.canceled) report(result.error);
|
|
1110
|
-
if (result.canceled) activeAssistant?.querySelectorAll(
|
|
1111
|
-
item
|
|
1158
|
+
if (result.canceled) activeAssistant?.querySelectorAll(`[data-ai-chat-tool]:not(.${part("tool--done")})`).forEach((item) => {
|
|
1159
|
+
finishToolElement(item, false, true);
|
|
1112
1160
|
});
|
|
1113
1161
|
};
|
|
1114
1162
|
const click = (event) => {
|
|
@@ -1124,10 +1172,13 @@ function bindChat(root, options = {}) {
|
|
|
1124
1172
|
chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
|
|
1125
1173
|
initialNodes = Array.from(chatThread.childNodes);
|
|
1126
1174
|
input.value = "";
|
|
1175
|
+
resizeInput();
|
|
1127
1176
|
activeAssistant = null;
|
|
1128
1177
|
activeText = null;
|
|
1129
1178
|
activeTextContent = "";
|
|
1130
1179
|
pendingTool = null;
|
|
1180
|
+
formContexts.clear();
|
|
1181
|
+
startConversation();
|
|
1131
1182
|
return;
|
|
1132
1183
|
}
|
|
1133
1184
|
const actionElement = target?.closest("[data-ai-action]");
|
|
@@ -1147,27 +1198,164 @@ function bindChat(root, options = {}) {
|
|
|
1147
1198
|
submit();
|
|
1148
1199
|
}
|
|
1149
1200
|
};
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1201
|
+
function followAnswer() {
|
|
1202
|
+
const scroller = root.querySelector("[data-ai-chat-scroll]");
|
|
1203
|
+
if (!scroller) return;
|
|
1204
|
+
let question = null;
|
|
1205
|
+
let following = false;
|
|
1206
|
+
const release = () => {
|
|
1207
|
+
following = false;
|
|
1208
|
+
};
|
|
1209
|
+
listen(scroller, "wheel", release, { passive: true });
|
|
1210
|
+
listen(scroller, "touchmove", release, { passive: true });
|
|
1211
|
+
const observer = new MutationObserver(() => {
|
|
1212
|
+
const questions = chatThread.querySelectorAll("[data-ai-chat-message=\"user\"]");
|
|
1213
|
+
const latest = questions[questions.length - 1] ?? null;
|
|
1214
|
+
if (latest !== question) {
|
|
1215
|
+
question = latest;
|
|
1216
|
+
following = true;
|
|
1217
|
+
}
|
|
1218
|
+
if (!question || !following || root.getAttribute("aria-busy") !== "true") return;
|
|
1219
|
+
const top = question.getBoundingClientRect().top - chatThread.getBoundingClientRect().top - Number.parseFloat(getComputedStyle(chatThread).paddingTop || "0");
|
|
1220
|
+
following = top > scroller.scrollHeight - scroller.clientHeight;
|
|
1221
|
+
scroller.scrollTo({ top });
|
|
1222
|
+
});
|
|
1223
|
+
observer.observe(chatThread, {
|
|
1224
|
+
childList: true,
|
|
1225
|
+
subtree: true
|
|
1226
|
+
});
|
|
1227
|
+
cleanups.push(() => observer.disconnect());
|
|
1228
|
+
}
|
|
1229
|
+
function trackKeyboard() {
|
|
1230
|
+
const viewport = root.ownerDocument.defaultView?.visualViewport;
|
|
1231
|
+
if (!viewport) return;
|
|
1232
|
+
const apply = () => {
|
|
1233
|
+
const covered = window.innerHeight - viewport.height - viewport.offsetTop;
|
|
1234
|
+
root.style.setProperty(`--${CHAT_CLASS}-keyboard`, `${Math.max(0, covered)}px`);
|
|
1235
|
+
};
|
|
1236
|
+
apply();
|
|
1237
|
+
listen(viewport, "resize", apply);
|
|
1238
|
+
listen(viewport, "scroll", apply);
|
|
1239
|
+
}
|
|
1240
|
+
function trackOffset() {
|
|
1241
|
+
const selector = root.dataset.aiChatOffset;
|
|
1242
|
+
const element = options.offsetElement ?? (selector ? root.ownerDocument.querySelector(selector) : null);
|
|
1243
|
+
if (!element) return;
|
|
1244
|
+
const apply = () => root.style.setProperty(`--${CHAT_CLASS}-offset`, `${element.offsetHeight}px`);
|
|
1245
|
+
apply();
|
|
1246
|
+
const observer = new ResizeObserver(apply);
|
|
1247
|
+
observer.observe(element);
|
|
1248
|
+
cleanups.push(() => observer.disconnect());
|
|
1249
|
+
}
|
|
1250
|
+
listen(form, "submit", submit);
|
|
1251
|
+
listen(root, "click", click);
|
|
1252
|
+
listen(input, "keydown", keydown);
|
|
1253
|
+
listen(input, "input", resizeInput);
|
|
1254
|
+
followAnswer();
|
|
1255
|
+
trackKeyboard();
|
|
1256
|
+
trackOffset();
|
|
1257
|
+
startConversation();
|
|
1258
|
+
const binding = {
|
|
1154
1259
|
session,
|
|
1260
|
+
labels,
|
|
1155
1261
|
appendAssistantReply(text) {
|
|
1156
1262
|
const content = text.trim();
|
|
1157
1263
|
if (!content) return;
|
|
1158
1264
|
appendMarkdown(appendMessage("assistant"), content);
|
|
1159
1265
|
session.addAssistantReply(content);
|
|
1160
1266
|
},
|
|
1267
|
+
setFormContext(name, summary, followUp) {
|
|
1268
|
+
const content = summary.trim();
|
|
1269
|
+
if (!content || formContexts.get(name) === content) return;
|
|
1270
|
+
const first = !formContexts.has(name);
|
|
1271
|
+
formContexts.set(name, content);
|
|
1272
|
+
session.setContextMessage(name, content);
|
|
1273
|
+
if (first && followUp) binding.appendAssistantReply(followUp);
|
|
1274
|
+
},
|
|
1161
1275
|
destroy() {
|
|
1162
1276
|
if (destroyed) return;
|
|
1163
1277
|
destroyed = true;
|
|
1164
1278
|
unsubscribe();
|
|
1165
1279
|
session.dispose();
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1280
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1283
|
+
return binding;
|
|
1284
|
+
}
|
|
1285
|
+
//#endregion
|
|
1286
|
+
//#region src/cards.ts
|
|
1287
|
+
/** Block classes of the cards below. Every element a card renders carries a class under its block. */
|
|
1288
|
+
const CARD_LIST_CLASS = "vv-ai-card-list";
|
|
1289
|
+
const ACTIONS_CLASS = "vv-ai-actions";
|
|
1290
|
+
function text(value) {
|
|
1291
|
+
return typeof value === "string" && value.trim() ? value : null;
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
|
|
1295
|
+
* Items that render nothing are skipped, and a list with nothing in it is null.
|
|
1296
|
+
*/
|
|
1297
|
+
function renderCardList(document, items, render, modifier) {
|
|
1298
|
+
if (!Array.isArray(items)) return null;
|
|
1299
|
+
const cards = items.map(render).filter((card) => card !== null);
|
|
1300
|
+
if (!cards.length) return null;
|
|
1301
|
+
const list = createPart(document, "div", CARD_LIST_CLASS);
|
|
1302
|
+
if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
|
|
1303
|
+
list.append(...cards);
|
|
1304
|
+
return list;
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* A row of things the visitor can do next. An item with `action` is a button that runs the action
|
|
1308
|
+
* registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
|
|
1309
|
+
* link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
|
|
1310
|
+
*/
|
|
1311
|
+
function renderActions(document, items) {
|
|
1312
|
+
const elements = [];
|
|
1313
|
+
for (const item of items) {
|
|
1314
|
+
const label = text(item?.label);
|
|
1315
|
+
if (!label) continue;
|
|
1316
|
+
let element = null;
|
|
1317
|
+
const action = text(item.action);
|
|
1318
|
+
const url = text(item.url);
|
|
1319
|
+
if (action) {
|
|
1320
|
+
const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
|
|
1321
|
+
button.type = "button";
|
|
1322
|
+
button.dataset.aiAction = action;
|
|
1323
|
+
const value = text(item.value);
|
|
1324
|
+
if (value) button.dataset.aiActionValue = value;
|
|
1325
|
+
element = button;
|
|
1326
|
+
} else if (url) {
|
|
1327
|
+
element = createSafeLink(document, label, url.trim());
|
|
1328
|
+
if (element) element.className = `${ACTIONS_CLASS}__action`;
|
|
1329
|
+
}
|
|
1330
|
+
if (element) {
|
|
1331
|
+
element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
|
|
1332
|
+
elements.push(element);
|
|
1169
1333
|
}
|
|
1334
|
+
}
|
|
1335
|
+
if (!elements.length) return null;
|
|
1336
|
+
const actions = createPart(document, "div", ACTIONS_CLASS);
|
|
1337
|
+
actions.append(...elements);
|
|
1338
|
+
return actions;
|
|
1339
|
+
}
|
|
1340
|
+
//#endregion
|
|
1341
|
+
//#region src/surfaces.ts
|
|
1342
|
+
/**
|
|
1343
|
+
* A surface that shows one item out of an authored list template. The template is cloned, every
|
|
1344
|
+
* element carrying `attribute` whose value is not the payload's `key` field is removed, and the
|
|
1345
|
+
* rest of the template stays as authored, so one item is the same markup the whole list shows.
|
|
1346
|
+
* Null when the template is missing or no item matches.
|
|
1347
|
+
*/
|
|
1348
|
+
function createTemplateItemSurface(options) {
|
|
1349
|
+
return ({ root, data }) => {
|
|
1350
|
+
const value = isPlainObject(data) ? data[options.key] : null;
|
|
1351
|
+
const template = root.querySelector(`template[data-template="${CSS.escape(options.template)}"]`);
|
|
1352
|
+
if (typeof value !== "string" || !template) return null;
|
|
1353
|
+
const content = template.content.cloneNode(true);
|
|
1354
|
+
let found = false;
|
|
1355
|
+
for (const item of content.querySelectorAll(`[${CSS.escape(options.attribute)}]`)) if (item.getAttribute(options.attribute) === value) found = true;
|
|
1356
|
+
else item.remove();
|
|
1357
|
+
return found ? content : null;
|
|
1170
1358
|
};
|
|
1171
1359
|
}
|
|
1172
1360
|
//#endregion
|
|
1173
|
-
export { AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_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, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderAnswerCard };
|
|
1361
|
+
export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, 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 };
|