@vettvangur/ai-sdk 0.4.0 → 0.5.2
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/LICENSE +1 -1
- package/README.md +16 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +131 -12
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -4,7 +4,7 @@ All original code in this repository is licensed under the terms below:
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
Copyright (c) 2025 Vettvangur
|
|
7
|
+
Copyright (c) 2025-2026 Vettvangur ehf
|
|
8
8
|
|
|
9
9
|
This software is provided for personal or internal non-commercial use only. You may not modify, distribute, sublicense, or use this software in commercial products or services without explicit written permission from Vettvangur.
|
|
10
10
|
|
package/README.md
CHANGED
|
@@ -44,18 +44,29 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
|
|
|
44
44
|
| --- | --- |
|
|
45
45
|
| `data-ai-chat-suggestion` | Asks its value (or its text) as the question. |
|
|
46
46
|
| `data-ai-chat-reset` | Clears the thread back to how the server rendered it and starts a new conversation. |
|
|
47
|
+
| `data-ai-chat-stop` | Shown only while a reply is in flight, in place of the send button; cancels the reply. |
|
|
48
|
+
| `data-ai-chat-counter` | Shows `{used} / {maxlength}` for the input, with `data-ai-chat-near-limit` from nine tenths on. |
|
|
49
|
+
| `template[data-ai-chat-reply-actions]` | Cloned under every finished answer, in `__reply-actions`. A `data-ai-chat-copy` button in it copies the answer's prose and cards as text, and gets `data-ai-chat-copied` for two seconds. `data-ai-chat-feedback="up"` and `"down"` buttons post the rating and get `aria-pressed`; they are left out when the server sent no turn token or there is no feedback endpoint. |
|
|
50
|
+
| `data-ai-chat-feedback-endpoint` | Where ratings are posted, as `{ turn, rating }` with the antiforgery header. The `feedbackEndpoint` option wins over the attribute. |
|
|
47
51
|
| `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
52
|
| `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. |
|
|
53
|
+
| `data-ai-chat-label-*` | Labels, in kebab case: `error`, `timeout`, `tool-running`, `tool-complete`, `tool-failed`, `tool-interrupted`, `sources`, `details`, `table`, `table-scroll`, `follow-ups`. The `labels` option wins over the attribute. |
|
|
50
54
|
| `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
55
|
|
|
52
56
|
The binding also keeps `--vv-ai-chat-keyboard` on the root at the height an on-screen keyboard
|
|
53
57
|
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.
|
|
58
|
+
and sends a `conversationId` context value that changes on every reset. After a reply or a reset
|
|
59
|
+
it puts focus back in the input, but only with a fine pointer and only when the visitor is not
|
|
60
|
+
working inside the thread, so a phone's keyboard does not cover the answer.
|
|
61
|
+
|
|
62
|
+
A `suggestions` event lists questions to ask next. They are drawn under the finished answer as
|
|
63
|
+
`__follow-up` buttons in a `__follow-ups` group labelled `follow-ups`, ask themselves when clicked,
|
|
64
|
+
and are removed when the next question is asked.
|
|
55
65
|
|
|
56
66
|
Elements it adds carry classes under `CHAT_CLASS` (`vv-ai-chat`): `__message` with `--user` or
|
|
57
67
|
`--assistant`, `__text`, `__tool` with `--done` and `--failed`, `__tool-dot`, `__tool-label`,
|
|
58
|
-
`__tool-status`, `__result` around a rendered tool result,
|
|
68
|
+
`__tool-status`, `__result` around a rendered tool result, `__reply-actions`, `__follow-ups`,
|
|
69
|
+
`__follow-up` and `__error`.
|
|
59
70
|
|
|
60
71
|
`binding.setFormContext(name, summary, followUp)` sends what a visitor entered into an embedded form
|
|
61
72
|
with every later question. An unchanged summary is not sent again, and `followUp` is added as an
|
|
@@ -108,6 +119,6 @@ of plain fields. Style by these classes rather than by element order.
|
|
|
108
119
|
plain text; a link belongs in `links`, `actions` or `sources`. `isSafeLinkUrl()` is the rule every
|
|
109
120
|
link passes, exported so a host's own renderers can apply it too.
|
|
110
121
|
|
|
111
|
-
The package accepts protocol-v1 events (`delta`, `tool`, `tool_result`, `tool_done`, `
|
|
112
|
-
`error`). Host-specific card rendering, embedded-component activation and styling remain host
|
|
122
|
+
The package accepts protocol-v1 events (`delta`, `tool`, `tool_result`, `tool_done`, `suggestions`,
|
|
123
|
+
`done` with an optional `turn` token, and `error`) and ignores any other. Host-specific card rendering, embedded-component activation and styling remain host
|
|
113
124
|
responsibilities. Eimskip migration is deliberately outside this package.
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ type AiChatRequest = {
|
|
|
11
11
|
type AiChatContext = Record<string, string>;
|
|
12
12
|
type AiChatSessionStatus = 'idle' | 'sending' | 'disposed';
|
|
13
13
|
type AiChatSessionResult = {
|
|
14
|
-
|
|
14
|
+
turn: string | null;
|
|
15
15
|
canceled: boolean;
|
|
16
16
|
error: Error | null;
|
|
17
17
|
};
|
|
@@ -102,10 +102,15 @@ type AiChatStreamEvent = {
|
|
|
102
102
|
name: string;
|
|
103
103
|
isError: boolean;
|
|
104
104
|
};
|
|
105
|
+
} | {
|
|
106
|
+
name: 'suggestions';
|
|
107
|
+
data: {
|
|
108
|
+
suggestions: string[];
|
|
109
|
+
};
|
|
105
110
|
} | {
|
|
106
111
|
name: 'done';
|
|
107
112
|
data: {
|
|
108
|
-
|
|
113
|
+
turn: string | null;
|
|
109
114
|
};
|
|
110
115
|
} | {
|
|
111
116
|
name: 'error';
|
|
@@ -114,6 +119,7 @@ type AiChatStreamEvent = {
|
|
|
114
119
|
};
|
|
115
120
|
};
|
|
116
121
|
type AiChatLabels = AiAnswerCardLabels & {
|
|
122
|
+
followUps: string;
|
|
117
123
|
error: string;
|
|
118
124
|
timeout: string;
|
|
119
125
|
toolRunning: string;
|
|
@@ -155,6 +161,7 @@ type AiChatBindings = {
|
|
|
155
161
|
timeoutMs?: number;
|
|
156
162
|
labels?: Partial<AiChatLabels>;
|
|
157
163
|
toolLabels?: Record<string, string>;
|
|
164
|
+
feedbackEndpoint?: string;
|
|
158
165
|
offsetElement?: HTMLElement | null;
|
|
159
166
|
registry?: AiChatRegistry;
|
|
160
167
|
onEmbedded?: (element: HTMLElement) => void;
|
package/dist/index.js
CHANGED
|
@@ -623,6 +623,7 @@ function renderAnswerCard(document, data, labels) {
|
|
|
623
623
|
//#endregion
|
|
624
624
|
//#region src/protocol.ts
|
|
625
625
|
const AI_CHAT_PROTOCOL_VERSION = 1;
|
|
626
|
+
const MAX_TURN_TOKEN_LENGTH = 1024;
|
|
626
627
|
function isRecord(value) {
|
|
627
628
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
628
629
|
}
|
|
@@ -679,11 +680,19 @@ function parseStreamEvent(name, data) {
|
|
|
679
680
|
}
|
|
680
681
|
};
|
|
681
682
|
}
|
|
683
|
+
case "suggestions": {
|
|
684
|
+
const suggestions = data.suggestions;
|
|
685
|
+
if (!Array.isArray(suggestions)) return null;
|
|
686
|
+
return {
|
|
687
|
+
name,
|
|
688
|
+
data: { suggestions: suggestions.filter((item) => typeof item === "string" && item.trim().length > 0).filter((item) => item.length <= 200).slice(0, 6) }
|
|
689
|
+
};
|
|
690
|
+
}
|
|
682
691
|
case "done": {
|
|
683
|
-
const
|
|
684
|
-
return
|
|
692
|
+
const turn = stringValue(data, "turn");
|
|
693
|
+
return {
|
|
685
694
|
name,
|
|
686
|
-
data: {
|
|
695
|
+
data: { turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null }
|
|
687
696
|
};
|
|
688
697
|
}
|
|
689
698
|
case "error": {
|
|
@@ -818,7 +827,7 @@ function createChatSession(options) {
|
|
|
818
827
|
role: "user",
|
|
819
828
|
content
|
|
820
829
|
}];
|
|
821
|
-
let
|
|
830
|
+
let turn = null;
|
|
822
831
|
let error = null;
|
|
823
832
|
let canceled = false;
|
|
824
833
|
let answer = "";
|
|
@@ -842,7 +851,7 @@ function createChatSession(options) {
|
|
|
842
851
|
if (event.name === "tool") await afterNextPaint();
|
|
843
852
|
if (event.name === "delta") answer += event.data.text;
|
|
844
853
|
else if (event.name === "tool_result" && event.data.reply) replies.push(event.data.reply);
|
|
845
|
-
else if (event.name === "done")
|
|
854
|
+
else if (event.name === "done") turn = event.data.turn;
|
|
846
855
|
else if (event.name === "error") throw new Error(event.data.message);
|
|
847
856
|
}
|
|
848
857
|
if (answer.trim()) replies = [...replies, answer.trim()];
|
|
@@ -864,7 +873,7 @@ function createChatSession(options) {
|
|
|
864
873
|
if (session.status !== "disposed") status = "idle";
|
|
865
874
|
}
|
|
866
875
|
return {
|
|
867
|
-
|
|
876
|
+
turn,
|
|
868
877
|
canceled,
|
|
869
878
|
error
|
|
870
879
|
};
|
|
@@ -959,8 +968,10 @@ const defaultLabels = {
|
|
|
959
968
|
sources: "Sources",
|
|
960
969
|
details: "Details",
|
|
961
970
|
table: "Published table",
|
|
962
|
-
tableScroll: "Scroll sideways to see all columns"
|
|
971
|
+
tableScroll: "Scroll sideways to see all columns",
|
|
972
|
+
followUps: "Suggested questions"
|
|
963
973
|
};
|
|
974
|
+
const NEAR_LIMIT = .9;
|
|
964
975
|
/**
|
|
965
976
|
* Every element the binding adds to the thread carries a class under this block, so a host styles
|
|
966
977
|
* the chat by class rather than by the order its elements happen to come in.
|
|
@@ -989,6 +1000,8 @@ function bindChat(root, options = {}) {
|
|
|
989
1000
|
const input = root.querySelector("[data-ai-chat-input]");
|
|
990
1001
|
const thread = root.querySelector("[data-ai-chat-thread]");
|
|
991
1002
|
const send = root.querySelector("[data-ai-chat-send]");
|
|
1003
|
+
const stop = root.querySelector("[data-ai-chat-stop]");
|
|
1004
|
+
const counter = root.querySelector("[data-ai-chat-counter]");
|
|
992
1005
|
if (!form || !input || !thread) throw new Error("AI chat shell requires form, input and thread elements");
|
|
993
1006
|
const chatThread = thread;
|
|
994
1007
|
const labels = readLabels(root, options.labels);
|
|
@@ -998,10 +1011,12 @@ function bindChat(root, options = {}) {
|
|
|
998
1011
|
const header = options.antiforgeryHeader ?? root.dataset.aiChatAntiforgeryHeader;
|
|
999
1012
|
const token = options.antiforgeryToken ?? root.dataset.aiChatAntiforgeryToken;
|
|
1000
1013
|
const headers = header && token ? { [header]: token } : void 0;
|
|
1014
|
+
const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
|
|
1001
1015
|
let activeAssistant = null;
|
|
1002
1016
|
let activeText = null;
|
|
1003
1017
|
let activeTextContent = "";
|
|
1004
1018
|
let pendingTool = null;
|
|
1019
|
+
let followUps = [];
|
|
1005
1020
|
let destroyed = false;
|
|
1006
1021
|
const formContexts = /* @__PURE__ */ new Map();
|
|
1007
1022
|
const cleanups = [];
|
|
@@ -1131,8 +1146,82 @@ function bindChat(root, options = {}) {
|
|
|
1131
1146
|
clearPendingTool();
|
|
1132
1147
|
renderResult(event);
|
|
1133
1148
|
} else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
|
|
1149
|
+
else if (event.name === "suggestions") followUps = event.data.suggestions;
|
|
1134
1150
|
else if (event.name === "done" || event.name === "error") clearPendingTool();
|
|
1135
1151
|
});
|
|
1152
|
+
function setBusy(busy) {
|
|
1153
|
+
if (busy) root.setAttribute("aria-busy", "true");
|
|
1154
|
+
else root.removeAttribute("aria-busy");
|
|
1155
|
+
if (send) {
|
|
1156
|
+
send.disabled = busy;
|
|
1157
|
+
if (stop) send.hidden = busy;
|
|
1158
|
+
}
|
|
1159
|
+
if (stop) stop.hidden = !busy;
|
|
1160
|
+
}
|
|
1161
|
+
const focusInput = () => {
|
|
1162
|
+
const view = root.ownerDocument.defaultView;
|
|
1163
|
+
const active = root.ownerDocument.activeElement;
|
|
1164
|
+
if (!view?.matchMedia?.("(pointer: fine)").matches || active && chatThread.contains(active)) return;
|
|
1165
|
+
input.focus({ preventScroll: true });
|
|
1166
|
+
};
|
|
1167
|
+
function appendFollowUps(parent, suggestions) {
|
|
1168
|
+
if (!suggestions.length) return;
|
|
1169
|
+
const list = root.ownerDocument.createElement("div");
|
|
1170
|
+
list.dataset.aiChatFollowUps = "true";
|
|
1171
|
+
list.className = part("follow-ups");
|
|
1172
|
+
list.setAttribute("role", "group");
|
|
1173
|
+
list.setAttribute("aria-label", labels.followUps);
|
|
1174
|
+
for (const suggestion of suggestions) {
|
|
1175
|
+
const button = root.ownerDocument.createElement("button");
|
|
1176
|
+
button.type = "button";
|
|
1177
|
+
button.className = part("follow-up");
|
|
1178
|
+
button.dataset.aiChatSuggestion = suggestion;
|
|
1179
|
+
button.append(root.ownerDocument.createTextNode(suggestion));
|
|
1180
|
+
list.append(button);
|
|
1181
|
+
}
|
|
1182
|
+
parent.append(list);
|
|
1183
|
+
}
|
|
1184
|
+
function appendReplyActions(parent, turn) {
|
|
1185
|
+
const template = root.querySelector("template[data-ai-chat-reply-actions]");
|
|
1186
|
+
if (!template) return;
|
|
1187
|
+
const actions = root.ownerDocument.createElement("div");
|
|
1188
|
+
actions.className = part("reply-actions");
|
|
1189
|
+
actions.append(template.content.cloneNode(true));
|
|
1190
|
+
if (turn && feedbackEndpoint) actions.dataset.aiChatTurn = turn;
|
|
1191
|
+
else for (const button of actions.querySelectorAll("[data-ai-chat-feedback]")) button.remove();
|
|
1192
|
+
if (actions.children.length) parent.append(actions);
|
|
1193
|
+
}
|
|
1194
|
+
async function copyReply(button) {
|
|
1195
|
+
const message = button.closest("[data-ai-chat-message]");
|
|
1196
|
+
const parts = Array.from(message?.querySelectorAll("[data-ai-chat-text], [data-ai-chat-card]") ?? [], (element) => (element.innerText ?? element.textContent ?? "").trim()).filter(Boolean);
|
|
1197
|
+
if (!parts.length) return;
|
|
1198
|
+
await navigator.clipboard.writeText(parts.join("\n\n"));
|
|
1199
|
+
button.dataset.aiChatCopied = "true";
|
|
1200
|
+
setTimeout(() => delete button.dataset.aiChatCopied, 2e3);
|
|
1201
|
+
}
|
|
1202
|
+
async function sendFeedback(button) {
|
|
1203
|
+
const actions = button.closest("[data-ai-chat-turn]");
|
|
1204
|
+
const rating = button.dataset.aiChatFeedback;
|
|
1205
|
+
if (!actions?.dataset.aiChatTurn || !feedbackEndpoint || rating !== "up" && rating !== "down") return;
|
|
1206
|
+
const response = await fetch(feedbackEndpoint, {
|
|
1207
|
+
method: "POST",
|
|
1208
|
+
headers: {
|
|
1209
|
+
"Content-Type": "application/json",
|
|
1210
|
+
...headers
|
|
1211
|
+
},
|
|
1212
|
+
body: JSON.stringify({
|
|
1213
|
+
turn: actions.dataset.aiChatTurn,
|
|
1214
|
+
rating
|
|
1215
|
+
})
|
|
1216
|
+
});
|
|
1217
|
+
if (!response.ok) throw new Error(`AI chat feedback failed with ${response.status}`);
|
|
1218
|
+
for (const item of actions.querySelectorAll("[data-ai-chat-feedback]")) item.setAttribute("aria-pressed", String(item === button));
|
|
1219
|
+
}
|
|
1220
|
+
const updateCounter = () => {
|
|
1221
|
+
if (!counter || input.maxLength <= 0) return;
|
|
1222
|
+
counter.textContent = `${input.value.length} / ${input.maxLength}`;
|
|
1223
|
+
counter.toggleAttribute("data-ai-chat-near-limit", input.value.length >= input.maxLength * NEAR_LIMIT);
|
|
1224
|
+
};
|
|
1136
1225
|
const resizeInput = () => {
|
|
1137
1226
|
input.style.height = "auto";
|
|
1138
1227
|
input.style.height = `${input.scrollHeight}px`;
|
|
@@ -1143,18 +1232,26 @@ function bindChat(root, options = {}) {
|
|
|
1143
1232
|
if (!question || session.status !== "idle") return;
|
|
1144
1233
|
input.value = "";
|
|
1145
1234
|
resizeInput();
|
|
1235
|
+
updateCounter();
|
|
1146
1236
|
for (const node of initialNodes) node.remove();
|
|
1237
|
+
for (const list of chatThread.querySelectorAll("[data-ai-chat-follow-ups]")) list.remove();
|
|
1238
|
+
followUps = [];
|
|
1147
1239
|
appendMarkdown(appendMessage("user"), question);
|
|
1148
1240
|
activeAssistant = appendMessage("assistant");
|
|
1149
1241
|
activeText = null;
|
|
1150
1242
|
activeTextContent = "";
|
|
1151
1243
|
pendingTool = tool("pending", "");
|
|
1152
|
-
|
|
1153
|
-
|
|
1244
|
+
setBusy(true);
|
|
1245
|
+
const assistant = activeAssistant;
|
|
1154
1246
|
const result = await session.send(question);
|
|
1155
|
-
|
|
1156
|
-
|
|
1247
|
+
if (destroyed) return;
|
|
1248
|
+
setBusy(false);
|
|
1157
1249
|
if (result.error && !result.canceled) report(result.error);
|
|
1250
|
+
if (!result.error && assistant.isConnected && assistant.childNodes.length) {
|
|
1251
|
+
appendReplyActions(assistant, result.turn);
|
|
1252
|
+
appendFollowUps(assistant, followUps);
|
|
1253
|
+
}
|
|
1254
|
+
focusInput();
|
|
1158
1255
|
if (result.canceled) activeAssistant?.querySelectorAll(`[data-ai-chat-tool]:not(.${part("tool--done")})`).forEach((item) => {
|
|
1159
1256
|
finishToolElement(item, false, true);
|
|
1160
1257
|
});
|
|
@@ -1167,6 +1264,20 @@ function bindChat(root, options = {}) {
|
|
|
1167
1264
|
submit();
|
|
1168
1265
|
return;
|
|
1169
1266
|
}
|
|
1267
|
+
if (target?.closest("[data-ai-chat-stop]")) {
|
|
1268
|
+
session.cancel();
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
const copy = target?.closest("[data-ai-chat-copy]");
|
|
1272
|
+
if (copy) {
|
|
1273
|
+
copyReply(copy).catch(report);
|
|
1274
|
+
return;
|
|
1275
|
+
}
|
|
1276
|
+
const feedback = target?.closest("[data-ai-chat-feedback]");
|
|
1277
|
+
if (feedback) {
|
|
1278
|
+
sendFeedback(feedback).catch(report);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1170
1281
|
if (target?.closest("[data-ai-chat-reset]")) {
|
|
1171
1282
|
session.reset();
|
|
1172
1283
|
chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
|
|
@@ -1177,8 +1288,11 @@ function bindChat(root, options = {}) {
|
|
|
1177
1288
|
activeText = null;
|
|
1178
1289
|
activeTextContent = "";
|
|
1179
1290
|
pendingTool = null;
|
|
1291
|
+
followUps = [];
|
|
1180
1292
|
formContexts.clear();
|
|
1181
1293
|
startConversation();
|
|
1294
|
+
updateCounter();
|
|
1295
|
+
focusInput();
|
|
1182
1296
|
return;
|
|
1183
1297
|
}
|
|
1184
1298
|
const actionElement = target?.closest("[data-ai-action]");
|
|
@@ -1250,7 +1364,12 @@ function bindChat(root, options = {}) {
|
|
|
1250
1364
|
listen(form, "submit", submit);
|
|
1251
1365
|
listen(root, "click", click);
|
|
1252
1366
|
listen(input, "keydown", keydown);
|
|
1253
|
-
listen(input, "input",
|
|
1367
|
+
listen(input, "input", () => {
|
|
1368
|
+
resizeInput();
|
|
1369
|
+
updateCounter();
|
|
1370
|
+
});
|
|
1371
|
+
setBusy(false);
|
|
1372
|
+
updateCounter();
|
|
1254
1373
|
followAnswer();
|
|
1255
1374
|
trackKeyboard();
|
|
1256
1375
|
trackOffset();
|