@vettvangur/ai-sdk 0.4.0 → 0.4.1
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 +16 -5
- package/dist/index.d.ts +9 -0
- package/dist/index.js +136 -9
- package/package.json +1 -1
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
|
@@ -12,6 +12,7 @@ type AiChatContext = Record<string, string>;
|
|
|
12
12
|
type AiChatSessionStatus = 'idle' | 'sending' | 'disposed';
|
|
13
13
|
type AiChatSessionResult = {
|
|
14
14
|
provider: string | null;
|
|
15
|
+
turn: string | null;
|
|
15
16
|
canceled: boolean;
|
|
16
17
|
error: Error | null;
|
|
17
18
|
};
|
|
@@ -102,10 +103,16 @@ type AiChatStreamEvent = {
|
|
|
102
103
|
name: string;
|
|
103
104
|
isError: boolean;
|
|
104
105
|
};
|
|
106
|
+
} | {
|
|
107
|
+
name: 'suggestions';
|
|
108
|
+
data: {
|
|
109
|
+
suggestions: string[];
|
|
110
|
+
};
|
|
105
111
|
} | {
|
|
106
112
|
name: 'done';
|
|
107
113
|
data: {
|
|
108
114
|
provider: string;
|
|
115
|
+
turn: string | null;
|
|
109
116
|
};
|
|
110
117
|
} | {
|
|
111
118
|
name: 'error';
|
|
@@ -114,6 +121,7 @@ type AiChatStreamEvent = {
|
|
|
114
121
|
};
|
|
115
122
|
};
|
|
116
123
|
type AiChatLabels = AiAnswerCardLabels & {
|
|
124
|
+
followUps: string;
|
|
117
125
|
error: string;
|
|
118
126
|
timeout: string;
|
|
119
127
|
toolRunning: string;
|
|
@@ -155,6 +163,7 @@ type AiChatBindings = {
|
|
|
155
163
|
timeoutMs?: number;
|
|
156
164
|
labels?: Partial<AiChatLabels>;
|
|
157
165
|
toolLabels?: Record<string, string>;
|
|
166
|
+
feedbackEndpoint?: string;
|
|
158
167
|
offsetElement?: HTMLElement | null;
|
|
159
168
|
registry?: AiChatRegistry;
|
|
160
169
|
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,23 @@ 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
692
|
const provider = stringValue(data, "provider");
|
|
693
|
+
const turn = stringValue(data, "turn");
|
|
684
694
|
return provider === null ? null : {
|
|
685
695
|
name,
|
|
686
|
-
data: {
|
|
696
|
+
data: {
|
|
697
|
+
provider,
|
|
698
|
+
turn: turn && turn.length <= MAX_TURN_TOKEN_LENGTH ? turn : null
|
|
699
|
+
}
|
|
687
700
|
};
|
|
688
701
|
}
|
|
689
702
|
case "error": {
|
|
@@ -819,6 +832,7 @@ function createChatSession(options) {
|
|
|
819
832
|
content
|
|
820
833
|
}];
|
|
821
834
|
let provider = null;
|
|
835
|
+
let turn = null;
|
|
822
836
|
let error = null;
|
|
823
837
|
let canceled = false;
|
|
824
838
|
let answer = "";
|
|
@@ -842,8 +856,10 @@ function createChatSession(options) {
|
|
|
842
856
|
if (event.name === "tool") await afterNextPaint();
|
|
843
857
|
if (event.name === "delta") answer += event.data.text;
|
|
844
858
|
else if (event.name === "tool_result" && event.data.reply) replies.push(event.data.reply);
|
|
845
|
-
else if (event.name === "done")
|
|
846
|
-
|
|
859
|
+
else if (event.name === "done") {
|
|
860
|
+
provider = event.data.provider;
|
|
861
|
+
turn = event.data.turn;
|
|
862
|
+
} else if (event.name === "error") throw new Error(event.data.message);
|
|
847
863
|
}
|
|
848
864
|
if (answer.trim()) replies = [...replies, answer.trim()];
|
|
849
865
|
history.push({
|
|
@@ -865,6 +881,7 @@ function createChatSession(options) {
|
|
|
865
881
|
}
|
|
866
882
|
return {
|
|
867
883
|
provider,
|
|
884
|
+
turn,
|
|
868
885
|
canceled,
|
|
869
886
|
error
|
|
870
887
|
};
|
|
@@ -959,8 +976,10 @@ const defaultLabels = {
|
|
|
959
976
|
sources: "Sources",
|
|
960
977
|
details: "Details",
|
|
961
978
|
table: "Published table",
|
|
962
|
-
tableScroll: "Scroll sideways to see all columns"
|
|
979
|
+
tableScroll: "Scroll sideways to see all columns",
|
|
980
|
+
followUps: "Suggested questions"
|
|
963
981
|
};
|
|
982
|
+
const NEAR_LIMIT = .9;
|
|
964
983
|
/**
|
|
965
984
|
* Every element the binding adds to the thread carries a class under this block, so a host styles
|
|
966
985
|
* the chat by class rather than by the order its elements happen to come in.
|
|
@@ -989,6 +1008,8 @@ function bindChat(root, options = {}) {
|
|
|
989
1008
|
const input = root.querySelector("[data-ai-chat-input]");
|
|
990
1009
|
const thread = root.querySelector("[data-ai-chat-thread]");
|
|
991
1010
|
const send = root.querySelector("[data-ai-chat-send]");
|
|
1011
|
+
const stop = root.querySelector("[data-ai-chat-stop]");
|
|
1012
|
+
const counter = root.querySelector("[data-ai-chat-counter]");
|
|
992
1013
|
if (!form || !input || !thread) throw new Error("AI chat shell requires form, input and thread elements");
|
|
993
1014
|
const chatThread = thread;
|
|
994
1015
|
const labels = readLabels(root, options.labels);
|
|
@@ -998,10 +1019,12 @@ function bindChat(root, options = {}) {
|
|
|
998
1019
|
const header = options.antiforgeryHeader ?? root.dataset.aiChatAntiforgeryHeader;
|
|
999
1020
|
const token = options.antiforgeryToken ?? root.dataset.aiChatAntiforgeryToken;
|
|
1000
1021
|
const headers = header && token ? { [header]: token } : void 0;
|
|
1022
|
+
const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
|
|
1001
1023
|
let activeAssistant = null;
|
|
1002
1024
|
let activeText = null;
|
|
1003
1025
|
let activeTextContent = "";
|
|
1004
1026
|
let pendingTool = null;
|
|
1027
|
+
let followUps = [];
|
|
1005
1028
|
let destroyed = false;
|
|
1006
1029
|
const formContexts = /* @__PURE__ */ new Map();
|
|
1007
1030
|
const cleanups = [];
|
|
@@ -1131,8 +1154,82 @@ function bindChat(root, options = {}) {
|
|
|
1131
1154
|
clearPendingTool();
|
|
1132
1155
|
renderResult(event);
|
|
1133
1156
|
} else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
|
|
1157
|
+
else if (event.name === "suggestions") followUps = event.data.suggestions;
|
|
1134
1158
|
else if (event.name === "done" || event.name === "error") clearPendingTool();
|
|
1135
1159
|
});
|
|
1160
|
+
function setBusy(busy) {
|
|
1161
|
+
if (busy) root.setAttribute("aria-busy", "true");
|
|
1162
|
+
else root.removeAttribute("aria-busy");
|
|
1163
|
+
if (send) {
|
|
1164
|
+
send.disabled = busy;
|
|
1165
|
+
if (stop) send.hidden = busy;
|
|
1166
|
+
}
|
|
1167
|
+
if (stop) stop.hidden = !busy;
|
|
1168
|
+
}
|
|
1169
|
+
const focusInput = () => {
|
|
1170
|
+
const view = root.ownerDocument.defaultView;
|
|
1171
|
+
const active = root.ownerDocument.activeElement;
|
|
1172
|
+
if (!view?.matchMedia?.("(pointer: fine)").matches || active && chatThread.contains(active)) return;
|
|
1173
|
+
input.focus({ preventScroll: true });
|
|
1174
|
+
};
|
|
1175
|
+
function appendFollowUps(parent, suggestions) {
|
|
1176
|
+
if (!suggestions.length) return;
|
|
1177
|
+
const list = root.ownerDocument.createElement("div");
|
|
1178
|
+
list.dataset.aiChatFollowUps = "true";
|
|
1179
|
+
list.className = part("follow-ups");
|
|
1180
|
+
list.setAttribute("role", "group");
|
|
1181
|
+
list.setAttribute("aria-label", labels.followUps);
|
|
1182
|
+
for (const suggestion of suggestions) {
|
|
1183
|
+
const button = root.ownerDocument.createElement("button");
|
|
1184
|
+
button.type = "button";
|
|
1185
|
+
button.className = part("follow-up");
|
|
1186
|
+
button.dataset.aiChatSuggestion = suggestion;
|
|
1187
|
+
button.append(root.ownerDocument.createTextNode(suggestion));
|
|
1188
|
+
list.append(button);
|
|
1189
|
+
}
|
|
1190
|
+
parent.append(list);
|
|
1191
|
+
}
|
|
1192
|
+
function appendReplyActions(parent, turn) {
|
|
1193
|
+
const template = root.querySelector("template[data-ai-chat-reply-actions]");
|
|
1194
|
+
if (!template) return;
|
|
1195
|
+
const actions = root.ownerDocument.createElement("div");
|
|
1196
|
+
actions.className = part("reply-actions");
|
|
1197
|
+
actions.append(template.content.cloneNode(true));
|
|
1198
|
+
if (turn && feedbackEndpoint) actions.dataset.aiChatTurn = turn;
|
|
1199
|
+
else for (const button of actions.querySelectorAll("[data-ai-chat-feedback]")) button.remove();
|
|
1200
|
+
if (actions.children.length) parent.append(actions);
|
|
1201
|
+
}
|
|
1202
|
+
async function copyReply(button) {
|
|
1203
|
+
const message = button.closest("[data-ai-chat-message]");
|
|
1204
|
+
const parts = Array.from(message?.querySelectorAll("[data-ai-chat-text], [data-ai-chat-card]") ?? [], (element) => (element.innerText ?? element.textContent ?? "").trim()).filter(Boolean);
|
|
1205
|
+
if (!parts.length) return;
|
|
1206
|
+
await navigator.clipboard.writeText(parts.join("\n\n"));
|
|
1207
|
+
button.dataset.aiChatCopied = "true";
|
|
1208
|
+
setTimeout(() => delete button.dataset.aiChatCopied, 2e3);
|
|
1209
|
+
}
|
|
1210
|
+
async function sendFeedback(button) {
|
|
1211
|
+
const actions = button.closest("[data-ai-chat-turn]");
|
|
1212
|
+
const rating = button.dataset.aiChatFeedback;
|
|
1213
|
+
if (!actions?.dataset.aiChatTurn || !feedbackEndpoint || rating !== "up" && rating !== "down") return;
|
|
1214
|
+
const response = await fetch(feedbackEndpoint, {
|
|
1215
|
+
method: "POST",
|
|
1216
|
+
headers: {
|
|
1217
|
+
"Content-Type": "application/json",
|
|
1218
|
+
...headers
|
|
1219
|
+
},
|
|
1220
|
+
body: JSON.stringify({
|
|
1221
|
+
turn: actions.dataset.aiChatTurn,
|
|
1222
|
+
rating
|
|
1223
|
+
})
|
|
1224
|
+
});
|
|
1225
|
+
if (!response.ok) throw new Error(`AI chat feedback failed with ${response.status}`);
|
|
1226
|
+
for (const item of actions.querySelectorAll("[data-ai-chat-feedback]")) item.setAttribute("aria-pressed", String(item === button));
|
|
1227
|
+
}
|
|
1228
|
+
const updateCounter = () => {
|
|
1229
|
+
if (!counter || input.maxLength <= 0) return;
|
|
1230
|
+
counter.textContent = `${input.value.length} / ${input.maxLength}`;
|
|
1231
|
+
counter.toggleAttribute("data-ai-chat-near-limit", input.value.length >= input.maxLength * NEAR_LIMIT);
|
|
1232
|
+
};
|
|
1136
1233
|
const resizeInput = () => {
|
|
1137
1234
|
input.style.height = "auto";
|
|
1138
1235
|
input.style.height = `${input.scrollHeight}px`;
|
|
@@ -1143,18 +1240,26 @@ function bindChat(root, options = {}) {
|
|
|
1143
1240
|
if (!question || session.status !== "idle") return;
|
|
1144
1241
|
input.value = "";
|
|
1145
1242
|
resizeInput();
|
|
1243
|
+
updateCounter();
|
|
1146
1244
|
for (const node of initialNodes) node.remove();
|
|
1245
|
+
for (const list of chatThread.querySelectorAll("[data-ai-chat-follow-ups]")) list.remove();
|
|
1246
|
+
followUps = [];
|
|
1147
1247
|
appendMarkdown(appendMessage("user"), question);
|
|
1148
1248
|
activeAssistant = appendMessage("assistant");
|
|
1149
1249
|
activeText = null;
|
|
1150
1250
|
activeTextContent = "";
|
|
1151
1251
|
pendingTool = tool("pending", "");
|
|
1152
|
-
|
|
1153
|
-
|
|
1252
|
+
setBusy(true);
|
|
1253
|
+
const assistant = activeAssistant;
|
|
1154
1254
|
const result = await session.send(question);
|
|
1155
|
-
|
|
1156
|
-
|
|
1255
|
+
if (destroyed) return;
|
|
1256
|
+
setBusy(false);
|
|
1157
1257
|
if (result.error && !result.canceled) report(result.error);
|
|
1258
|
+
if (!result.error && assistant.isConnected && assistant.childNodes.length) {
|
|
1259
|
+
appendReplyActions(assistant, result.turn);
|
|
1260
|
+
appendFollowUps(assistant, followUps);
|
|
1261
|
+
}
|
|
1262
|
+
focusInput();
|
|
1158
1263
|
if (result.canceled) activeAssistant?.querySelectorAll(`[data-ai-chat-tool]:not(.${part("tool--done")})`).forEach((item) => {
|
|
1159
1264
|
finishToolElement(item, false, true);
|
|
1160
1265
|
});
|
|
@@ -1167,6 +1272,20 @@ function bindChat(root, options = {}) {
|
|
|
1167
1272
|
submit();
|
|
1168
1273
|
return;
|
|
1169
1274
|
}
|
|
1275
|
+
if (target?.closest("[data-ai-chat-stop]")) {
|
|
1276
|
+
session.cancel();
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
1279
|
+
const copy = target?.closest("[data-ai-chat-copy]");
|
|
1280
|
+
if (copy) {
|
|
1281
|
+
copyReply(copy).catch(report);
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
const feedback = target?.closest("[data-ai-chat-feedback]");
|
|
1285
|
+
if (feedback) {
|
|
1286
|
+
sendFeedback(feedback).catch(report);
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1170
1289
|
if (target?.closest("[data-ai-chat-reset]")) {
|
|
1171
1290
|
session.reset();
|
|
1172
1291
|
chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
|
|
@@ -1177,8 +1296,11 @@ function bindChat(root, options = {}) {
|
|
|
1177
1296
|
activeText = null;
|
|
1178
1297
|
activeTextContent = "";
|
|
1179
1298
|
pendingTool = null;
|
|
1299
|
+
followUps = [];
|
|
1180
1300
|
formContexts.clear();
|
|
1181
1301
|
startConversation();
|
|
1302
|
+
updateCounter();
|
|
1303
|
+
focusInput();
|
|
1182
1304
|
return;
|
|
1183
1305
|
}
|
|
1184
1306
|
const actionElement = target?.closest("[data-ai-action]");
|
|
@@ -1250,7 +1372,12 @@ function bindChat(root, options = {}) {
|
|
|
1250
1372
|
listen(form, "submit", submit);
|
|
1251
1373
|
listen(root, "click", click);
|
|
1252
1374
|
listen(input, "keydown", keydown);
|
|
1253
|
-
listen(input, "input",
|
|
1375
|
+
listen(input, "input", () => {
|
|
1376
|
+
resizeInput();
|
|
1377
|
+
updateCounter();
|
|
1378
|
+
});
|
|
1379
|
+
setBusy(false);
|
|
1380
|
+
updateCounter();
|
|
1254
1381
|
followAnswer();
|
|
1255
1382
|
trackKeyboard();
|
|
1256
1383
|
trackOffset();
|