@vettvangur/ai-sdk 0.2.1 → 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 CHANGED
@@ -3,7 +3,7 @@
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
- a DOM binding for a server-rendered shell, and generic cards a host can draw tool results with. It
6
+ a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool results with. It
7
7
  ships no styles: every element it renders carries a BEM class, and the project styles those.
8
8
 
9
9
  ```html
@@ -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, and `__error`.
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
@@ -80,21 +91,16 @@ value is not the payload's `key` field. Register it with `registry.registerSurfa
80
91
 
81
92
  ## Cards
82
93
 
83
- A host maps a tool's payload onto these and registers the result as that tool's renderer. Each
84
- returns null when there is nothing to show.
94
+ Each returns null when there is nothing to show. Cards for a project's own payloads belong to the
95
+ project; build them with the helpers below rather than adding them here.
85
96
 
86
- - `renderContactCard` (`vv-ai-contact-card`): name, subtitle, image (such as a flag), address, phone
87
- and email links, and labelled groups of hours. Parts: `__head`, `__image`, `__title`, `__name`,
88
- `__subtitle`, `__address`, `__links`, `__link`, `__hours`, `__hours-label`, `__hours-row`,
89
- `__hours-days`, `__hours-time`, `__hours-note`.
90
- - `renderMediaCard` (`vv-ai-media-card`, `--with-image`): a title and facts led by an image. Parts:
91
- `__figure`, `__image`, `__body`, `__title`, `__facts`, `__fact`, `__fact-label`, `__fact-value`.
92
97
  - `renderActions` (`vv-ai-actions`): buttons that run a registered action and safe links, each
93
98
  `__action` with `--primary` or `--secondary`.
94
99
  - `renderCardList` (`vv-ai-card-list`, `--{modifier}`): several cards from one result.
95
100
 
96
- `createSafeImage`, `createSafeLink` and `createPart` are the builders these use, exported for a
97
- host's own renderers.
101
+ `createSafeImage` (web and site-relative URLs only, with srcset and size when given),
102
+ `createSafeLink` (the `isSafeLinkUrl` rule, new tab for web URLs) and `createPart` (an element with
103
+ a BEM class and text) are exported for a host's own renderers.
98
104
 
99
105
  ## Answer cards
100
106
 
@@ -113,6 +119,6 @@ of plain fields. Style by these classes rather than by element order.
113
119
  plain text; a link belongs in `links`, `actions` or `sources`. `isSafeLinkUrl()` is the rule every
114
120
  link passes, exported so a host's own renderers can apply it too.
115
121
 
