@boldare/askdare 0.3.0 → 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/docs/protocol.md CHANGED
@@ -12,6 +12,7 @@ Every path sits under the route's base path: `/api/chat` by default, or `basePat
12
12
  | --- | --- | --- |
13
13
  | `GET /widget.js` | None | The loader script for your pages. `?bot=<id>` adds that bot's launcher look |
14
14
  | `GET /embed/<bot>` | None | The chat document in the iframe. `?lang=<tag>` carries the embedding page's language for `locale: 'auto'`, and `?mode=inline` marks a chat inside the page |
15
+ | `GET /config/<bot>` | None | The bot's public configuration in one language, for switching the chat's language in place. `?lang=<tag>` picks the language for `locale: 'auto'` |
15
16
  | `GET /theme/<bot>.css` | None | The bot's theme and `widget.css`, with a content hash in `?v=` |
16
17
  | `GET /assets/<file>` | None | The chat's script and stylesheet, and the preset fonts |
17
18
  | `POST /session` | None | Starts or renews a visitor's session and answers an access token ([Identity](#identity)) |
@@ -24,8 +25,9 @@ Every path sits under the route's base path: `/api/chat` by default, or `basePat
24
25
  | `POST /doctor` | Doctor token | Checks the setup for `askdare doctor` ([Diagnostics](#diagnostics)) |
25
26
 
26
27
  - **`POST /messages`** takes `{ "botId", "text", "resumeToken"?, "attachments"?, "context"?, "locale"? }`. Without `resumeToken`, the server starts a new conversation and sends `conversation.created`. `locale` is the visitor's language tag, passed to the bot's instructions.
27
- - **`POST /history`** takes `{ "botId", "resumeToken" }` and answers `{ "messages": [{ "id", "role", "text", "citations", "attachments", "feedback"?, "replies"? }] }`, where `attachments` is a count, `feedback` is the answer's rating handle (see [Feedback](#feedback)) and `replies` are the options of the latest answer (see [Reply options](#reply-options)).
28
+ - **`POST /history`** takes `{ "botId", "resumeToken" }` and answers `{ "messages": [{ "id", "role", "text", "citations", "attachments", "feedback"?, "replies"?, "ui"? }] }`, where `attachments` is a count, `feedback` is the answer's rating handle (see [Feedback](#feedback)), `replies` are the options of the latest answer (see [Reply options](#reply-options)) and `ui` are the tool payloads of an answer (see [Tool UI](#tool-ui)).
28
29
  - **`DELETE /conversation`** takes the same body and answers `204` with no body.
30
+ - **`GET /config/<bot>`** answers the same public configuration the chat document carries: texts, greeting, starters, theme variants and the other widget settings, never the model, instructions, tools or vector stores. For a bot with `locale: 'auto'`, `?lang=` picks the language; without it, the browser's `Accept-Language` does, then English. A bot with a fixed locale ignores `lang`. An invalid tag answers `400` with `invalid_input`, an unknown bot `404`. Responses are cached for five minutes (`no-cache` in development) and vary by `Accept-Language`. `Content-Language` names the language the texts are written in, for the chat document's `lang`: the visitor's when the bot has texts for it, else English for a language without a built-in dictionary.
29
31
  - **Same origin only.** Every `POST` and `DELETE` except `/doctor` refuses cross-site requests with `401`. The API serves the chat's own iframe, which runs on the same origin.
30
32
 
31
33
  ## Transport
@@ -52,6 +54,7 @@ Every path sits under the route's base path: `/api/chat` by default, or `basePat
52
54
  | `text.delta` | `messageId`, `delta` | Append text to the reply (markdown) |
53
55
  | `citation` | `messageId`, `index`, `title`, `url?` | Source for marker `[index]`; `url` is http(s) only |
54
56
  | `tool.status` | `messageId`, `callId`, `name`, `state: running \| done \| error` | A tool ran; arguments and results stay on the server. `name: file_search` is the knowledge base search |
57
+ | `tool.ui` | `messageId`, `callId`, `name`, `data` | What a tool picked from its result for the visitor ([Tool UI](#tool-ui)); after the step's `tool.status` events, at most four per answer |
55
58
  | `replies` | `messageId`, `items` | Options the visitor can click instead of typing ([Reply options](#reply-options)); at most once, before `message.end` |
56
59
  | `message.end` | `messageId`, `reason`, `resumeToken?`, `feedback?` | The reply finished. A resumed conversation gets a fresh `resumeToken`, so it stays reachable 30 days after its last message. `feedback` is the answer's rating handle, when answers can be rated. Reasons: `completed`, `max_steps`, `max_output_tokens`, `timeout`, `content_filter`, `aborted` |
57
60
  | `error` | `code`, `message`, `retryAfterMs?`, `key?`, `params?` | The turn failed; `message` is safe to show ([keys and parameters](#error-keys-and-parameters)) |
@@ -89,6 +92,17 @@ An answer can offer a few options the visitor clicks instead of typing ("Yes, bo
89
92
 
90
93
  Older clients ignore the event, so it is additive in protocol version 1.
91
94
 
95
+ ## Tool UI
96
+
97
+ A tool can pick fields from its result for the visitor to see as a card, list or table, drawn by a component the site registers ([ADR-0017](https://github.com/boldare/askdare/blob/main/docs/adr/0017-tool-renderers.md)). The payload comes in a `tool.ui` event, `{ "messageId", "callId", "name", "data" }`: `callId` is the same opaque ID as in `tool.status`, `name` is the tool's name, which picks the component, and `data` is whatever the tool's `ui` function returned. The events of a step come once all its calls are done, in call order, before the model writes on. After a reload, `POST /history` returns them as `ui: [{ "callId", "name", "data" }]` on the answer they belong to, for every answer, not only the latest; a turn that ended without a visible answer has none to carry them. How to define them: [Tools](tools.md#cards-for-the-visitor).
98
+
99
+ - **Limits.** `data` is plain JSON (objects, arrays, strings, finite numbers, booleans and `null`, but not `null` alone), at most 8 KB (8,192 bytes of UTF-8 JSON) and at most 8 levels of arrays and objects. An answer carries at most four, each `callId` once. The server drops a payload that breaks a limit whole and never cuts one; clients ignore an event that breaks one, and refuse a history that does.
100
+ - **Never a failed call.** A call that failed, timed out or returned too much data sends no `tool.ui`.
101
+ - **Never as HTML.** Render `data` with your own components as text, and links through a URL check; no client renders it as Markdown or HTML.
102
+ - **A click is a message.** A component acts only by sending a visitor message through `POST /messages`, as a reply option does.
103
+
104
+ Older clients ignore the event, so it is additive in protocol version 1.
105
+
92
106
  ## Identity
93
107
 
94
108
  `POST /session` takes an optional `identityToken`: the JWT from `askdare('identify')`, or `null` to sign out. Without it, a renewal keeps the identity the previous access token had. Widgets send the page's latest token with every session request. The answer adds `identified` (boolean), `identityKey` (an HMAC that tells users apart without revealing them; widgets keep one conversation handle per key), `resumeToken` when signing in adopted an anonymous conversation, and `identityProblem` when a token was refused. A signed-in access token expires with the identity token. Identities travel inside the encrypted access token; clients never see the claims ([ADR-0009](https://github.com/boldare/askdare/blob/main/docs/adr/0009-visitor-identity.md)).
package/docs/react.md CHANGED
@@ -64,6 +64,7 @@ That is all: the components are client components already, and the chat loads it
64
64
  | `greeting`, `starters` | This page's greeting and up to 4 suggested questions, instead of the bot's. |
65
65
  | `context` | A short description of the page for the assistant, up to 1,000 characters. Only for a bot with `pageContext: true`. |
66
66
  | `onEvent` | Called with what happens in the chat, such as a message sent or an answer rated, for analytics. Metadata only. A new function doesn't restart the chat. See [Chat events](events.md). |
67
+ | `toolRenderers` | Your components for tools' results, by tool name. `DefaultChat` and `ToolResults` draw them under the answer. See [Tool cards](#tool-cards). |
67
68
 
68
69
  `greeting`, `starters` and `context` are the same as in `askdare('configure')` and are checked the same way ([Styling](styling.md#3-page-javascript)).
69
70
 
@@ -128,6 +129,7 @@ function Bubble() {
128
129
  return (
129
130
  <Chat.Message className={message.role === 'user' ? 'mine' : 'theirs'}>
130
131
  <Chat.MessageText />
132
+ <Chat.ToolResults />
131
133
  <Chat.MessageFiles />
132
134
  <Chat.Citations />
133
135
  <Chat.FeedbackButton rating="up">👍</Chat.FeedbackButton>
@@ -174,6 +176,8 @@ Without `Theme` and `DefaultChat`, no stylesheet of the chat loads: the look is
174
176
  | `MessageText` | `div` | The text: the visitor's as typed, an answer as Markdown, typing dots before the first word. |
175
177
  | `Markdown` | none | Renders a `text` as the chat renders answers. |
176
178
  | `Citations` | `ol` | The answer's sources. |
179
+ | `ToolResults` | `div` | The answer's tool cards (`tool-result`, with `data-ask-tool`), each drawn by the component `Root`'s `toolRenderers` has for its tool, in call order. See [Tool cards](#tool-cards). |
180
+ | `Link` | `a` or `span` | A link for a URL from a tool's payload, checked as links in answers are: only `https`, `http` and `mailto`, opened in a new tab. Any other URL renders the text alone. |
177
181
  | `MessageFiles` | `ul` or `p` | The files sent with a message. |
178
182
  | `FeedbackButton` | `button` | Rates the answer; takes `rating="up"` or `"down"`. See [Answer ratings](feedback.md). |
179
183
  | `QuickReplies` | `div` | The options the latest answer offers, as a group of buttons (`reply`) that show their text as plain text. A click sends the option as the visitor's message. Inside `MessageList` it renders under the latest answer only; placed anywhere else, such as above the `Composer`, it shows the latest answer's options there. Either way they go away once the visitor sends anything. The default look follows the theme's `replies` variant ([Themes](themes.md#variants)). See [Reply options](reply-options.md#in-react). |
@@ -191,11 +195,55 @@ Primitives that have nothing to show render nothing, so you can place them witho
191
195
 
192
196
  **Never render an answer as HTML.** Model output can be steered by whatever the model reads. `MessageText` and `Markdown` turn it into elements without ever producing HTML, allow only `http`, `https` and `mailto` links, and never load images. If you render `message.text` yourself, render it as text.
193
197
 
198
+ ### Tool cards
199
+
200
+ A tool can pick what the visitor may see of its result with `ui` ([Tools](tools.md#cards-for-the-visitor)). Give `Root` a component for it, and the chat draws it under the answer, live and after a reload:
201
+
202
+ ```tsx
203
+ 'use client';
204
+ import * as Chat from '@boldare/askdare/react';
205
+ // Types only: the tool runs on the server and never reaches this bundle.
206
+ import type { findSlots } from '@/tools';
207
+
208
+ function SlotList({ data }: Chat.ToolRendererProps<typeof findSlots>) {
209
+ const { actions } = Chat.useChat();
210
+ return (
211
+ <ul className="slots">
212
+ {data.slots.map((slot) => (
213
+ <li key={slot}>
214
+ <button type="button" onClick={() => void actions.send(`Book ${slot}`)}>
215
+ {slot}
216
+ </button>
217
+ </li>
218
+ ))}
219
+ </ul>
220
+ );
221
+ }
222
+
223
+ const toolRenderers = { find_slots: SlotList } satisfies Chat.ToolRenderers<[typeof findSlots]>;
224
+
225
+ export function Help({ config }: { config: Chat.ChatConfig }) {
226
+ return (
227
+ <Chat.Root config={config} toolRenderers={toolRenderers}>
228
+ <Chat.DefaultChat className="help-chat" />
229
+ </Chat.Root>
230
+ );
231
+ }
232
+ ```
233
+
234
+ - **A component gets `{ data, name, callId }`.** `data` is what the tool's `ui` returned, typed from the tool with `ToolRendererProps<typeof tool>`. `satisfies ToolRenderers<[…]>` checks each component against its tool's payload and the tool names; `Root` also takes a plain map without types. Everything else comes from the hooks.
235
+ - **Render `data` as text.** React escapes it. Never pass it to `dangerouslySetInnerHTML`, and put URLs from it in `Chat.Link`, which drops `javascript:` and every other scheme but `https`, `http` and `mailto`. Load images only from URLs your tool builds itself, never from the model's arguments: an image URL can carry data out if a prompt injection steers the model.
236
+ - **To act, send a message.** `actions.send(text)` sends the visitor's own words, exactly as if they had typed them; the model decides what happens, as always. A card can't run a tool or anything else by itself.
237
+ - **No component, no card.** A tool without one shows nothing (the answer's text still tells the result), and the console says so once per tool. If a component throws, its card is left out and the chat goes on.
238
+ - **Placement.** `DefaultChat` puts the cards under the answer's text. In your own markup, place `ToolResults` inside `MessageList`; style the cards yourself, with the chat's tokens (`var(--ask-color-border)` and the others) so they follow the theme.
239
+ - **The script-tag widget** draws them too, for a bot that shows your own page in its iframe: render that page with `EmbedRoot` from `@boldare/askdare/embed` and the same `toolRenderers`. See [Embedding: your own page in the iframe](embedding.md#your-own-page-in-the-iframe).
240
+
194
241
  ### Hooks
195
242
 
196
243
  - **`useChat()`** returns `{ state, actions, bot, t }` and re-renders on every change.
197
244
  - **`useChatState(select)`** returns one value and re-renders only when it changes: `useChatState((state) => state.busy)`. Return a value from the state, not a new object.
198
245
  - **`useMessage()`** returns the message being rendered, inside `MessageList`.
246
+ - **`useFrame()`** returns `{ close }` inside `EmbedRoot`, on your own page in the widget's iframe, and `null` everywhere else. `close` asks the widget to close its panel (undefined for an inline chat). The default look, ejected or not, uses it to become the page's main landmark with a close button; your own markup can use it for its close button. See [Embedding](embedding.md#your-own-page-in-the-iframe).
199
247
 
200
248
  | `state` | Meaning |
201
249
  | --- | --- |
@@ -283,5 +331,5 @@ The copy imports only `@boldare/askdare/react`, so `Root`, the hooks and the pri
283
331
  - **Server rendering.** The chat renders on the server in its starting state, with the greeting and suggestions, and connects after hydration. A stored conversation appears then.
284
332
  - **Several chats on a page** work, each in its own `Root`, also for different bots with different themes.
285
333
  - **One conversation per bot and browser**, shared by every page that shows that bot, and by the widget on the same origin.
286
- - **Switching the language.** Call `getChatConfig` with the new `locale` and pass the result to `Root`: it starts the chat again in that language, and the conversation stays. The texts, starters and greeting change with it. An answer still streaming disappears from view, `onEvent` gets `message.received` with `outcome: 'stopped'`, and the server still finishes and stores it. Only a bot with `locale: 'auto'` switches; see [Texts](texts.md#switching-the-language-on-the-page).
287
- - **Sizes** (gzipped, in your bundle): about 28 KB for everything, about 8 KB when you use only `Root` and the hooks. The Markdown renderer is loaded only if you render `MessageText` or `Markdown`.
334
+ - **Switching the language.** Call `getChatConfig` with the new `locale` and pass the result to `Root`: the same chat switches to that language's texts, greeting and placeholder, and the conversation, the unsent message and an answer still streaming stay. Another bot or `basePath` starts another chat. Only a bot with `locale: 'auto'` switches; see [Texts](texts.md#switching-the-language-on-the-page).
335
+ - **Sizes** (gzipped, in your bundle): about 32 KB for everything, about 10 KB when you use only `Root` and the hooks. The Markdown renderer is loaded only if you render `MessageText` or `Markdown`.
package/docs/styling.md CHANGED
@@ -66,7 +66,7 @@ A full example is the demo site's BLDR theme, in Boldare's style: `defineTheme`
66
66
 
67
67
  The launcher's short variables on your page (`--a`, `--o` and the like) are internal too.
68
68
 
69
- **Parts** (`[data-ask-part="…"]`, public API): `panel`, `header`, `identity`, `identity-text`, `title`, `subtitle`, `actions`, `new-conversation`, `close`, `avatar`, `orb`, `messages`, `welcome`, `greeting`, `starters`, `starter`, `persona`, `persona-name`, `presence`, `intro`, `intro-card`, `message`, `message-body`, `bubble`, `image-alt`, `typing`, `citations`, `citation`, `attachments-note`, the rating of an answer: `feedback`, `feedback-button`, `feedback-comment`, `feedback-comment-input`, `feedback-comment-actions`, `feedback-skip`, `feedback-send`, the options under the latest answer: `replies`, `reply`, then `status`, `error`, `composer`, `composer-box`, `input`, `attach`, `voice`, `send`, `attachments`, `message-attachments`, `attachment`, `attachment-preview`, `attachment-badge`, `attachment-name`, `attachment-status`, `attachment-remove`, `recorder`, `recorder-level`, `recorder-label`, `recorder-time`, `recorder-cancel`, `recorder-done`, `send-label` (shown by Aura), `disclosure`, and the question before a new conversation: `confirm-backdrop`, `confirm`, `confirm-icon`, `confirm-text`, `confirm-actions`, `confirm-cancel`, `confirm-accept`.
69
+ **Parts** (`[data-ask-part="…"]`, public API): `panel`, `header`, `identity`, `identity-text`, `title`, `subtitle`, `actions`, `new-conversation`, `close`, `avatar`, `orb`, `messages`, `welcome`, `greeting`, `starters`, `starter`, `persona`, `persona-name`, `presence`, `intro`, `intro-card`, `message`, `message-body`, `bubble`, `image-alt`, `typing`, `citations`, `citation`, `attachments-note`, the rating of an answer: `feedback`, `feedback-button`, `feedback-comment`, `feedback-comment-input`, `feedback-comment-actions`, `feedback-skip`, `feedback-send`, the options under the latest answer: `replies`, `reply`, the cards of an answer's tools: `tool-results`, `tool-result`, then `status`, `error`, `composer`, `composer-box`, `input`, `attach`, `voice`, `send`, `attachments`, `message-attachments`, `attachment`, `attachment-preview`, `attachment-badge`, `attachment-name`, `attachment-status`, `attachment-remove`, `recorder`, `recorder-level`, `recorder-label`, `recorder-time`, `recorder-cancel`, `recorder-done`, `send-label` (shown by Aura), `disclosure`, and the question before a new conversation: `confirm-backdrop`, `confirm`, `confirm-icon`, `confirm-text`, `confirm-actions`, `confirm-cancel`, `confirm-accept`.
70
70
 
71
71
  `identity-text` holds the title and subtitle in the header. `image-alt` stands in for an image in a reply: the chat never loads images that the model writes, so it shows their alt text in brackets.
72
72
 
@@ -82,6 +82,7 @@ The launcher's short variables on your page (`--a`, `--o` and the like) are inte
82
82
  | `attachment` | `data-kind` | `image`, `pdf`; absent until the chat has recognized the file |
83
83
  | `recorder` | `data-state` | `recording`, `transcribing` |
84
84
  | `feedback-button` | `data-rating` | `up`, `down`; `aria-pressed="true"` on the visitor's rating |
85
+ | `tool-result` | `data-ask-tool` | The name of the tool whose card it holds |
85
86
  | `replies` | `data-placement` | `composer` on the row above the message field (variant `replies: 'composer'`); absent under an answer |
86
87
  | `avatar` | `data-kind` | `orb`, `icon`, `initials`, `image` |
87
88
  | `avatar` | `data-size` | `small` in the header, next to the assistant's messages and in the `intro` welcome; `large` in the `hero` and `persona` welcome |
@@ -171,7 +172,7 @@ Every preset sets both font tokens, so set both. You can also set them as the `f
171
172
  <script src="https://app.example.com/api/chat/widget.js?bot=support" async></script>
172
173
  ```
173
174
 
174
- `locale` is a BCP 47 tag, such as `'pl'`, and the server checks it against the bot like any language. It reloads the chat in that language and keeps the conversation; a call with only `locale` leaves the greeting, suggestions and context as they were. To follow your page's `<html lang>` instead, add `data-follow-lang` to the script tag. See [Texts](texts.md#switching-the-language-on-the-page).
175
+ `locale` is a BCP 47 tag, such as `'pl'`, and the server checks it against the bot like any language. It switches the chat to that language in place and keeps the conversation; a call with only `locale` leaves the greeting, suggestions and context as they were. To follow your page's `<html lang>` instead, add `data-follow-lang` to the script tag. See [Texts](texts.md#switching-the-language-on-the-page).
175
176
 
176
177
  An inline chat loads with the page without taking focus or scrolling to itself.
177
178
 
package/docs/texts.md CHANGED
@@ -24,7 +24,7 @@ defineBot({
24
24
 
25
25
  - **Keys.** Only the keys in the table below are accepted. An unknown key, or a text that is empty or longer than 300 characters, makes `defineBot` throw at startup.
26
26
  - **Shortcuts.** `title`, `greeting`, `placeholder` and `launcherLabel` set `header.title`, `welcome.greeting`, `composer.placeholder` and `launcher.label`. If you set a shortcut and the same key in `texts`, the shortcut wins.
27
- - **Every language.** An override replaces the text in every language. With `locale: 'auto'`, Polish visitors see your override too.
27
+ - **Every language.** An override replaces the text in every language. With `locale: 'auto'`, Polish visitors see your override too. For different texts in each language, use [texts per language](#texts-per-language).
28
28
  - **Placeholders.** Words in braces, such as `{count}`, `{name}`, `{size}` and `{max}`, are filled in by the widget. Keep the ones the default text has. A placeholder the widget doesn't fill for that key is shown as typed.
29
29
  - **Bold.** In `welcome.greeting`, `**words**` are shown in bold.
30
30
 
@@ -45,6 +45,29 @@ A page can still set its own greeting with `askdare('configure', { greeting })`;
45
45
 
46
46
  With `'auto'`, the launcher on your page follows the same order. Your `instructions` function receives the chosen tag as `context.locale`, so you can tell the model which language to answer in.
47
47
 
48
+ ### Texts per language
49
+
50
+ With `locale: 'auto'`, give `widget.texts` one set of overrides per language instead:
51
+
52
+ ```ts
53
+ defineBot({
54
+ // …
55
+ widget: {
56
+ locale: 'auto',
57
+ texts: {
58
+ en: { 'launcher.label': 'Questions?', 'welcome.greeting': 'Hi! How can I help?' },
59
+ pl: { 'launcher.label': 'Pytania?', 'welcome.greeting': 'Cześć! W czym pomóc?' },
60
+ },
61
+ },
62
+ });
63
+ ```
64
+
65
+ - **Which set a visitor gets.** The set for their language tag (`pl-PL`), else one for the same language (`pl`, or another `pl-…` set). A language without a built-in dictionary, such as French, shows English, so it gets the `en` set. A language with a dictionary but no set of yours, such as Polish without `pl`, shows the built-in Polish texts.
66
+ - **The launcher on your page** follows the same sets, by language: a German page shows your `de` launcher texts, the rest in English.
67
+ - **Shortcuts.** `title`, `greeting`, `placeholder` and `launcherLabel` still apply in every language, but a set that gives the same key wins for its language.
68
+ - **Keys and tags.** The keys are checked as in the flat form. Each language must be a valid BCP 47 tag, once (`pl` and `PL` are the same language), and at most 20 languages are allowed.
69
+ - **One form or the other.** `texts` is either one set for every language or one set per language, not both.
70
+
48
71
  ### Switching the language on the page
49
72
 
50
73
  A site that switches its language without a page load, such as a single-page app with a language menu, can switch the chat too:
@@ -52,7 +75,9 @@ A site that switches its language without a page load, such as a single-page app
52
75
  - **`data-follow-lang`** on the script tag makes the chat follow the page's `<html lang>` whenever it changes.
53
76
  - **`askdare('configure', { locale: 'pl' })`** switches it from your own code. It wins over `data-follow-lang` until the page's `lang` changes again.
54
77
 
55
- The launcher's texts change at once, and the chat reloads in the new language. The visitor keeps their conversation: earlier answers stay in the language they were written in, and new answers and the interface follow the switch. Your `instructions` function gets the new tag as `context.locale` from the next message on. The reload loads the conversation again, which takes about as long as opening the chat. An answer still streaming disappears from view, and the page hears `message.received` with `outcome: 'stopped'` ([Chat events](events.md)); the server still finishes and stores it.
78
+ The launcher's texts change at once, and the chat switches in place, without reloading. The visitor keeps their conversation, their unsent message and an answer still streaming, which finishes as usual. Earlier answers stay in the language they were written in; new answers and the interface follow the switch. Your `instructions` function gets the new tag as `context.locale` from the next message on.
79
+
80
+ If the chat can't load the new texts, or the switch happens before the chat has connected, it reloads in the new language instead and keeps the conversation. An answer still streaming then disappears from view, and the page hears `message.received` with `outcome: 'stopped'` ([Chat events](events.md)); the server still finishes and stores it.
56
81
 
57
82
  Only a bot with `locale: 'auto'` switches. A bot with a fixed locale keeps its language, and the console says once that it ignored the change. The value is a BCP 47 tag; anything else is ignored with a console warning.
58
83
 
@@ -90,7 +115,7 @@ Setting the same language again does nothing.
90
115
 
91
116
  A call with only `locale` keeps the greeting, starters and page context of earlier `configure` calls. Next to `data-follow-lang`, your call wins until the page's `lang` changes again.
92
117
 
93
- **In React.** `Root` starts the chat again when the `locale` of its config changes, and the conversation stays ([React](react.md#good-to-know)). Read the language in a Server Component, for example from a `[lang]` segment:
118
+ **In React.** When only the `locale` of its config changes, `Root` switches the same chat to the new texts, and the conversation, the unsent message and an answer under way stay ([React](react.md#good-to-know)). Read the language in a Server Component, for example from a `[lang]` segment:
94
119
 
95
120
  ```tsx
96
121
  // app/[lang]/help/page.tsx
@@ -156,7 +181,7 @@ To see the categories of another language, run `new Intl.PluralRules('cs').resol
156
181
 
157
182
  ## Add a language
158
183
 
159
- The library has dictionaries for English and Polish only, and `widget.texts` has no per-language form. For another language, set a fixed `locale` and translate every key:
184
+ The library has dictionaries for English and Polish only. For another language, translate every key, either for a bot with a fixed `locale`:
160
185
 
161
186
  ```ts
162
187
  defineBot({
@@ -176,8 +201,8 @@ defineBot({
176
201
 
177
202
  - Keys you leave out show English.
178
203
  - Plurals follow the rules of the tag you set, so translate each category the language uses.
179
- - Keep `locale` fixed. With `'auto'`, your translations would show to every visitor, whatever their language. For a site in several languages without a dictionary, define one bot per language, each with its own `locale` and `texts`.
180
- - The chat document's `lang` attribute is your `locale` as soon as `widget.texts` has any key, so screen readers read your translation in the right language. Without your texts, a language without a built-in dictionary shows English, and `lang` says `en`.
204
+ - With `'auto'`, put the translation in its own set (`texts: { de: { … } }`, see [texts per language](#texts-per-language)). Flat texts would show to every visitor, whatever their language.
205
+ - The chat document's `lang` attribute is the visitor's language when a set of yours exists for it, or your fixed `locale` as soon as flat `widget.texts` has any key, so screen readers read your translation in the right language. Without your texts, a language without a built-in dictionary shows English, and `lang` says `en`.
181
206
 
182
207
  ## All texts
183
208
 
package/docs/tools.md CHANGED
@@ -63,6 +63,26 @@ export const orderStatus = defineTool({
63
63
 
64
64
  [Reply options](reply-options.md) has more flows, options in several languages, and when to let the model suggest options instead.
65
65
 
66
+ ## Cards for the visitor
67
+
68
+ A tool can also pick what the visitor may see of its result, for a card, a list or a table that your own React component draws under the answer ([ADR-0017](https://github.com/boldare/askdare/blob/main/docs/adr/0017-tool-renderers.md)):
69
+
70
+ ```ts
71
+ export const findSlots = defineTool({
72
+ name: 'find_slots',
73
+ description: 'Free consultation slots on a day.',
74
+ input: z.object({ day: z.string() }),
75
+ execute: async ({ day }) => calendar.freeSlots(day),
76
+ ui: (result) => ({ day: result.day, slots: result.slots.map((slot) => slot.start) }),
77
+ });
78
+ ```
79
+
80
+ - **Only what `ui` returns reaches the browser,** never the result itself. Pick the fields a visitor may see: no internal IDs, costs or notes, nothing about other customers. The visitor can read the payload in their browser even where no component shows it.
81
+ - **Keep `ui` pure.** It gets the result as the model received it, parsed back from JSON (a `Date` is a string by then), and runs again on every reload to bring the card back. The same result must give the same payload; a reload after a deploy shows what your current `ui` returns.
82
+ - **Limits.** Return plain JSON of at most 8 KB and 8 levels of arrays and objects, or `undefined` or `null` for no card. A payload over a limit is dropped whole and the tool's name is logged. An answer shows at most 4, in call order. A call that failed, timed out or returned too much data shows none. If `ui` throws, the answer comes without that card and the error is logged.
83
+ - **The model still sees the whole result** and writes about it as usual. If the card should speak for itself, say so in the tool's description or the bot's instructions.
84
+ - **Drawing the card** is your React component, registered with `Root`'s `toolRenderers` in the chat inside your page ([Tool cards](react.md#tool-cards)). The payload's type comes from `ui`, and the tool's name stays a literal, so a page types its components from the tool with `import type`. In the script-tag widget, a bot draws them when its iframe shows your own page (`embedPath`, [Embedding](embedding.md#your-own-page-in-the-iframe)); askdare's own iframe page has no components to draw them with.
85
+
66
86
  ## Rules
67
87
 
68
88
  - **Every field is required.** OpenAI's strict mode demands it: use `.nullable()` instead of `.optional()`. `defineTool` fails at startup otherwise.
package/llms.txt CHANGED
@@ -8,17 +8,17 @@ Set it up with `npx @boldare/askdare init` and verify it with `npx @boldare/askd
8
8
 
9
9
  - [Getting started](docs/getting-started.md): install, `init`, `.env.local`, `doctor`, embedding on other sites
10
10
  - [Configuration](docs/configuration.md): every `defineBot` and `createChatHandler` option, limits with defaults, environment variables
11
- - [Embedding](docs/embedding.md): the script tag and its `data-*` attributes, several bots, the host page's CSP, staging and production
11
+ - [Embedding](docs/embedding.md): the script tag and its `data-*` attributes, several bots, the host page's CSP, your own page in the widget's iframe (`embedPath`, `EmbedRoot`, `embedPageHeaders`), staging and production
12
12
  - [CLI](docs/cli.md): `init`, `doctor`, `kb sync`, `add ui` and `usage`, with every flag
13
13
  - [Troubleshooting](docs/troubleshooting.md): symptoms, causes and fixes, by error code
14
- - [Tools](docs/tools.md): `defineTool`, Zod schemas, what a tool may trust
14
+ - [Tools](docs/tools.md): `defineTool`, Zod schemas, what a tool may trust, and `ui`: what the visitor sees of a result as a card
15
15
  - [Reply options](docs/reply-options.md): clickable answers under the latest reply, suggested by the model (`widget.replies: 'suggest'`) or defined by a tool (`defineTool({ replies })`), limits, placement, cost
16
16
  - [Signed-in visitors](docs/identity.md): `askdare('identify')`, IDENTITY_SECRET, `context.identity`
17
17
  - [Knowledge base](docs/knowledge-base.md): `npx @boldare/askdare kb sync`, vector stores, citations
18
18
  - [Attachments](docs/attachments.md): images and PDFs from visitors
19
19
  - [Voice input](docs/voice-input.md): dictation and its limits
20
20
  - [Styling](docs/styling.md): texts, languages, AI disclosure, custom CSS, `askdare('open' | 'configure')`, inline mode
21
- - [React](docs/react.md): the chat inside a page of your own app with `@boldare/askdare/react`: `getChatConfig`, `Root`, `DefaultChat`, hooks and primitives, CSS resets, CSP, `add ui`
21
+ - [React](docs/react.md): the chat inside a page of your own app with `@boldare/askdare/react`: `getChatConfig`, `Root`, `DefaultChat`, hooks and primitives, tool cards (`toolRenderers`, `ToolResults`, `Link`), CSS resets, CSP, `add ui`
22
22
  - [Texts](docs/texts.md): every text key with its English and Polish default, plurals, adding a language, switching the chat's language on the page (`askdare('configure', { locale })`, `data-follow-lang`)
23
23
  - [Themes](docs/themes.md): Halo, Aura, Sage and Care, tokens and variants
24
24
  - [Deployment](docs/deployment.md): Vercel, Heroku, proxies, shared limits
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boldare/askdare",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Embeddable AI chatbot for Next.js, as a script-tag widget or React components, built on the official OpenAI SDK.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -49,6 +49,10 @@
49
49
  "types": "./dist/react.d.ts",
50
50
  "default": "./dist/react.js"
51
51
  },
52
+ "./embed": {
53
+ "types": "./dist/embed.d.ts",
54
+ "default": "./dist/embed.js"
55
+ },
52
56
  "./package.json": "./package.json"
53
57
  },
54
58
  "types": "./dist/index.d.ts",
@@ -75,14 +79,14 @@
75
79
  "@types/react": "^19.3.0",
76
80
  "@types/react-dom": "^19.3.0",
77
81
  "happy-dom": "^21.0.4",
78
- "marked": "18.1.3",
79
- "next": "^16.4.5",
82
+ "marked": "18.2.0",
83
+ "next": "^16.4.6",
80
84
  "preact": "11.2.0",
81
85
  "publint": "^0.3.25",
82
86
  "react": "^19.3.1",
83
87
  "react-dom": "^19.3.1",
84
88
  "tsdown": "^0.23.7",
85
- "vite": "^8.3.6",
89
+ "vite": "^8.3.8",
86
90
  "zod": "^4.6.7"
87
91
  },
88
92
  "peerDependencies": {
@@ -99,8 +103,8 @@
99
103
  }
100
104
  },
101
105
  "dependencies": {
102
- "jose": "^6.2.15",
103
- "openai": "^7.52.0"
106
+ "jose": "^6.2.17",
107
+ "openai": "^7.56.0"
104
108
  },
105
109
  "scripts": {
106
110
  "build:assets": "vite build -c vite.widget.config.ts && vite build -c vite.skin.config.ts && vite build -c vite.loader.config.ts && node scripts/inline-assets.mjs",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: askdare
3
- description: Add, configure or troubleshoot the @boldare/askdare AI chat in a Next.js app (defineBot, defineTool, createChatHandler, the widget script, the React chat inside a page, themes, knowledge base, reply options, the chat's language, answer ratings, usage reports, deployment). Use when the project depends on @boldare/askdare or the user asks for a website chatbot built on it.
3
+ description: Add, configure or troubleshoot the @boldare/askdare AI chat in a Next.js app (defineBot, defineTool, createChatHandler, the widget script, the React chat inside a page, tool cards, your own page in the widget's iframe, themes, knowledge base, reply options, the chat's language, answer ratings, usage reports, deployment). Use when the project depends on @boldare/askdare or the user asks for a website chatbot built on it.
4
4
  ---
5
5
 
6
6
  # askdare
@@ -22,6 +22,8 @@ description: Add, configure or troubleshoot the @boldare/askdare AI chat in a Ne
22
22
  - The chat's language on the page, for a bot with `locale: 'auto'`: `askdare('configure', { locale: 'pl' })`, or `data-follow-lang` on the script tag to follow `<html lang>`. The chat reloads in the new language and keeps the conversation; your `instructions` get it as `context.locale`. See `docs/texts.md`.
23
23
  - Reply options (clickable answers under the latest reply): `widget.replies: 'suggest'` lets the model suggest them; `defineTool({ replies: (result) => [...] })` derives them from a tool's result. See `docs/reply-options.md`.
24
24
  - The chat inside a page of the same Next.js app (React 19): `getChatConfig` from `@boldare/askdare/next` in a Server Component, then `Root`, `DefaultChat`, the hooks (`useChat`, `useChatState`, `useMessage`) and the primitives from `@boldare/askdare/react` (see `docs/react.md`). To change the default components, run `npx @boldare/askdare add ui`; don't copy them from `node_modules` by hand.
25
+ - Tool cards: `defineTool({ ui: (result) => data })` picks what the visitor may see of a result (plain JSON, at most 8 KB; only that reaches the browser), and `Root`'s `toolRenderers={{ tool_name: Component }}` draws it, typed with `Chat.ToolRendererProps<typeof tool>` and `import type`. Render `data` as text and URLs through `Chat.Link`. See `docs/react.md#tool-cards`.
26
+ - Your own page in the widget's iframe: `defineBot({ embedPath: '/askdare/support' })`; the page lives in its own route group and root layout, renders `<EmbedRoot config={getEmbedConfig({ bots, bot, searchParams })}>` from `@boldare/askdare/embed` with `DefaultChat` inside, and gets `embedPageHeaders({ bots, bot })` from `proxy.ts` (not `next.config.ts` headers, which are fixed at build). Check with `askdare doctor --origin <site>`. See `docs/embedding.md#your-own-page-in-the-iframe`.
25
27
  - Styling: `widget.texts`, `widget.theme`, `widget.css` with `[data-ask-part="…"]` selectors and `--ask-*` tokens (see `docs/styling.md`).
26
28
 
27
29
  Never import from `@boldare/askdare/dist/…` or other internal paths.
@@ -37,6 +39,7 @@ Never import from `@boldare/askdare/dist/…` or other internal paths.
37
39
  - With `@boldare/askdare/react`: never render `message.text` as HTML (use `MessageText` or `Markdown`); sign a visitor out with `identity={null}`, since `undefined` keeps the current one; a page that passes `identity` must not be cached; on pages with third-party scripts, prefer the script-tag widget.
38
40
  - Tools: every Zod field is required (use `.nullable()`, not `.optional()`). Never take user IDs, emails or permissions from tool arguments; use the verified `context` (`visitorId`, `botId`, `locale`, `identity`, `signal`). Keep tools read-only.
39
41
  - Signed-in users: the site's backend signs an HS256 JWT with `IDENTITY_SECRET` (`sub`, `aud` = bot ID, `iat`, `exp`), and the page calls `askdare('identify', token)` (`null` on sign-out). See `docs/identity.md`.
42
+ - Tool cards: `ui` must be pure (it runs again on every reload) and must return only fields a visitor may see; never render its `data` as HTML, and load images only from URLs the tool builds itself.
40
43
  - Reply options: at most 4, up to 80 characters each, plain text without links; anything else is dropped. A click only sends the option's text as the visitor's message, so write options the way a visitor would say them ("Cancel the order"), never as commands or IDs, and never treat a clicked option as more trusted than typed text.
41
44
  - More than one server instance (Vercel, several dynos) needs shared limits: `@boldare/askdare-upstash`.
42
45
  - Answer ratings (👍/👎) show only with `createChatHandler({ onFeedback })`; `widget.feedback: false` hides them for one bot. askdare stores no ratings: save the report in `onFeedback`. A rating's `comment` is visitor text: escape it wherever it is shown, and cover it in the privacy notice. See `docs/feedback.md`.