116
- The package accepts protocol-v1 events (`delta`, `tool`, `tool_result`, `tool_done`, `done`, and
117
- `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
118
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;
@@ -174,29 +183,6 @@ type AiCardImage = {
174
183
  width?: number | null;
175
184
  height?: number | null;
176
185
  };
177
- type AiContactCardHoursRow = {
178
- label: string;
179
- value: string;
180
- note?: string | null;
181
- };
182
- type AiContactCardHours = {
183
- label?: string | null;
184
- rows: AiContactCardHoursRow[];
185
- };
186
- type AiContactCard = {
187
- name: string;
188
- subtitle?: string | null;
189
- image?: AiCardImage | null;
190
- address?: string | null;
191
- phone?: string | null;
192
- email?: string | null;
193
- hours?: AiContactCardHours[] | null;
194
- };
195
- type AiMediaCard = {
196
- title: string;
197
- image?: AiCardImage | null;
198
- facts?: AiAnswerCardFact[] | null;
199
- };
200
186
  type AiChatActionItem = {
201
187
  label: string;
202
188
  action?: string | null;
@@ -245,24 +231,12 @@ declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBi
245
231
  //#region src/cards.d.ts
246
232
  /** Block classes of the cards below. Every element a card renders carries a class under its block. */
247
233
  declare const CARD_LIST_CLASS = "vv-ai-card-list";
248
- declare const CONTACT_CARD_CLASS = "vv-ai-contact-card";
249
- declare const MEDIA_CARD_CLASS = "vv-ai-media-card";
250
234
  declare const ACTIONS_CLASS = "vv-ai-actions";
251
235
  /**
252
236
  * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
253
237
  * Items that render nothing are skipped, and a list with nothing in it is null.
254
238
  */
255
239
  declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
256
- /**
257
- * A place or person to get in touch with: name, an optional subtitle and image (such as a flag),
258
- * address, phone and email links, and any number of labelled groups of hours. Null without a name.
259
- */
260
- declare function renderContactCard(document: Document, data: unknown): HTMLElement | null;
261
- /**
262
- * A thing best recognised by its picture, with labelled facts beside it. The image leads, and the
263
- * card carries `--with-image` when it has one. Null without a title.
264
- */
265
- declare function renderMediaCard(document: Document, data: unknown): HTMLElement | null;
266
240
  /**
267
241
  * A row of things the visitor can do next. An item with `action` is a button that runs the action
268
242
  * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
@@ -303,4 +277,4 @@ declare function readEventStream(response: Response, signal: AbortSignal): Async
303
277
  */
304
278
  declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: AiChatExtensionContext) => DocumentFragment | null;
305
279
  //#endregion
306
- 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 AiContactCard, type AiContactCardHours, type AiContactCardHoursRow, type AiMediaCard, type AiTemplateItemSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, CONTACT_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, MEDIA_CARD_CLASS, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderContactCard, renderMediaCard };
280
+ 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
@@ -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: { provider }
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") provider = event.data.provider;
846
- else if (event.name === "error") throw new Error(event.data.message);
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
- root.setAttribute("aria-busy", "true");
1153
- if (send) send.disabled = true;
1252
+ setBusy(true);
1253
+ const assistant = activeAssistant;
1154
1254
  const result = await session.send(question);
1155
- root.removeAttribute("aria-busy");
1156
- if (send) send.disabled = false;
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", resizeInput);
1375
+ listen(input, "input", () => {
1376
+ resizeInput();
1377
+ updateCounter();
1378
+ });
1379
+ setBusy(false);
1380
+ updateCounter();
1254
1381
  followAnswer();
1255
1382
  trackKeyboard();
1256
1383
  trackOffset();
@@ -1286,8 +1413,6 @@ function bindChat(root, options = {}) {
1286
1413
  //#region src/cards.ts
1287
1414
  /** Block classes of the cards below. Every element a card renders carries a class under its block. */
1288
1415
  const CARD_LIST_CLASS = "vv-ai-card-list";
1289
- const CONTACT_CARD_CLASS = "vv-ai-contact-card";
1290
- const MEDIA_CARD_CLASS = "vv-ai-media-card";
1291
1416
  const ACTIONS_CLASS = "vv-ai-actions";
1292
1417
  function text(value) {
1293
1418
  return typeof value === "string" && value.trim() ? value : null;
@@ -1305,90 +1430,6 @@ function renderCardList(document, items, render, modifier) {
1305
1430
  list.append(...cards);
1306
1431
  return list;
1307
1432
  }
1308
- function appendHours(document, card, hours) {
1309
- const rows = Array.isArray(hours.rows) ? hours.rows.filter((row) => isPlainObject(row) && text(row.value)) : [];
1310
- if (!rows.length) return;
1311
- const block = createPart(document, "div", CONTACT_CARD_CLASS, "hours");
1312
- const label = text(hours.label);
1313
- if (label) block.append(createPart(document, "span", CONTACT_CARD_CLASS, "hours-label", label));
1314
- for (const row of rows) {
1315
- const line = createPart(document, "div", CONTACT_CARD_CLASS, "hours-row");
1316
- const time = createPart(document, "span", CONTACT_CARD_CLASS, "hours-time", row.value);
1317
- const note = text(row.note);
1318
- if (note) time.append(" ", createPart(document, "span", CONTACT_CARD_CLASS, "hours-note", note));
1319
- line.append(createPart(document, "span", CONTACT_CARD_CLASS, "hours-days", text(row.label)), time);
1320
- block.append(line);
1321
- }
1322
- card.append(block);
1323
- }
1324
- /**
1325
- * A place or person to get in touch with: name, an optional subtitle and image (such as a flag),
1326
- * address, phone and email links, and any number of labelled groups of hours. Null without a name.
1327
- */
1328
- function renderContactCard(document, data) {
1329
- if (!isPlainObject(data)) return null;
1330
- const contact = data;
1331
- const name = text(contact.name);
1332
- if (!name) return null;
1333
- const card = createPart(document, "article", CONTACT_CARD_CLASS);
1334
- const head = createPart(document, "header", CONTACT_CARD_CLASS, "head");
1335
- const image = createSafeImage(document, contact.image);
1336
- if (image) {
1337
- image.className = `${CONTACT_CARD_CLASS}__image`;
1338
- head.append(image);
1339
- }
1340
- const title = createPart(document, "span", CONTACT_CARD_CLASS, "title");
1341
- title.append(createPart(document, "span", CONTACT_CARD_CLASS, "name", name));
1342
- const subtitle = text(contact.subtitle);
1343
- if (subtitle) title.append(createPart(document, "span", CONTACT_CARD_CLASS, "subtitle", subtitle));
1344
- head.append(title);
1345
- card.append(head);
1346
- const address = text(contact.address);
1347
- if (address) card.append(createPart(document, "p", CONTACT_CARD_CLASS, "address", address));
1348
- const links = createPart(document, "p", CONTACT_CARD_CLASS, "links");
1349
- const phone = text(contact.phone);
1350
- const email = text(contact.email);
1351
- for (const link of [phone ? createSafeLink(document, phone, `tel:${phone.replace(/[^+\d]/g, "")}`) : null, email ? createSafeLink(document, email, `mailto:${email.trim()}`) : null]) if (link) {
1352
- link.className = `${CONTACT_CARD_CLASS}__link`;
1353
- links.append(link);
1354
- }
1355
- if (links.children.length) card.append(links);
1356
- for (const hours of Array.isArray(contact.hours) ? contact.hours : []) if (isPlainObject(hours)) appendHours(document, card, hours);
1357
- return card;
1358
- }
1359
- /**
1360
- * A thing best recognised by its picture, with labelled facts beside it. The image leads, and the
1361
- * card carries `--with-image` when it has one. Null without a title.
1362
- */
1363
- function renderMediaCard(document, data) {
1364
- if (!isPlainObject(data)) return null;
1365
- const media = data;
1366
- const title = text(media.title);
1367
- if (!title) return null;
1368
- const card = createPart(document, "article", MEDIA_CARD_CLASS);
1369
- const image = createSafeImage(document, media.image);
1370
- if (image) {
1371
- image.className = `${MEDIA_CARD_CLASS}__image`;
1372
- const figure = createPart(document, "div", MEDIA_CARD_CLASS, "figure");
1373
- figure.append(image);
1374
- card.classList.add(`${MEDIA_CARD_CLASS}--with-image`);
1375
- card.append(figure);
1376
- }
1377
- const body = createPart(document, "div", MEDIA_CARD_CLASS, "body");
1378
- body.append(createPart(document, "h3", MEDIA_CARD_CLASS, "title", title));
1379
- const facts = (Array.isArray(media.facts) ? media.facts : []).filter((fact) => isPlainObject(fact) && text(fact.value));
1380
- if (facts.length) {
1381
- const list = createPart(document, "div", MEDIA_CARD_CLASS, "facts");
1382
- for (const fact of facts) {
1383
- const row = createPart(document, "div", MEDIA_CARD_CLASS, "fact");
1384
- row.append(createPart(document, "span", MEDIA_CARD_CLASS, "fact-label", text(fact.label)), createPart(document, "span", MEDIA_CARD_CLASS, "fact-value", fact.value));
1385
- list.append(row);
1386
- }
1387
- body.append(list);
1388
- }
1389
- card.append(body);
1390
- return card;
1391
- }
1392
1433
  /**
1393
1434
  * A row of things the visitor can do next. An item with `action` is a button that runs the action
1394
1435
  * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
@@ -1444,4 +1485,4 @@ function createTemplateItemSurface(options) {
1444
1485
  };
1445
1486
  }
1446
1487
  //#endregion
1447
- export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, CONTACT_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, MEDIA_CARD_CLASS, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderContactCard, renderMediaCard };
1488
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.2.1",
3
+ "version": "0.4.1",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",