@boldare/askdare 0.3.0-rc.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/CHANGELOG.md +38 -0
- package/README.md +2 -2
- package/dist/cli.js +92 -20
- package/dist/define-tool.js +334 -6
- package/dist/embed.d.ts +19 -0
- package/dist/embed.js +249 -0
- package/dist/index.js +1 -166
- package/dist/next.d.ts +51 -1
- package/dist/next.js +259 -59
- package/dist/react-marked.js +648 -624
- package/dist/react.d.ts +41 -75
- package/dist/react.js +24 -1838
- package/dist/root.js +2122 -0
- package/dist/store.d.ts +43 -9
- package/dist/tool-results.d.ts +130 -0
- package/dist/ui/askdare.css +13 -1
- package/dist/ui/avatar.tsx +1 -1
- package/dist/ui/chat.tsx +1 -1
- package/dist/ui/confirm.tsx +1 -1
- package/dist/ui/context.ts +1 -1
- package/dist/ui/feedback.tsx +1 -1
- package/dist/ui/footer.tsx +1 -1
- package/dist/ui/header.tsx +1 -1
- package/dist/ui/icons.tsx +1 -1
- package/dist/ui/index.ts +1 -1
- package/dist/ui/message.tsx +6 -4
- package/dist/ui/panel.tsx +15 -6
- package/dist/ui/welcome.tsx +1 -1
- package/docs/cli.md +1 -0
- package/docs/configuration.md +11 -0
- package/docs/costs.md +1 -1
- package/docs/embedding.md +102 -0
- package/docs/events.md +1 -1
- package/docs/privacy.md +1 -1
- package/docs/protocol.md +15 -1
- package/docs/react.md +50 -2
- package/docs/styling.md +3 -2
- package/docs/texts.md +31 -6
- package/docs/tools.md +20 -0
- package/llms.txt +3 -3
- package/package.json +10 -6
- package/skills/askdare/SKILL.md +4 -1
package/dist/root.js
ADDED
|
@@ -0,0 +1,2122 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { t as O } from "./react-marked.js";
|
|
3
|
+
import { Component, createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
5
|
+
// src/react/context.tsx
|
|
6
|
+
const StoreContext = createContext(null);
|
|
7
|
+
/** Set by `EmbedRoot`; null in a chat inside a page. */
|
|
8
|
+
const FrameContext = createContext(null);
|
|
9
|
+
/**
|
|
10
|
+
* Inside `EmbedRoot`, on your own page in the widget's iframe (ADR-0018): the chat is the whole
|
|
11
|
+
* document, and `close` asks the loader to close the panel (undefined in `inline` mode or when the
|
|
12
|
+
* page isn't in the widget). Null everywhere else. Your own markup uses it for a close button.
|
|
13
|
+
*/
|
|
14
|
+
function useFrame() {
|
|
15
|
+
return useContext(FrameContext);
|
|
16
|
+
}
|
|
17
|
+
const MessageContext = createContext(null);
|
|
18
|
+
/** Provides a chat store to the primitives below. `Root` creates one; the iframe brings its own. */
|
|
19
|
+
function ChatProvider({ store, children }) {
|
|
20
|
+
return /* @__PURE__ */ jsx(StoreContext.Provider, {
|
|
21
|
+
value: store,
|
|
22
|
+
children
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** The store of the surrounding chat. Throws outside `Root`, with a hint. */
|
|
26
|
+
function useStore() {
|
|
27
|
+
const store = useContext(StoreContext);
|
|
28
|
+
if (!store) throw new Error("[askdare] Chat components must be inside <Root>.");
|
|
29
|
+
return store;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The chat's texts in its current language. Re-renders when the language switches in place
|
|
33
|
+
* (ADR-0014), which components reading `useStore().t` would miss.
|
|
34
|
+
*/
|
|
35
|
+
function useTexts() {
|
|
36
|
+
const store = useStore();
|
|
37
|
+
const read = () => store.t;
|
|
38
|
+
return useSyncExternalStore(store.subscribe, read, read);
|
|
39
|
+
}
|
|
40
|
+
/** The chat's public configuration, current after a language switch in place. */
|
|
41
|
+
function useChatConfig() {
|
|
42
|
+
const store = useStore();
|
|
43
|
+
const read = () => store.config;
|
|
44
|
+
return useSyncExternalStore(store.subscribe, read, read);
|
|
45
|
+
}
|
|
46
|
+
/** The chat's state; re-renders on every change. */
|
|
47
|
+
function useSnapshot(store) {
|
|
48
|
+
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
|
|
49
|
+
}
|
|
50
|
+
/** The whole chat: its state, actions, bot settings and texts. Re-renders on every change. */
|
|
51
|
+
function useChat() {
|
|
52
|
+
const store = useStore();
|
|
53
|
+
const state = useSnapshot(store);
|
|
54
|
+
const { config } = store;
|
|
55
|
+
const { page } = state;
|
|
56
|
+
const bot = useMemo(() => ({
|
|
57
|
+
id: config.botId,
|
|
58
|
+
title: config.widget.title,
|
|
59
|
+
subtitle: config.widget.subtitle,
|
|
60
|
+
greeting: page.greeting ?? config.widget.greeting,
|
|
61
|
+
starters: page.starters ?? config.widget.starters,
|
|
62
|
+
placeholder: config.widget.placeholder,
|
|
63
|
+
avatar: config.widget.avatar,
|
|
64
|
+
locale: config.widget.locale,
|
|
65
|
+
disclosure: config.widget.disclosure,
|
|
66
|
+
preset: config.widget.preset,
|
|
67
|
+
variants: config.widget.variants,
|
|
68
|
+
attachments: config.attachments,
|
|
69
|
+
maxDictationSeconds: config.voice?.maxSeconds,
|
|
70
|
+
texts: config.widget.texts
|
|
71
|
+
}), [config, page]);
|
|
72
|
+
return {
|
|
73
|
+
state,
|
|
74
|
+
actions: store.actions,
|
|
75
|
+
bot,
|
|
76
|
+
t: store.t
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* One value from the chat's state, such as `useChatState((state) => state.busy)`. Re-renders only
|
|
81
|
+
* when that value changes, so return a primitive or a part of the state, not a new object.
|
|
82
|
+
*/
|
|
83
|
+
function useChatState(select) {
|
|
84
|
+
const store = useStore();
|
|
85
|
+
return useSyncExternalStore(store.subscribe, () => select(store.getSnapshot()), () => select(store.getServerSnapshot()));
|
|
86
|
+
}
|
|
87
|
+
/** Provides one message to the components inside `MessageList`. */
|
|
88
|
+
function MessageProvider({ message, children }) {
|
|
89
|
+
return /* @__PURE__ */ jsx(MessageContext.Provider, {
|
|
90
|
+
value: message,
|
|
91
|
+
children
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/** The message being rendered, or null outside `MessageList`. */
|
|
95
|
+
function useOptionalMessage() {
|
|
96
|
+
return useContext(MessageContext);
|
|
97
|
+
}
|
|
98
|
+
/** The message being rendered, inside `MessageList`. */
|
|
99
|
+
function useMessage() {
|
|
100
|
+
const message = useContext(MessageContext);
|
|
101
|
+
if (!message) throw new Error("[askdare] useMessage() works only inside <MessageList>.");
|
|
102
|
+
return message;
|
|
103
|
+
}
|
|
104
|
+
// src/chat/prepare-file.ts
|
|
105
|
+
/** Longest image edge sent to the model; larger photos only cost upload time. */
|
|
106
|
+
const MAX_EDGE = 2048;
|
|
107
|
+
const JPEG_QUALITY = .85;
|
|
108
|
+
const IMAGE_NAME = /\.(png|jpe?g|webp|gif|heic|heif|avif|bmp)$/i;
|
|
109
|
+
var UnsupportedFileError = class extends Error {};
|
|
110
|
+
const isPdf = (file) => file.type === "application/pdf" || /\.pdf$/i.test(file.name);
|
|
111
|
+
const isImage = (file) => file.type.startsWith("image/") && file.type !== "image/svg+xml" || IMAGE_NAME.test(file.name);
|
|
112
|
+
const baseName = (name) => name.replace(/\.[^.]*$/, "") || "image";
|
|
113
|
+
/** The `accept` attribute for the file picker. */
|
|
114
|
+
function acceptTypes(allowed) {
|
|
115
|
+
return [...allowed.images ? [
|
|
116
|
+
"image/png",
|
|
117
|
+
"image/jpeg",
|
|
118
|
+
"image/webp",
|
|
119
|
+
"image/gif",
|
|
120
|
+
"image/heic"
|
|
121
|
+
] : [], ...allowed.pdf ? ["application/pdf"] : []].join(",");
|
|
122
|
+
}
|
|
123
|
+
async function encodeJpeg(bitmap, width, height) {
|
|
124
|
+
const canvas = document.createElement("canvas");
|
|
125
|
+
canvas.width = width;
|
|
126
|
+
canvas.height = height;
|
|
127
|
+
const context = canvas.getContext("2d");
|
|
128
|
+
if (!context) throw new UnsupportedFileError();
|
|
129
|
+
context.fillStyle = "#fff";
|
|
130
|
+
context.fillRect(0, 0, width, height);
|
|
131
|
+
context.drawImage(bitmap, 0, 0, width, height);
|
|
132
|
+
return new Promise((resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(new UnsupportedFileError()), "image/jpeg", JPEG_QUALITY));
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Gets a file ready to upload. Images are decoded, downsized and re-encoded as JPEG in the
|
|
136
|
+
* browser, which drops EXIF data such as the GPS position and turns HEIC photos into a format
|
|
137
|
+
* OpenAI accepts (where the browser can decode HEIC). PDFs are sent as they are.
|
|
138
|
+
*/
|
|
139
|
+
async function prepareFile(file, allowed) {
|
|
140
|
+
if (allowed.pdf && isPdf(file)) return {
|
|
141
|
+
blob: file,
|
|
142
|
+
name: file.name,
|
|
143
|
+
kind: "pdf"
|
|
144
|
+
};
|
|
145
|
+
if (!allowed.images || !isImage(file)) throw new UnsupportedFileError();
|
|
146
|
+
let bitmap;
|
|
147
|
+
try {
|
|
148
|
+
bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
|
|
149
|
+
} catch {
|
|
150
|
+
throw new UnsupportedFileError();
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
|
|
154
|
+
const width = Math.max(1, Math.round(bitmap.width * scale));
|
|
155
|
+
const height = Math.max(1, Math.round(bitmap.height * scale));
|
|
156
|
+
return {
|
|
157
|
+
blob: await encodeJpeg(bitmap, width, height),
|
|
158
|
+
name: `${baseName(file.name)}.jpg`,
|
|
159
|
+
kind: "image"
|
|
160
|
+
};
|
|
161
|
+
} finally {
|
|
162
|
+
bitmap.close();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// src/chat/state.ts
|
|
166
|
+
/** Whether the draft, or the files ready to go, can be sent now. */
|
|
167
|
+
function canSend(state) {
|
|
168
|
+
return state.phase === "ready" && !state.busy && !state.files.some((file) => file.status === "uploading") && (state.draft.trim() !== "" || state.files.some((file) => file.status === "ready"));
|
|
169
|
+
}
|
|
170
|
+
// src/i18n/format.ts
|
|
171
|
+
/** Text helpers the widget needs; the dictionaries stay on the server. */
|
|
172
|
+
/** Fills `{name}` placeholders. */
|
|
173
|
+
function formatText(template, params = {}) {
|
|
174
|
+
return template.replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match);
|
|
175
|
+
}
|
|
176
|
+
/** A plural text such as `message.attachments` for a count, by the locale's plural rules. */
|
|
177
|
+
function pluralText(texts, base, count, locale) {
|
|
178
|
+
let category = "other";
|
|
179
|
+
try {
|
|
180
|
+
category = new Intl.PluralRules(locale).select(count);
|
|
181
|
+
} catch {}
|
|
182
|
+
return formatText(texts[`${base}.${category}`] ?? texts[`${base}.other`] ?? "", { count });
|
|
183
|
+
}
|
|
184
|
+
// src/react/markdown.tsx
|
|
185
|
+
const SAFE_PROTOCOLS = /* @__PURE__ */ new Set([
|
|
186
|
+
"http:",
|
|
187
|
+
"https:",
|
|
188
|
+
"mailto:"
|
|
189
|
+
]);
|
|
190
|
+
/**
|
|
191
|
+
* Deeper nesting than any real answer needs. Past it, the rest shows as plain text: a prompt-
|
|
192
|
+
* injected answer of `>>>>…` or `- - - …` must not blow the stack and take the chat down with it.
|
|
193
|
+
*/
|
|
194
|
+
const MAX_DEPTH = 16;
|
|
195
|
+
/** Keeps only http(s) and mailto links; everything else (javascript:, data:, relative) is dropped. */
|
|
196
|
+
function safeUrl(url) {
|
|
197
|
+
try {
|
|
198
|
+
const parsed = new URL(url);
|
|
199
|
+
return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : "";
|
|
200
|
+
} catch {
|
|
201
|
+
return "";
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const NAMED = {
|
|
205
|
+
amp: "&",
|
|
206
|
+
lt: "<",
|
|
207
|
+
gt: ">",
|
|
208
|
+
quot: "\"",
|
|
209
|
+
apos: "'",
|
|
210
|
+
nbsp: "\xA0",
|
|
211
|
+
copy: "©",
|
|
212
|
+
reg: "®",
|
|
213
|
+
trade: "™",
|
|
214
|
+
hellip: "…",
|
|
215
|
+
mdash: "—",
|
|
216
|
+
ndash: "–",
|
|
217
|
+
lsquo: "‘",
|
|
218
|
+
rsquo: "’",
|
|
219
|
+
ldquo: "“",
|
|
220
|
+
rdquo: "”",
|
|
221
|
+
laquo: "«",
|
|
222
|
+
raquo: "»",
|
|
223
|
+
bull: "•",
|
|
224
|
+
middot: "·",
|
|
225
|
+
deg: "°",
|
|
226
|
+
plusmn: "±",
|
|
227
|
+
times: "×",
|
|
228
|
+
divide: "÷",
|
|
229
|
+
euro: "€",
|
|
230
|
+
pound: "£",
|
|
231
|
+
yen: "¥",
|
|
232
|
+
cent: "¢",
|
|
233
|
+
sect: "§",
|
|
234
|
+
para: "¶"
|
|
235
|
+
};
|
|
236
|
+
/**
|
|
237
|
+
* marked leaves character references for an HTML renderer to decode; we render text, so decode
|
|
238
|
+
* them here: numeric ones and the common named ones (others stay as written). Safe, because the
|
|
239
|
+
* result is only ever text or a URL that `safeUrl` checks after decoding.
|
|
240
|
+
*/
|
|
241
|
+
function decodeEntities(text) {
|
|
242
|
+
if (!text.includes("&")) return text;
|
|
243
|
+
return text.replace(/&(#\d{1,7}|#[xX][\da-fA-F]{1,6}|[a-zA-Z]{2,8});/g, (match, entity) => {
|
|
244
|
+
if (entity[0] !== "#") return NAMED[entity] ?? match;
|
|
245
|
+
const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
|
|
246
|
+
return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
/** Inline tokens: text, emphasis, code, links. HTML is dropped, images are never loaded. */
|
|
250
|
+
function inline(tokens, depth) {
|
|
251
|
+
if (depth > MAX_DEPTH) return [(tokens ?? []).map((token) => token.raw).join("")];
|
|
252
|
+
return (tokens ?? []).map((token, key) => {
|
|
253
|
+
switch (token.type) {
|
|
254
|
+
case "text": return "tokens" in token && token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
|
|
255
|
+
case "escape": return token.text;
|
|
256
|
+
case "strong": return /* @__PURE__ */ jsx("strong", { children: inline(token.tokens, depth + 1) }, key);
|
|
257
|
+
case "em": return /* @__PURE__ */ jsx("em", { children: inline(token.tokens, depth + 1) }, key);
|
|
258
|
+
case "del": return /* @__PURE__ */ jsx("del", { children: inline(token.tokens, depth + 1) }, key);
|
|
259
|
+
case "codespan": return /* @__PURE__ */ jsx("code", { children: token.text }, key);
|
|
260
|
+
case "br": return /* @__PURE__ */ jsx("br", {}, key);
|
|
261
|
+
case "link": {
|
|
262
|
+
const href = safeUrl(decodeEntities(token.href));
|
|
263
|
+
return href ? /* @__PURE__ */ jsx("a", {
|
|
264
|
+
href,
|
|
265
|
+
target: "_blank",
|
|
266
|
+
rel: "noopener noreferrer nofollow",
|
|
267
|
+
children: inline(token.tokens, depth + 1)
|
|
268
|
+
}, key) : /* @__PURE__ */ jsx("span", { children: inline(token.tokens, depth + 1) }, key);
|
|
269
|
+
}
|
|
270
|
+
case "image": return token.text ? /* @__PURE__ */ jsxs("span", {
|
|
271
|
+
"data-ask-part": "image-alt",
|
|
272
|
+
children: [
|
|
273
|
+
"[",
|
|
274
|
+
decodeEntities(token.text),
|
|
275
|
+
"]"
|
|
276
|
+
]
|
|
277
|
+
}, key) : null;
|
|
278
|
+
default: return null;
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
function cells(row, header, depth) {
|
|
283
|
+
return row.map((cell, key) => {
|
|
284
|
+
return /* @__PURE__ */ jsx(header ? "th" : "td", {
|
|
285
|
+
style: cell.align ? { textAlign: cell.align } : void 0,
|
|
286
|
+
children: inline(cell.tokens, depth + 1)
|
|
287
|
+
}, key);
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
function blocks(tokens, depth) {
|
|
291
|
+
if (depth > MAX_DEPTH) return [tokens.map((token) => token.raw).join("")];
|
|
292
|
+
return tokens.map((token, key) => {
|
|
293
|
+
switch (token.type) {
|
|
294
|
+
case "paragraph": return /* @__PURE__ */ jsx("p", { children: inline(token.tokens, depth + 1) }, key);
|
|
295
|
+
case "text": return token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
|
|
296
|
+
case "heading": {
|
|
297
|
+
const Heading = `h${Math.min(Math.max(token.depth, 1), 6)}`;
|
|
298
|
+
return /* @__PURE__ */ jsx(Heading, { children: inline(token.tokens, depth + 1) }, key);
|
|
299
|
+
}
|
|
300
|
+
case "code": return /* @__PURE__ */ jsx("pre", { children: /* @__PURE__ */ jsx("code", { children: token.text }) }, key);
|
|
301
|
+
case "blockquote": return /* @__PURE__ */ jsx("blockquote", { children: blocks(token.tokens ?? [], depth + 1) }, key);
|
|
302
|
+
case "hr": return /* @__PURE__ */ jsx("hr", {}, key);
|
|
303
|
+
case "list": {
|
|
304
|
+
const items = token.items.map((item, index) => /* @__PURE__ */ jsxs("li", { children: [item.task && /* @__PURE__ */ jsx("input", {
|
|
305
|
+
type: "checkbox",
|
|
306
|
+
checked: item.checked ?? false,
|
|
307
|
+
disabled: true
|
|
308
|
+
}), blocks(item.tokens.filter((child) => child.type !== "checkbox"), depth + 1)] }, index));
|
|
309
|
+
return token.ordered ? /* @__PURE__ */ jsx("ol", {
|
|
310
|
+
start: typeof token.start === "number" ? token.start : void 0,
|
|
311
|
+
children: items
|
|
312
|
+
}, key) : /* @__PURE__ */ jsx("ul", { children: items }, key);
|
|
313
|
+
}
|
|
314
|
+
case "table": return /* @__PURE__ */ jsxs("table", { children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: cells(token.header, true, depth) }) }), /* @__PURE__ */ jsx("tbody", { children: token.rows.map((row, index) => /* @__PURE__ */ jsx("tr", { children: cells(row, false, depth) }, index)) })] }, key);
|
|
315
|
+
default: return null;
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/** The text as paragraphs, when markdown can't be had. */
|
|
320
|
+
const plain = (text) => text.split(/\n{2,}/).map((paragraph, key) => /* @__PURE__ */ jsx("p", { children: paragraph }, key));
|
|
321
|
+
function render(text) {
|
|
322
|
+
try {
|
|
323
|
+
return blocks(O.lex(text, { gfm: true }), 0);
|
|
324
|
+
} catch {
|
|
325
|
+
return plain(text);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
/** Shows the plain text if rendering a message ever fails, so one answer can't break the chat. */
|
|
329
|
+
var Fallback = class extends Component {
|
|
330
|
+
state = { failed: false };
|
|
331
|
+
static getDerivedStateFromError() {
|
|
332
|
+
return { failed: true };
|
|
333
|
+
}
|
|
334
|
+
render() {
|
|
335
|
+
return this.state.failed ? plain(this.props.text) : this.props.children;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
const Markdown = /* @__PURE__ */ memo(function Markdown({ text }) {
|
|
339
|
+
return /* @__PURE__ */ jsx(Fallback, {
|
|
340
|
+
text,
|
|
341
|
+
children: render(text)
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
// src/base-path.ts
|
|
345
|
+
/**
|
|
346
|
+
* Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
|
|
347
|
+
* origin, a relative path or anything that needs escaping (ADR-0011). The server, the React entry
|
|
348
|
+
* and the CLI each bundle their own copy.
|
|
349
|
+
*/
|
|
350
|
+
function isBasePath(value) {
|
|
351
|
+
return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
|
|
352
|
+
}
|
|
353
|
+
// src/i18n/locale.ts
|
|
354
|
+
/** The canonical form of a BCP 47 tag that Intl accepts (plural rules need it), else undefined. */
|
|
355
|
+
function canonicalLocale(tag) {
|
|
356
|
+
if (tag.length > 35) return void 0;
|
|
357
|
+
try {
|
|
358
|
+
return Intl.getCanonicalLocales(tag)[0];
|
|
359
|
+
} catch {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
// src/chat/page-options.ts
|
|
364
|
+
const MAX_CONTEXT = 1e3;
|
|
365
|
+
const JWT = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
366
|
+
/**
|
|
367
|
+
* A JWT-shaped string, or null to sign out; the server verifies it. Any other string signs out
|
|
368
|
+
* too, so a broken token never leaves the previous user signed in.
|
|
369
|
+
*/
|
|
370
|
+
function identityToken(value) {
|
|
371
|
+
if (value === null) return null;
|
|
372
|
+
if (typeof value !== "string") return void 0;
|
|
373
|
+
if (value.length <= 4096 && JWT.test(value)) return value;
|
|
374
|
+
console.warn("[askdare] askdare('identify') got something that isn't a JWT; signing out.");
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* The canonical form of the language a page asks for, with askdare('configure', { locale }) or
|
|
379
|
+
* its `<html lang>`, else undefined. Only a hint: the server checks it against the bot again.
|
|
380
|
+
*/
|
|
381
|
+
function pageLocale(value) {
|
|
382
|
+
return typeof value === "string" ? canonicalLocale(value) : void 0;
|
|
383
|
+
}
|
|
384
|
+
/** Keeps only the allowed fields, trimmed and within their limits. */
|
|
385
|
+
function pageOptions(data) {
|
|
386
|
+
const greeting = typeof data["greeting"] === "string" ? data["greeting"].trim() : "";
|
|
387
|
+
const starters = Array.isArray(data["starters"]) ? data["starters"].filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0 && item.length <= 80).slice(0, 4) : void 0;
|
|
388
|
+
const context = typeof data["context"] === "string" ? data["context"].trim() : "";
|
|
389
|
+
return {
|
|
390
|
+
...greeting && greeting.length <= 500 ? { greeting } : {},
|
|
391
|
+
...starters ? { starters } : {},
|
|
392
|
+
...context ? { context: context.slice(0, MAX_CONTEXT) } : {}
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
// src/protocol/events.ts
|
|
396
|
+
/** Stable error codes sent to clients. The accompanying message never contains internals. */
|
|
397
|
+
const ERROR_CODES = [
|
|
398
|
+
"invalid_input",
|
|
399
|
+
"unauthorized",
|
|
400
|
+
"session_expired",
|
|
401
|
+
"not_found",
|
|
402
|
+
"rate_limited",
|
|
403
|
+
"budget_exceeded",
|
|
404
|
+
"bot_unavailable",
|
|
405
|
+
"content_blocked",
|
|
406
|
+
"timeout",
|
|
407
|
+
"upstream_error",
|
|
408
|
+
"internal_error"
|
|
409
|
+
];
|
|
410
|
+
const MESSAGE_END_REASONS = [
|
|
411
|
+
"completed",
|
|
412
|
+
"max_steps",
|
|
413
|
+
"max_output_tokens",
|
|
414
|
+
"timeout",
|
|
415
|
+
"content_filter",
|
|
416
|
+
"aborted"
|
|
417
|
+
];
|
|
418
|
+
const PROTOCOL_EVENT_TYPES = [
|
|
419
|
+
"conversation.created",
|
|
420
|
+
"user.ack",
|
|
421
|
+
"message.start",
|
|
422
|
+
"reasoning",
|
|
423
|
+
"text.delta",
|
|
424
|
+
"citation",
|
|
425
|
+
"tool.status",
|
|
426
|
+
"tool.ui",
|
|
427
|
+
"replies",
|
|
428
|
+
"message.end",
|
|
429
|
+
"error"
|
|
430
|
+
];
|
|
431
|
+
/**
|
|
432
|
+
* A URL or something a browser or a chat app would turn into a link: a scheme (`https://`,
|
|
433
|
+
* `mailto:`, `javascript:` …), `www.`, an IP address or a domain name such as `example.com`.
|
|
434
|
+
* Strict on purpose: a few odd names (`Node.js`) are dropped with them.
|
|
435
|
+
*/
|
|
436
|
+
const LINK = /[a-z][a-z\d+.-]*:\/\/|\b(?:mailto|tel|sms|javascript|vbscript|data|file):|\bwww\.|\b\d{1,3}(?:\.\d{1,3}){3}\b|[\p{L}\d-]\.[a-z]{2,}(?![\p{L}\d])/iu;
|
|
437
|
+
/**
|
|
438
|
+
* Characters the visitor can't see or read: line breaks and other control characters, format
|
|
439
|
+
* characters (bidirectional overrides that reorder text, zero-width characters, tag characters
|
|
440
|
+
* that can spell hidden words), private-use and unassigned code points. A click sends the option
|
|
441
|
+
* as the visitor's own message, so it must say exactly what they read. The zero-width joiner stays
|
|
442
|
+
* for emoji built from several, such as "woman technologist".
|
|
443
|
+
*/
|
|
444
|
+
const CONTROL = /[\p{Cc}\p{Co}\p{Cn}\u2028\u2029]|(?!\u200d)\p{Cf}/u;
|
|
445
|
+
/** One option as it goes over the wire: trimmed, 1 to 80 characters, one line, no links. */
|
|
446
|
+
function isReplyText(value) {
|
|
447
|
+
return typeof value === "string" && value.length > 0 && value.length <= 80 && value === value.trim() && !CONTROL.test(value) && !LINK.test(value);
|
|
448
|
+
}
|
|
449
|
+
/** A list of options as it goes over the wire: 1 to 4 valid options, no duplicates. */
|
|
450
|
+
function isReplyList(value) {
|
|
451
|
+
return Array.isArray(value) && value.length > 0 && value.length <= 4 && value.every(isReplyText) && new Set(value).size === value.length;
|
|
452
|
+
}
|
|
453
|
+
/** A tool's name: what `defineTool` accepts and what the protocol carries. */
|
|
454
|
+
const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
455
|
+
/** Whether a value is plain JSON: no `undefined`, functions, class instances or `NaN`. */
|
|
456
|
+
function isPlainJson(value, depth) {
|
|
457
|
+
switch (typeof value) {
|
|
458
|
+
case "string":
|
|
459
|
+
case "boolean": return true;
|
|
460
|
+
case "number": return Number.isFinite(value);
|
|
461
|
+
case "object": {
|
|
462
|
+
if (value === null) return true;
|
|
463
|
+
if (depth >= 8) return false;
|
|
464
|
+
if (Array.isArray(value)) {
|
|
465
|
+
for (let index = 0; index < value.length; index += 1) if (!(index in value) || !isPlainJson(value[index], depth + 1)) return false;
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
const prototype = Object.getPrototypeOf(value);
|
|
469
|
+
if (prototype !== Object.prototype && prototype !== null) return false;
|
|
470
|
+
return Object.values(value).every((item) => isPlainJson(item, depth + 1));
|
|
471
|
+
}
|
|
472
|
+
default: return false;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
/** The payload's JSON, or undefined when it isn't plain JSON within the size and depth limits. */
|
|
476
|
+
function wireJson(value) {
|
|
477
|
+
if (value === null || value === void 0 || !isPlainJson(value, 0)) return void 0;
|
|
478
|
+
const json = JSON.stringify(value);
|
|
479
|
+
return new TextEncoder().encode(json).length <= 8192 ? json : void 0;
|
|
480
|
+
}
|
|
481
|
+
/** One payload as it goes over the wire: a call ID, a tool name and data within the limits. */
|
|
482
|
+
function isToolUi(value) {
|
|
483
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
484
|
+
const { callId, name, data } = value;
|
|
485
|
+
return typeof callId === "string" && callId.length > 0 && callId.length <= 128 && typeof name === "string" && TOOL_NAME.test(name) && wireJson(data) !== void 0;
|
|
486
|
+
}
|
|
487
|
+
/** A list of payloads as it goes over the wire: 1 to 4, each valid, no call twice. */
|
|
488
|
+
function isToolUiList(value) {
|
|
489
|
+
return Array.isArray(value) && value.length > 0 && value.length <= 4 && value.every(isToolUi) && new Set(value.map((item) => item.callId)).size === value.length;
|
|
490
|
+
}
|
|
491
|
+
// src/protocol/validate.ts
|
|
492
|
+
const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
493
|
+
const text = (value, min = 0, max = Number.POSITIVE_INFINITY) => typeof value === "string" && value.length >= min && value.length <= max;
|
|
494
|
+
const integer = (value, min) => typeof value === "number" && Number.isSafeInteger(value) && value >= min;
|
|
495
|
+
const oneOf = (value, options) => options.includes(value);
|
|
496
|
+
const messageId = (value) => text(value, 1, 128);
|
|
497
|
+
/** A rating handle, or undefined when the value breaks the protocol. */
|
|
498
|
+
function feedbackOf(value) {
|
|
499
|
+
return record$1(value) && text(value["handle"], 1, 4096) && typeof value["key"] === "string" && /^[0-9a-f]{16,64}$/.test(value["key"]) ? {
|
|
500
|
+
handle: value["handle"],
|
|
501
|
+
key: value["key"]
|
|
502
|
+
} : void 0;
|
|
503
|
+
}
|
|
504
|
+
/** An absolute http(s) URL as the server sends it; stricter than a browser's lenient parsing. */
|
|
505
|
+
function httpUrl(value) {
|
|
506
|
+
if (typeof value !== "string" || !/^https?:\/\/[^\s/?#]+[^\s]*$/i.test(value)) return false;
|
|
507
|
+
try {
|
|
508
|
+
const { protocol } = new URL(value);
|
|
509
|
+
return protocol === "http:" || protocol === "https:";
|
|
510
|
+
} catch {
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function citationOf(value) {
|
|
515
|
+
if (!record$1(value) || !integer(value["index"], 1) || !text(value["title"], 1)) return void 0;
|
|
516
|
+
if (value["url"] !== void 0 && !httpUrl(value["url"])) return void 0;
|
|
517
|
+
return {
|
|
518
|
+
index: value["index"],
|
|
519
|
+
title: value["title"],
|
|
520
|
+
...value["url"] === void 0 ? {} : { url: value["url"] }
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
function paramsOf(value) {
|
|
524
|
+
if (!record$1(value)) return void 0;
|
|
525
|
+
const params = {};
|
|
526
|
+
for (const [key, item] of Object.entries(value)) {
|
|
527
|
+
if (key.length > 32 || !(text(item, 0, 200) || typeof item === "number" && Number.isFinite(item))) return void 0;
|
|
528
|
+
params[key] = item;
|
|
529
|
+
}
|
|
530
|
+
return params;
|
|
531
|
+
}
|
|
532
|
+
/** A protocol event received over the wire, or undefined when it breaks the protocol. */
|
|
533
|
+
function parseEvent(value) {
|
|
534
|
+
if (!record$1(value)) return void 0;
|
|
535
|
+
const id = value["messageId"];
|
|
536
|
+
switch (value["type"]) {
|
|
537
|
+
case "conversation.created": return text(value["resumeToken"], 1) ? {
|
|
538
|
+
type: "conversation.created",
|
|
539
|
+
resumeToken: value["resumeToken"]
|
|
540
|
+
} : void 0;
|
|
541
|
+
case "user.ack":
|
|
542
|
+
case "message.start": return messageId(id) ? {
|
|
543
|
+
type: value["type"],
|
|
544
|
+
messageId: id
|
|
545
|
+
} : void 0;
|
|
546
|
+
case "reasoning": return messageId(id) && oneOf(value["state"], ["started", "done"]) ? {
|
|
547
|
+
type: "reasoning",
|
|
548
|
+
messageId: id,
|
|
549
|
+
state: value["state"]
|
|
550
|
+
} : void 0;
|
|
551
|
+
case "text.delta": return messageId(id) && text(value["delta"]) ? {
|
|
552
|
+
type: "text.delta",
|
|
553
|
+
messageId: id,
|
|
554
|
+
delta: value["delta"]
|
|
555
|
+
} : void 0;
|
|
556
|
+
case "citation": {
|
|
557
|
+
const citation = citationOf(value);
|
|
558
|
+
return messageId(id) && citation ? {
|
|
559
|
+
type: "citation",
|
|
560
|
+
messageId: id,
|
|
561
|
+
...citation
|
|
562
|
+
} : void 0;
|
|
563
|
+
}
|
|
564
|
+
case "tool.status": return messageId(id) && text(value["callId"], 1, 128) && text(value["name"], 1, 64) && oneOf(value["state"], [
|
|
565
|
+
"running",
|
|
566
|
+
"done",
|
|
567
|
+
"error"
|
|
568
|
+
]) ? {
|
|
569
|
+
type: "tool.status",
|
|
570
|
+
messageId: id,
|
|
571
|
+
callId: value["callId"],
|
|
572
|
+
name: value["name"],
|
|
573
|
+
state: value["state"]
|
|
574
|
+
} : void 0;
|
|
575
|
+
case "tool.ui": return messageId(id) && isToolUi(value) ? {
|
|
576
|
+
type: "tool.ui",
|
|
577
|
+
messageId: id,
|
|
578
|
+
callId: value["callId"],
|
|
579
|
+
name: value["name"],
|
|
580
|
+
data: value["data"]
|
|
581
|
+
} : void 0;
|
|
582
|
+
case "replies": return messageId(id) && isReplyList(value["items"]) ? {
|
|
583
|
+
type: "replies",
|
|
584
|
+
messageId: id,
|
|
585
|
+
items: [...value["items"]]
|
|
586
|
+
} : void 0;
|
|
587
|
+
case "message.end": {
|
|
588
|
+
const { resumeToken } = value;
|
|
589
|
+
if (!messageId(id) || !oneOf(value["reason"], MESSAGE_END_REASONS)) return;
|
|
590
|
+
if (resumeToken !== void 0 && !text(resumeToken, 1)) return void 0;
|
|
591
|
+
const feedback = value["feedback"] === void 0 ? void 0 : feedbackOf(value["feedback"]);
|
|
592
|
+
if (value["feedback"] !== void 0 && !feedback) return void 0;
|
|
593
|
+
return {
|
|
594
|
+
type: "message.end",
|
|
595
|
+
messageId: id,
|
|
596
|
+
reason: value["reason"],
|
|
597
|
+
...typeof resumeToken === "string" ? { resumeToken } : {},
|
|
598
|
+
...feedback ? { feedback } : {}
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
case "error": {
|
|
602
|
+
const { code, message, retryAfterMs, key, params } = value;
|
|
603
|
+
if (!oneOf(code, ERROR_CODES) || !text(message, 0, 500)) return void 0;
|
|
604
|
+
if (retryAfterMs !== void 0 && !integer(retryAfterMs, 0)) return void 0;
|
|
605
|
+
if (key !== void 0 && !text(key, 0, 64)) return void 0;
|
|
606
|
+
const checked = params === void 0 ? void 0 : paramsOf(params);
|
|
607
|
+
if (params !== void 0 && !checked) return void 0;
|
|
608
|
+
return {
|
|
609
|
+
type: "error",
|
|
610
|
+
code,
|
|
611
|
+
message,
|
|
612
|
+
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
613
|
+
...key === void 0 ? {} : { key },
|
|
614
|
+
...checked ? { params: checked } : {}
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
default: return;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
function historyMessageOf(value) {
|
|
621
|
+
if (!record$1(value) || !text(value["id"], 1, 256) || !oneOf(value["role"], ["user", "assistant"]) || !text(value["text"]) || !Array.isArray(value["citations"]) || !integer(value["attachments"], 0)) return;
|
|
622
|
+
const citations = value["citations"].map(citationOf);
|
|
623
|
+
if (citations.some((citation) => citation === void 0)) return void 0;
|
|
624
|
+
const feedback = value["feedback"] === void 0 ? void 0 : feedbackOf(value["feedback"]);
|
|
625
|
+
if (value["feedback"] !== void 0 && !feedback) return void 0;
|
|
626
|
+
const { replies } = value;
|
|
627
|
+
if (replies !== void 0 && !isReplyList(replies)) return void 0;
|
|
628
|
+
const { ui } = value;
|
|
629
|
+
if (ui !== void 0 && !isToolUiList(ui)) return void 0;
|
|
630
|
+
return {
|
|
631
|
+
id: value["id"],
|
|
632
|
+
role: value["role"],
|
|
633
|
+
text: value["text"],
|
|
634
|
+
citations,
|
|
635
|
+
attachments: value["attachments"],
|
|
636
|
+
...feedback ? { feedback } : {},
|
|
637
|
+
...replies === void 0 ? {} : { replies: [...replies] },
|
|
638
|
+
...ui === void 0 ? {} : { ui: ui.map(({ callId, name, data }) => ({
|
|
639
|
+
callId,
|
|
640
|
+
name,
|
|
641
|
+
data
|
|
642
|
+
})) }
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
/** The answer of `POST /history`, or undefined when it breaks the protocol. */
|
|
646
|
+
function parseHistory(value) {
|
|
647
|
+
if (!record$1(value) || !Array.isArray(value["messages"])) return void 0;
|
|
648
|
+
const messages = value["messages"].map(historyMessageOf);
|
|
649
|
+
return messages.some((message) => message === void 0) ? void 0 : { messages };
|
|
650
|
+
}
|
|
651
|
+
// src/protocol/sse.ts
|
|
652
|
+
const KNOWN_TYPES = new Set(PROTOCOL_EVENT_TYPES);
|
|
653
|
+
/**
|
|
654
|
+
* Validates a framed event against the protocol. Unknown event types are reported, not thrown,
|
|
655
|
+
* so older clients keep working when newer servers add events.
|
|
656
|
+
*/
|
|
657
|
+
function decodeEvent(raw) {
|
|
658
|
+
if (!KNOWN_TYPES.has(raw.event)) return {
|
|
659
|
+
ok: false,
|
|
660
|
+
reason: "unknown_type",
|
|
661
|
+
type: raw.event
|
|
662
|
+
};
|
|
663
|
+
let json;
|
|
664
|
+
try {
|
|
665
|
+
json = JSON.parse(raw.data);
|
|
666
|
+
} catch {
|
|
667
|
+
return {
|
|
668
|
+
ok: false,
|
|
669
|
+
reason: "invalid_json",
|
|
670
|
+
type: raw.event
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
const event = parseEvent(json);
|
|
674
|
+
if (!event || event.type !== raw.event) return {
|
|
675
|
+
ok: false,
|
|
676
|
+
reason: "invalid_payload",
|
|
677
|
+
type: raw.event
|
|
678
|
+
};
|
|
679
|
+
return {
|
|
680
|
+
ok: true,
|
|
681
|
+
event
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Incremental parser for `text/event-stream`, following the WHATWG framing rules: any line ending
|
|
686
|
+
* (CRLF, LF, CR), comments, multi-line `data`, and dispatch on a blank line. Fields other than
|
|
687
|
+
* `event` and `data` are ignored. An unterminated event at end of stream is discarded.
|
|
688
|
+
*/
|
|
689
|
+
var SseParser = class {
|
|
690
|
+
#buffer = "";
|
|
691
|
+
#pendingCr = false;
|
|
692
|
+
#started = false;
|
|
693
|
+
#eventType = "";
|
|
694
|
+
#dataLines = [];
|
|
695
|
+
/** Feeds a decoded text chunk and returns the events completed by it. */
|
|
696
|
+
push(chunk) {
|
|
697
|
+
let text = chunk;
|
|
698
|
+
if (!this.#started && text.length > 0) {
|
|
699
|
+
this.#started = true;
|
|
700
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
701
|
+
}
|
|
702
|
+
if (this.#pendingCr && text.startsWith("\n")) text = text.slice(1);
|
|
703
|
+
this.#pendingCr = false;
|
|
704
|
+
this.#buffer += text;
|
|
705
|
+
const events = [];
|
|
706
|
+
let lineStart = 0;
|
|
707
|
+
for (let i = 0; i < this.#buffer.length; i += 1) {
|
|
708
|
+
const char = this.#buffer[i];
|
|
709
|
+
if (char !== "\n" && char !== "\r") continue;
|
|
710
|
+
const line = this.#buffer.slice(lineStart, i);
|
|
711
|
+
if (char === "\r") {
|
|
712
|
+
if (i + 1 === this.#buffer.length) this.#pendingCr = true;
|
|
713
|
+
else if (this.#buffer[i + 1] === "\n") i += 1;
|
|
714
|
+
}
|
|
715
|
+
lineStart = i + 1;
|
|
716
|
+
const event = this.#processLine(line);
|
|
717
|
+
if (event) events.push(event);
|
|
718
|
+
}
|
|
719
|
+
this.#buffer = this.#buffer.slice(lineStart);
|
|
720
|
+
return events;
|
|
721
|
+
}
|
|
722
|
+
#processLine(line) {
|
|
723
|
+
if (line === "") return this.#dispatch();
|
|
724
|
+
if (line.startsWith(":")) return void 0;
|
|
725
|
+
const colon = line.indexOf(":");
|
|
726
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
727
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
728
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
729
|
+
if (field === "event") this.#eventType = value;
|
|
730
|
+
else if (field === "data") this.#dataLines.push(value);
|
|
731
|
+
}
|
|
732
|
+
#dispatch() {
|
|
733
|
+
const hasData = this.#dataLines.length > 0;
|
|
734
|
+
const event = {
|
|
735
|
+
event: this.#eventType === "" ? "message" : this.#eventType,
|
|
736
|
+
data: this.#dataLines.join("\n")
|
|
737
|
+
};
|
|
738
|
+
this.#eventType = "";
|
|
739
|
+
this.#dataLines = [];
|
|
740
|
+
return hasData ? event : void 0;
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
// src/chat/chat-client.ts
|
|
744
|
+
/** The parts of a widget a language switch replaces, checked before use. */
|
|
745
|
+
function isWidget(value) {
|
|
746
|
+
if (typeof value !== "object" || value === null) return false;
|
|
747
|
+
const widget = value;
|
|
748
|
+
const texts = widget["texts"];
|
|
749
|
+
return [
|
|
750
|
+
"locale",
|
|
751
|
+
"title",
|
|
752
|
+
"greeting",
|
|
753
|
+
"placeholder",
|
|
754
|
+
"launcherLabel"
|
|
755
|
+
].every((key) => typeof widget[key] === "string") && typeof texts === "object" && texts !== null && Object.values(texts).every((text) => typeof text === "string");
|
|
756
|
+
}
|
|
757
|
+
const json = (value) => ({
|
|
758
|
+
contentType: "application/json",
|
|
759
|
+
body: JSON.stringify(value)
|
|
760
|
+
});
|
|
761
|
+
const RENEW_MARGIN_SECONDS = 30;
|
|
762
|
+
/** The server refused a session and said why: a limit, a switched-off bot, a setup problem. */
|
|
763
|
+
var SessionRefused = class extends Error {
|
|
764
|
+
event;
|
|
765
|
+
constructor(event) {
|
|
766
|
+
super(event.message);
|
|
767
|
+
this.event = event;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
/**
|
|
771
|
+
* Talks to the askdare API from the iframe: keeps the access token in memory, the resume token
|
|
772
|
+
* in best-effort storage, and turns each send into a stream of protocol events. Network and
|
|
773
|
+
* protocol problems are reported as `error` events, never thrown.
|
|
774
|
+
*/
|
|
775
|
+
var ChatClient = class {
|
|
776
|
+
#options;
|
|
777
|
+
#fetch;
|
|
778
|
+
#botId;
|
|
779
|
+
/** The visitor's language, sent with each message; it changes when the page switches it. */
|
|
780
|
+
#locale;
|
|
781
|
+
#session;
|
|
782
|
+
/** The page context the current conversation already has, so it is sent only when it changes. */
|
|
783
|
+
#sentContext;
|
|
784
|
+
/** Shared by concurrent callers, so parallel uploads end up with one visitor. */
|
|
785
|
+
#opening;
|
|
786
|
+
/**
|
|
787
|
+
* The page's latest askdare('identify'): a token, or null when signed out (ADR-0009). Sent with
|
|
788
|
+
* every session request, so the server re-checks it and the identity ends with the token.
|
|
789
|
+
*/
|
|
790
|
+
#identity;
|
|
791
|
+
/** Set when the identity changed: no request may use the previous user's session any more. */
|
|
792
|
+
#identityChanged = false;
|
|
793
|
+
/** Tokens already reported as refused, so a renewal doesn't warn again. */
|
|
794
|
+
#refused;
|
|
795
|
+
/** The signed-in user, as an opaque key from the server; undefined while anonymous. */
|
|
796
|
+
#identityKey;
|
|
797
|
+
/** The previous user's access token while their identity is replaced: renews the visitor only. */
|
|
798
|
+
#renewal;
|
|
799
|
+
constructor(options) {
|
|
800
|
+
this.#options = options;
|
|
801
|
+
this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
802
|
+
this.#botId = options.botId;
|
|
803
|
+
this.#locale = options.locale;
|
|
804
|
+
}
|
|
805
|
+
/** The language sent with each message from now on (ADR-0014, step 2). */
|
|
806
|
+
setLocale(locale) {
|
|
807
|
+
this.#locale = locale;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* The bot's public widget settings in another language, from `GET /config/<bot>`, with the
|
|
811
|
+
* language its texts are written in; undefined when they can't be read. Never throws.
|
|
812
|
+
*/
|
|
813
|
+
async fetchWidget(locale) {
|
|
814
|
+
const query = new URLSearchParams({ lang: locale });
|
|
815
|
+
try {
|
|
816
|
+
const response = await this.#fetch(`${this.#options.basePath}/config/${encodeURIComponent(this.#botId)}?${query}`);
|
|
817
|
+
if (!response.ok) return void 0;
|
|
818
|
+
const body = await response.json();
|
|
819
|
+
if (!isWidget(body?.widget)) return void 0;
|
|
820
|
+
const language = response.headers.get("content-language");
|
|
821
|
+
return {
|
|
822
|
+
widget: body.widget,
|
|
823
|
+
language: language || body.widget.locale
|
|
824
|
+
};
|
|
825
|
+
} catch {
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/** A client-side error: the dictionary text for `key`, else the English message. */
|
|
830
|
+
#error(code, key, english) {
|
|
831
|
+
return {
|
|
832
|
+
type: "error",
|
|
833
|
+
code,
|
|
834
|
+
key,
|
|
835
|
+
message: this.#options.translate?.(key) ?? english
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
/** A server error in the visitor's language when it carries a known key. */
|
|
839
|
+
#localize(event) {
|
|
840
|
+
const text = event.key ? this.#options.translate?.(event.key, event.params) : void 0;
|
|
841
|
+
return text ? {
|
|
842
|
+
...event,
|
|
843
|
+
message: text
|
|
844
|
+
} : event;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Signs the visitor in (a token from the site's backend) or out (null) right away. Resolves to
|
|
848
|
+
* true when the stored conversation belonged to someone else and is gone from this browser.
|
|
849
|
+
*/
|
|
850
|
+
async identify(token) {
|
|
851
|
+
if (token === this.#identity) return false;
|
|
852
|
+
this.#identity = token;
|
|
853
|
+
this.#identityChanged = true;
|
|
854
|
+
await this.#opening?.catch(() => void 0);
|
|
855
|
+
const before = this.#resumeKey();
|
|
856
|
+
this.#renewal = this.#session?.accessToken ?? this.#renewal;
|
|
857
|
+
this.#session = void 0;
|
|
858
|
+
try {
|
|
859
|
+
await this.#ensureSession(false);
|
|
860
|
+
} catch {}
|
|
861
|
+
return this.#resumeKey() !== before;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Where this browser keeps the conversation: one place per signed-in user and one for anonymous
|
|
865
|
+
* visits, so signing out or in never hands a conversation to someone else, nor loses it.
|
|
866
|
+
*/
|
|
867
|
+
#resumeKey() {
|
|
868
|
+
const base = `askdare:${this.#botId}:resume`;
|
|
869
|
+
return this.#identityKey ? `${base}:${this.#identityKey}` : base;
|
|
870
|
+
}
|
|
871
|
+
/** Forgets the stored conversation so the next message starts a new one. */
|
|
872
|
+
reset() {
|
|
873
|
+
this.#sentContext = void 0;
|
|
874
|
+
this.#options.storage.remove(this.#resumeKey());
|
|
875
|
+
}
|
|
876
|
+
/** True when this browser holds a conversation to resume. */
|
|
877
|
+
hasConversation() {
|
|
878
|
+
return this.#options.storage.get(this.#resumeKey()) !== void 0;
|
|
879
|
+
}
|
|
880
|
+
/** Loads the visible part of the stored conversation; empty when there is none or it is gone. */
|
|
881
|
+
async loadHistory(signal) {
|
|
882
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
883
|
+
if (!resumeToken) return [];
|
|
884
|
+
const response = await this.#authorized("POST", "/history", () => json({
|
|
885
|
+
botId: this.#options.botId,
|
|
886
|
+
resumeToken
|
|
887
|
+
}), signal);
|
|
888
|
+
if (response.status === 404) {
|
|
889
|
+
this.reset();
|
|
890
|
+
return [];
|
|
891
|
+
}
|
|
892
|
+
if (!response.ok) throw new Error(`History request failed with ${response.status}`);
|
|
893
|
+
return parseHistory(await response.json())?.messages ?? [];
|
|
894
|
+
}
|
|
895
|
+
/** Deletes the conversation on the server (best effort) and forgets it in this browser. */
|
|
896
|
+
async deleteConversation() {
|
|
897
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
898
|
+
try {
|
|
899
|
+
if (resumeToken) await this.#authorized("DELETE", "/conversation", () => json({
|
|
900
|
+
botId: this.#options.botId,
|
|
901
|
+
resumeToken
|
|
902
|
+
}));
|
|
903
|
+
} finally {
|
|
904
|
+
this.reset();
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
/** This browser's ratings of answers, by feedback key (ADR-0012: askdare stores none). */
|
|
908
|
+
ratings() {
|
|
909
|
+
try {
|
|
910
|
+
const stored = JSON.parse(this.#options.storage.get(this.#ratingsKey()) ?? "{}");
|
|
911
|
+
if (typeof stored !== "object" || stored === null) return {};
|
|
912
|
+
return Object.fromEntries(Object.entries(stored).filter((entry) => entry[1] === "up" || entry[1] === "down"));
|
|
913
|
+
} catch {
|
|
914
|
+
return {};
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
/** Remembers a rating, or forgets it with null. Only the latest hundred are kept. */
|
|
918
|
+
rememberRating(key, rating) {
|
|
919
|
+
const { [key]: _previous, ...others } = this.ratings();
|
|
920
|
+
const entries = Object.entries(rating ? {
|
|
921
|
+
...others,
|
|
922
|
+
[key]: rating
|
|
923
|
+
} : others).slice(-100);
|
|
924
|
+
this.#options.storage.set(this.#ratingsKey(), JSON.stringify(Object.fromEntries(entries)));
|
|
925
|
+
}
|
|
926
|
+
#ratingsKey() {
|
|
927
|
+
return `askdare:${this.#botId}:ratings`;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Sends a rating of one answer (null takes it back) with an optional comment; `handle` comes
|
|
931
|
+
* with the answer. Resolves to what went wrong, in the visitor's language, or undefined.
|
|
932
|
+
*/
|
|
933
|
+
async rate(handle, rating, comment) {
|
|
934
|
+
try {
|
|
935
|
+
const response = await this.#authorized("POST", "/feedback", () => json({
|
|
936
|
+
botId: this.#options.botId,
|
|
937
|
+
feedback: handle,
|
|
938
|
+
rating,
|
|
939
|
+
...comment ? { comment } : {}
|
|
940
|
+
}));
|
|
941
|
+
return response.ok ? void 0 : (await this.#errorFromResponse(response, false)).message;
|
|
942
|
+
} catch (error) {
|
|
943
|
+
return this.#failure(error, "upstream_error").message;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
/** Uploads one file for the next message. The server checks its type and size again. */
|
|
947
|
+
async upload(file, name, signal) {
|
|
948
|
+
try {
|
|
949
|
+
const response = await this.#authorized("POST", "/attachments", () => ({
|
|
950
|
+
contentType: "application/octet-stream",
|
|
951
|
+
body: file,
|
|
952
|
+
headers: {
|
|
953
|
+
"x-askdare-bot": this.#options.botId,
|
|
954
|
+
"x-askdare-filename": encodeURIComponent(name)
|
|
955
|
+
}
|
|
956
|
+
}), signal);
|
|
957
|
+
if (!response.ok) return {
|
|
958
|
+
ok: false,
|
|
959
|
+
message: (await this.#errorFromResponse(response)).message
|
|
960
|
+
};
|
|
961
|
+
const uploaded = (await response.json()).attachment;
|
|
962
|
+
if (typeof uploaded?.id !== "string" || uploaded.kind !== "image" && uploaded.kind !== "pdf" || typeof uploaded.name !== "string") return {
|
|
963
|
+
ok: false,
|
|
964
|
+
message: this.#error("upstream_error", "error.uploadFailed", "The file could not be uploaded.").message
|
|
965
|
+
};
|
|
966
|
+
return {
|
|
967
|
+
ok: true,
|
|
968
|
+
file: {
|
|
969
|
+
id: uploaded.id,
|
|
970
|
+
kind: uploaded.kind,
|
|
971
|
+
name: uploaded.name
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
} catch (error) {
|
|
975
|
+
return {
|
|
976
|
+
ok: false,
|
|
977
|
+
message: this.#failure(error, "upstream_error").message
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
/** Turns a dictation into text. `languages` are hints such as the browser's and the page's language. */
|
|
982
|
+
async transcribe(audio, languages) {
|
|
983
|
+
try {
|
|
984
|
+
const response = await this.#authorized("POST", "/transcriptions", () => ({
|
|
985
|
+
contentType: "application/octet-stream",
|
|
986
|
+
body: audio,
|
|
987
|
+
headers: {
|
|
988
|
+
"x-askdare-bot": this.#options.botId,
|
|
989
|
+
"x-askdare-languages": languages.join(",")
|
|
990
|
+
}
|
|
991
|
+
}));
|
|
992
|
+
if (!response.ok) return {
|
|
993
|
+
ok: false,
|
|
994
|
+
message: (await this.#errorFromResponse(response)).message
|
|
995
|
+
};
|
|
996
|
+
const body = await response.json();
|
|
997
|
+
return typeof body.text === "string" ? {
|
|
998
|
+
ok: true,
|
|
999
|
+
text: body.text
|
|
1000
|
+
} : {
|
|
1001
|
+
ok: false,
|
|
1002
|
+
message: this.#error("upstream_error", "error.transcriptionFailed", "The recording could not be transcribed.").message
|
|
1003
|
+
};
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
return {
|
|
1006
|
+
ok: false,
|
|
1007
|
+
message: this.#failure(error, "upstream_error").message
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
async send(message, onEvent, signal) {
|
|
1012
|
+
const context = message.context !== this.#sentContext ? message.context : void 0;
|
|
1013
|
+
try {
|
|
1014
|
+
const response = await this.#authorized("POST", "/messages", () => {
|
|
1015
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
1016
|
+
return json({
|
|
1017
|
+
botId: this.#options.botId,
|
|
1018
|
+
text: message.text,
|
|
1019
|
+
locale: this.#locale,
|
|
1020
|
+
...message.attachments?.length ? { attachments: message.attachments } : {},
|
|
1021
|
+
...context ? { context } : {},
|
|
1022
|
+
...resumeToken ? { resumeToken } : {}
|
|
1023
|
+
});
|
|
1024
|
+
}, signal);
|
|
1025
|
+
if (!response.ok || !response.body) {
|
|
1026
|
+
onEvent(await this.#errorFromResponse(response));
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
if (response.headers.get("x-askdare-protocol") !== String(1)) {
|
|
1030
|
+
onEvent(this.#error("bot_unavailable", "error.updated", "The assistant was updated. Please reload the page."));
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
await this.#readStream(response.body, (event) => {
|
|
1034
|
+
if (event.type === "message.start" && context) this.#sentContext = context;
|
|
1035
|
+
onEvent(event);
|
|
1036
|
+
}, signal);
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
if (signal?.aborted) return;
|
|
1039
|
+
onEvent(this.#failure(error, error instanceof DOMException && error.name === "TimeoutError" ? "timeout" : "upstream_error"));
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
/** Sends an authenticated request, renewing an expired session once. */
|
|
1043
|
+
async #authorized(method, path, request, signal) {
|
|
1044
|
+
const attempt = async (renew) => {
|
|
1045
|
+
const session = await this.#ensureSession(renew);
|
|
1046
|
+
const { contentType, body, headers } = request();
|
|
1047
|
+
return this.#fetch(`${this.#options.basePath}${path}`, {
|
|
1048
|
+
method,
|
|
1049
|
+
headers: {
|
|
1050
|
+
...headers,
|
|
1051
|
+
"content-type": contentType,
|
|
1052
|
+
authorization: `Bearer ${session.accessToken}`
|
|
1053
|
+
},
|
|
1054
|
+
body,
|
|
1055
|
+
...signal ? { signal } : {}
|
|
1056
|
+
});
|
|
1057
|
+
};
|
|
1058
|
+
const first = await attempt(false);
|
|
1059
|
+
return first.status === 401 ? attempt(true) : first;
|
|
1060
|
+
}
|
|
1061
|
+
async #ensureSession(renew) {
|
|
1062
|
+
const now = Date.now() / 1e3;
|
|
1063
|
+
if (!renew && !this.#identityChanged && this.#session && this.#session.expiresAt - RENEW_MARGIN_SECONDS > now) return this.#session;
|
|
1064
|
+
this.#opening ??= this.#openSession().finally(() => {
|
|
1065
|
+
this.#opening = void 0;
|
|
1066
|
+
});
|
|
1067
|
+
return this.#opening;
|
|
1068
|
+
}
|
|
1069
|
+
/** Not tied to one caller's signal, because other callers may be waiting for the same session. */
|
|
1070
|
+
async #openSession() {
|
|
1071
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
1072
|
+
const accessToken = this.#session?.accessToken ?? this.#renewal;
|
|
1073
|
+
const identityToken = this.#identity;
|
|
1074
|
+
const sentFrom = this.#resumeKey();
|
|
1075
|
+
const response = await this.#fetch(`${this.#options.basePath}/session`, {
|
|
1076
|
+
method: "POST",
|
|
1077
|
+
headers: { "content-type": "application/json" },
|
|
1078
|
+
body: JSON.stringify({
|
|
1079
|
+
botId: this.#options.botId,
|
|
1080
|
+
...resumeToken ? { resumeToken } : {},
|
|
1081
|
+
...accessToken ? { accessToken } : {},
|
|
1082
|
+
...identityToken === void 0 ? {} : { identityToken }
|
|
1083
|
+
})
|
|
1084
|
+
});
|
|
1085
|
+
if (!response.ok) throw new SessionRefused(await this.#errorFromResponse(response, false));
|
|
1086
|
+
const body = await response.json();
|
|
1087
|
+
if (this.#identity === identityToken) this.#identityChanged = false;
|
|
1088
|
+
this.#renewal = void 0;
|
|
1089
|
+
this.#identityKey = body.identified ? body.identityKey : void 0;
|
|
1090
|
+
if (identityToken && !body.identified && this.#refused !== identityToken) {
|
|
1091
|
+
this.#refused = identityToken;
|
|
1092
|
+
console.warn(`[askdare] askdare('identify') was refused (${body.identityProblem ?? "unknown"}); the chat continues anonymously.`);
|
|
1093
|
+
}
|
|
1094
|
+
if (body.resumeToken) {
|
|
1095
|
+
this.#options.storage.set(this.#resumeKey(), body.resumeToken);
|
|
1096
|
+
if (sentFrom !== this.#resumeKey()) this.#options.storage.remove(sentFrom);
|
|
1097
|
+
} else if (!body.resumable && resumeToken && sentFrom === this.#resumeKey()) this.reset();
|
|
1098
|
+
this.#session = {
|
|
1099
|
+
accessToken: body.accessToken,
|
|
1100
|
+
expiresAt: body.expiresAt
|
|
1101
|
+
};
|
|
1102
|
+
return this.#session;
|
|
1103
|
+
}
|
|
1104
|
+
/** What to show for a request that threw: the server's reason for refusing a session, if any. */
|
|
1105
|
+
#failure(error, code) {
|
|
1106
|
+
return error instanceof SessionRefused ? error.event : this.#connectionError(code);
|
|
1107
|
+
}
|
|
1108
|
+
#connectionError(code) {
|
|
1109
|
+
return this.#error(code, "error.connection", "Connection problem. Please try again.");
|
|
1110
|
+
}
|
|
1111
|
+
async #errorFromResponse(response, forgetMissing = true) {
|
|
1112
|
+
let body = {};
|
|
1113
|
+
try {
|
|
1114
|
+
body = await response.json();
|
|
1115
|
+
} catch {}
|
|
1116
|
+
if (forgetMissing && response.status === 404 && body.error?.code === "not_found") this.reset();
|
|
1117
|
+
const result = decodeEvent({
|
|
1118
|
+
event: "error",
|
|
1119
|
+
data: JSON.stringify({
|
|
1120
|
+
type: "error",
|
|
1121
|
+
...body.error
|
|
1122
|
+
})
|
|
1123
|
+
});
|
|
1124
|
+
return result.ok && result.event.type === "error" ? this.#localize(result.event) : this.#error("upstream_error", "error.upstream_error", "The assistant is temporarily unavailable. Please try again.");
|
|
1125
|
+
}
|
|
1126
|
+
async #readStream(body, onEvent, signal) {
|
|
1127
|
+
const reader = body.getReader();
|
|
1128
|
+
const decoder = new TextDecoder();
|
|
1129
|
+
const parser = new SseParser();
|
|
1130
|
+
const watchdogMs = this.#options.watchdogMs ?? 45e3;
|
|
1131
|
+
let timer;
|
|
1132
|
+
let stalled = false;
|
|
1133
|
+
const arm = () => {
|
|
1134
|
+
clearTimeout(timer);
|
|
1135
|
+
timer = setTimeout(() => {
|
|
1136
|
+
stalled = true;
|
|
1137
|
+
reader.cancel();
|
|
1138
|
+
}, watchdogMs);
|
|
1139
|
+
};
|
|
1140
|
+
const onAbort = () => void reader.cancel();
|
|
1141
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1142
|
+
try {
|
|
1143
|
+
arm();
|
|
1144
|
+
for (;;) {
|
|
1145
|
+
const { done, value } = await reader.read();
|
|
1146
|
+
if (done) break;
|
|
1147
|
+
arm();
|
|
1148
|
+
for (const raw of parser.push(decoder.decode(value, { stream: true }))) {
|
|
1149
|
+
const result = decodeEvent(raw);
|
|
1150
|
+
if (!result.ok) continue;
|
|
1151
|
+
if (result.event.type === "conversation.created") this.#options.storage.set(this.#resumeKey(), result.event.resumeToken);
|
|
1152
|
+
else if (result.event.type === "message.end" && result.event.resumeToken) this.#options.storage.set(this.#resumeKey(), result.event.resumeToken);
|
|
1153
|
+
else if (result.event.type === "error" && result.event.code === "not_found") this.reset();
|
|
1154
|
+
onEvent(result.event.type === "error" ? this.#localize(result.event) : result.event);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
if (stalled) onEvent(this.#error("timeout", "error.stalled", "The connection stalled. Please try again."));
|
|
1158
|
+
} finally {
|
|
1159
|
+
clearTimeout(timer);
|
|
1160
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
};
|
|
1164
|
+
// src/chat/events.ts
|
|
1165
|
+
/**
|
|
1166
|
+
* Listeners by event type, or '*' for every type; used by the chat store and by the loader on the
|
|
1167
|
+
* host page. Each event is frozen, so one listener can't change what the next one gets. A listener
|
|
1168
|
+
* that throws can't break the chat: it is logged in one line, without details, and the others
|
|
1169
|
+
* still run.
|
|
1170
|
+
*/
|
|
1171
|
+
function eventListeners() {
|
|
1172
|
+
const listeners = [];
|
|
1173
|
+
const off = (type, listener) => {
|
|
1174
|
+
const index = listeners.findIndex(([t, l]) => t === type && l === listener);
|
|
1175
|
+
if (index >= 0) listeners.splice(index, 1);
|
|
1176
|
+
};
|
|
1177
|
+
return {
|
|
1178
|
+
on(type, listener) {
|
|
1179
|
+
if (typeof type === "string" && typeof listener === "function") listeners.push([type, listener]);
|
|
1180
|
+
else console.warn("[askdare] askdare('on') expects an event type and a function.");
|
|
1181
|
+
return () => off(type, listener);
|
|
1182
|
+
},
|
|
1183
|
+
off,
|
|
1184
|
+
emit(event) {
|
|
1185
|
+
Object.freeze(event);
|
|
1186
|
+
for (const [type, listener] of [...listeners]) {
|
|
1187
|
+
if (type !== "*" && type !== event.type) continue;
|
|
1188
|
+
try {
|
|
1189
|
+
listener(event);
|
|
1190
|
+
} catch {
|
|
1191
|
+
console.warn(`[askdare] A listener for "${event.type}" threw.`);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
// src/chat/recorder.ts
|
|
1198
|
+
/** Formats OpenAI transcribes, best first: WebM/Opus (Chrome, Firefox, Edge), then MP4 (Safari). */
|
|
1199
|
+
const MIME_TYPES = [
|
|
1200
|
+
"audio/webm;codecs=opus",
|
|
1201
|
+
"audio/webm",
|
|
1202
|
+
"audio/mp4;codecs=mp4a.40.2",
|
|
1203
|
+
"audio/mp4"
|
|
1204
|
+
];
|
|
1205
|
+
/** Speech needs little: about 240 KB per minute where the browser honours it. */
|
|
1206
|
+
const BITS_PER_SECOND = 32e3;
|
|
1207
|
+
function recordingMimeType() {
|
|
1208
|
+
if (typeof MediaRecorder === "undefined") return void 0;
|
|
1209
|
+
return MIME_TYPES.find((type) => MediaRecorder.isTypeSupported(type));
|
|
1210
|
+
}
|
|
1211
|
+
/** True when this browser can record and the embedding page's policy lets the iframe use the microphone. */
|
|
1212
|
+
function canRecord() {
|
|
1213
|
+
if (!navigator.mediaDevices?.getUserMedia || !recordingMimeType()) return false;
|
|
1214
|
+
return document.featurePolicy?.allowsFeature("microphone") ?? true;
|
|
1215
|
+
}
|
|
1216
|
+
var MicrophoneError = class extends Error {
|
|
1217
|
+
reason;
|
|
1218
|
+
constructor(reason, options) {
|
|
1219
|
+
super(`Microphone ${reason}`, options);
|
|
1220
|
+
this.reason = reason;
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
/**
|
|
1224
|
+
* Asks for the microphone and starts recording. Recording stops by itself after `maxSeconds`,
|
|
1225
|
+
* even in a hidden frame. Throws {@link MicrophoneError}.
|
|
1226
|
+
*/
|
|
1227
|
+
async function startRecording(maxSeconds) {
|
|
1228
|
+
const mimeType = recordingMimeType();
|
|
1229
|
+
if (!mimeType) throw new MicrophoneError("failed");
|
|
1230
|
+
let stream;
|
|
1231
|
+
try {
|
|
1232
|
+
stream = await navigator.mediaDevices.getUserMedia({ audio: {
|
|
1233
|
+
echoCancellation: true,
|
|
1234
|
+
noiseSuppression: true
|
|
1235
|
+
} });
|
|
1236
|
+
} catch (error) {
|
|
1237
|
+
const name = error instanceof DOMException ? error.name : "";
|
|
1238
|
+
if (name === "NotAllowedError" || name === "SecurityError") throw new MicrophoneError("blocked", { cause: error });
|
|
1239
|
+
if (name === "NotFoundError" || name === "OverconstrainedError") throw new MicrophoneError("missing", { cause: error });
|
|
1240
|
+
throw new MicrophoneError("failed", { cause: error });
|
|
1241
|
+
}
|
|
1242
|
+
try {
|
|
1243
|
+
return record(stream, mimeType, maxSeconds);
|
|
1244
|
+
} catch (error) {
|
|
1245
|
+
for (const track of stream.getTracks()) track.stop();
|
|
1246
|
+
throw new MicrophoneError("failed", { cause: error });
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
function record(stream, mimeType, maxSeconds) {
|
|
1250
|
+
const recorder = new MediaRecorder(stream, {
|
|
1251
|
+
mimeType,
|
|
1252
|
+
audioBitsPerSecond: BITS_PER_SECOND
|
|
1253
|
+
});
|
|
1254
|
+
const chunks = [];
|
|
1255
|
+
recorder.addEventListener("dataavailable", (event) => {
|
|
1256
|
+
if (event.data.size > 0) chunks.push(event.data);
|
|
1257
|
+
});
|
|
1258
|
+
const stopped = new Promise((resolve) => recorder.addEventListener("stop", () => resolve(), { once: true }));
|
|
1259
|
+
const context = new AudioContext();
|
|
1260
|
+
const analyser = context.createAnalyser();
|
|
1261
|
+
analyser.fftSize = 512;
|
|
1262
|
+
context.createMediaStreamSource(stream).connect(analyser);
|
|
1263
|
+
const samples = new Uint8Array(analyser.fftSize);
|
|
1264
|
+
const release = () => {
|
|
1265
|
+
for (const track of stream.getTracks()) track.stop();
|
|
1266
|
+
context.close();
|
|
1267
|
+
};
|
|
1268
|
+
let limit;
|
|
1269
|
+
const halt = () => {
|
|
1270
|
+
clearTimeout(limit);
|
|
1271
|
+
if (recorder.state !== "inactive") recorder.stop();
|
|
1272
|
+
};
|
|
1273
|
+
recorder.start(250);
|
|
1274
|
+
limit = setTimeout(halt, maxSeconds * 1e3);
|
|
1275
|
+
return {
|
|
1276
|
+
level() {
|
|
1277
|
+
analyser.getByteTimeDomainData(samples);
|
|
1278
|
+
let sum = 0;
|
|
1279
|
+
for (const sample of samples) {
|
|
1280
|
+
const value = (sample - 128) / 128;
|
|
1281
|
+
sum += value * value;
|
|
1282
|
+
}
|
|
1283
|
+
return Math.min(1, Math.sqrt(sum / samples.length) * 4);
|
|
1284
|
+
},
|
|
1285
|
+
async stop() {
|
|
1286
|
+
halt();
|
|
1287
|
+
await stopped;
|
|
1288
|
+
release();
|
|
1289
|
+
return new Blob(chunks, { type: mimeType.split(";")[0] ?? mimeType });
|
|
1290
|
+
},
|
|
1291
|
+
cancel() {
|
|
1292
|
+
halt();
|
|
1293
|
+
release();
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
// src/chat/reducer.ts
|
|
1298
|
+
/** Looks texts up in a bot's dictionary; an unknown key shows as itself. */
|
|
1299
|
+
function translator(texts) {
|
|
1300
|
+
return (key, params) => formatText(texts[key] ?? key, params);
|
|
1301
|
+
}
|
|
1302
|
+
const fromHistory = (message) => ({
|
|
1303
|
+
id: message.id,
|
|
1304
|
+
role: message.role,
|
|
1305
|
+
text: message.text,
|
|
1306
|
+
citations: message.citations,
|
|
1307
|
+
attachments: message.attachments,
|
|
1308
|
+
status: "done",
|
|
1309
|
+
...message.feedback ? { feedback: message.feedback } : {},
|
|
1310
|
+
...message.replies ? { replies: message.replies } : {},
|
|
1311
|
+
...message.ui ? { ui: message.ui } : {}
|
|
1312
|
+
});
|
|
1313
|
+
/** The messages after one protocol event of a streamed answer. */
|
|
1314
|
+
function applyEvent(messages, event) {
|
|
1315
|
+
const update = (id, change) => messages.map((message) => message.id === id ? change(message) : message);
|
|
1316
|
+
switch (event.type) {
|
|
1317
|
+
case "message.start": return [...messages, {
|
|
1318
|
+
id: event.messageId,
|
|
1319
|
+
role: "assistant",
|
|
1320
|
+
text: "",
|
|
1321
|
+
citations: [],
|
|
1322
|
+
attachments: 0,
|
|
1323
|
+
status: "streaming"
|
|
1324
|
+
}];
|
|
1325
|
+
case "text.delta": return update(event.messageId, (message) => ({
|
|
1326
|
+
...message,
|
|
1327
|
+
text: message.text + event.delta
|
|
1328
|
+
}));
|
|
1329
|
+
case "citation": return update(event.messageId, (message) => ({
|
|
1330
|
+
...message,
|
|
1331
|
+
citations: [...message.citations, {
|
|
1332
|
+
index: event.index,
|
|
1333
|
+
title: event.title,
|
|
1334
|
+
url: event.url
|
|
1335
|
+
}]
|
|
1336
|
+
}));
|
|
1337
|
+
case "tool.ui": {
|
|
1338
|
+
const { callId, name, data } = event;
|
|
1339
|
+
const payload = {
|
|
1340
|
+
callId,
|
|
1341
|
+
name,
|
|
1342
|
+
data
|
|
1343
|
+
};
|
|
1344
|
+
return update(event.messageId, (message) => {
|
|
1345
|
+
const ui = message.ui ?? [];
|
|
1346
|
+
if (ui.length >= 4 || ui.some((item) => item.callId === callId)) return message;
|
|
1347
|
+
return {
|
|
1348
|
+
...message,
|
|
1349
|
+
ui: [...ui, payload]
|
|
1350
|
+
};
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
case "replies": return update(event.messageId, (message) => ({
|
|
1354
|
+
...message,
|
|
1355
|
+
replies: event.items
|
|
1356
|
+
}));
|
|
1357
|
+
case "message.end": return update(event.messageId, (message) => ({
|
|
1358
|
+
...message,
|
|
1359
|
+
status: "done",
|
|
1360
|
+
...event.feedback ? { feedback: event.feedback } : {}
|
|
1361
|
+
}));
|
|
1362
|
+
default: return messages;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
/** Marks the answer that was streaming when the turn failed. */
|
|
1366
|
+
const failStreaming = (messages) => messages.map((message) => message.status === "streaming" ? {
|
|
1367
|
+
...message,
|
|
1368
|
+
status: "error"
|
|
1369
|
+
} : message);
|
|
1370
|
+
/** What the assistant is doing right now, shown while no text streams; undefined: unchanged. */
|
|
1371
|
+
function activityFor(event, t) {
|
|
1372
|
+
if (event.type === "reasoning") return event.state === "started" ? t("status.thinking") : null;
|
|
1373
|
+
if (event.type === "tool.status") return event.state === "running" ? event.name === "file_search" ? t("status.searching") : t("status.tool", { name: event.name }) : null;
|
|
1374
|
+
if (event.type === "text.delta" || event.type === "message.end") return null;
|
|
1375
|
+
}
|
|
1376
|
+
// src/chat/storage.ts
|
|
1377
|
+
function browserStorage() {
|
|
1378
|
+
return {
|
|
1379
|
+
get(key) {
|
|
1380
|
+
try {
|
|
1381
|
+
return window.localStorage.getItem(key) ?? void 0;
|
|
1382
|
+
} catch {
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
},
|
|
1386
|
+
set(key, value) {
|
|
1387
|
+
try {
|
|
1388
|
+
window.localStorage.setItem(key, value);
|
|
1389
|
+
} catch {}
|
|
1390
|
+
},
|
|
1391
|
+
remove(key) {
|
|
1392
|
+
try {
|
|
1393
|
+
window.localStorage.removeItem(key);
|
|
1394
|
+
} catch {}
|
|
1395
|
+
}
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
// src/chat/store.ts
|
|
1399
|
+
/** How long a focus request waits for its element to appear, such as the field after a dictation. */
|
|
1400
|
+
const FOCUS_WAIT_MS = 2e3;
|
|
1401
|
+
/**
|
|
1402
|
+
* Where the chat wants focus next. A request stays pending until a listener for its target really
|
|
1403
|
+
* takes it: the message field comes back only after a dictation ends, and a listener whose element
|
|
1404
|
+
* has just unmounted must not swallow the request. Only the latest request is kept.
|
|
1405
|
+
*/
|
|
1406
|
+
function focusRequests() {
|
|
1407
|
+
const listeners = {
|
|
1408
|
+
input: /* @__PURE__ */ new Set(),
|
|
1409
|
+
dictation: /* @__PURE__ */ new Set()
|
|
1410
|
+
};
|
|
1411
|
+
let pending;
|
|
1412
|
+
const deliver = (target, explicit) => {
|
|
1413
|
+
let taken = false;
|
|
1414
|
+
for (const listener of listeners[target]) taken = listener(explicit) || taken;
|
|
1415
|
+
return taken;
|
|
1416
|
+
};
|
|
1417
|
+
return {
|
|
1418
|
+
focus(target, explicit = false) {
|
|
1419
|
+
pending = deliver(target, explicit) ? void 0 : {
|
|
1420
|
+
target,
|
|
1421
|
+
explicit,
|
|
1422
|
+
at: Date.now()
|
|
1423
|
+
};
|
|
1424
|
+
},
|
|
1425
|
+
onFocus(target, listener) {
|
|
1426
|
+
listeners[target].add(listener);
|
|
1427
|
+
if (pending?.target === target && Date.now() - pending.at < FOCUS_WAIT_MS && listener(pending?.explicit ?? false)) pending = void 0;
|
|
1428
|
+
return () => listeners[target].delete(listener);
|
|
1429
|
+
}
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
const MICROPHONE_MESSAGES = {
|
|
1433
|
+
blocked: "microphone.blocked",
|
|
1434
|
+
missing: "microphone.missing",
|
|
1435
|
+
failed: "microphone.failed"
|
|
1436
|
+
};
|
|
1437
|
+
/** As the server's limit for a rating's comment. */
|
|
1438
|
+
const MAX_COMMENT = 500;
|
|
1439
|
+
const megabytes = (bytes) => `${Math.floor(bytes / 1e5) / 10} MB`;
|
|
1440
|
+
function revokePreviews(files) {
|
|
1441
|
+
for (const file of files) if (file.previewUrl) URL.revokeObjectURL(file.previewUrl);
|
|
1442
|
+
}
|
|
1443
|
+
/** The chat's state and actions for one bot, without any UI (ADR-0011). */
|
|
1444
|
+
function createChatStore(initialConfig, options = {}) {
|
|
1445
|
+
let config = initialConfig;
|
|
1446
|
+
let t = translator(config.widget.texts);
|
|
1447
|
+
const client = options.client ?? new ChatClient({
|
|
1448
|
+
basePath: config.basePath,
|
|
1449
|
+
botId: config.botId,
|
|
1450
|
+
locale: config.widget.locale,
|
|
1451
|
+
storage: browserStorage(),
|
|
1452
|
+
translate: (key, params) => config.widget.texts[key] === void 0 ? void 0 : t(key, params)
|
|
1453
|
+
});
|
|
1454
|
+
const recorder = options.recorder ?? {
|
|
1455
|
+
canRecord,
|
|
1456
|
+
startRecording
|
|
1457
|
+
};
|
|
1458
|
+
const voice = config.voice;
|
|
1459
|
+
const allowed = config.attachments;
|
|
1460
|
+
const initial = {
|
|
1461
|
+
phase: "starting",
|
|
1462
|
+
busy: false,
|
|
1463
|
+
messages: [],
|
|
1464
|
+
draft: "",
|
|
1465
|
+
error: void 0,
|
|
1466
|
+
activity: null,
|
|
1467
|
+
files: [],
|
|
1468
|
+
dictation: "idle",
|
|
1469
|
+
elapsed: 0,
|
|
1470
|
+
canDictate: false,
|
|
1471
|
+
page: options.page ?? {},
|
|
1472
|
+
ratings: {},
|
|
1473
|
+
commenting: void 0
|
|
1474
|
+
};
|
|
1475
|
+
let state = initial;
|
|
1476
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1477
|
+
const set = (change) => {
|
|
1478
|
+
state = {
|
|
1479
|
+
...state,
|
|
1480
|
+
...change
|
|
1481
|
+
};
|
|
1482
|
+
for (const listener of listeners) listener();
|
|
1483
|
+
};
|
|
1484
|
+
const events = eventListeners();
|
|
1485
|
+
const bot = config.botId;
|
|
1486
|
+
/** `ready` fires once per chat, not again when a sign-in reloads the conversation. */
|
|
1487
|
+
let announced = false;
|
|
1488
|
+
const announce = () => {
|
|
1489
|
+
if (announced) return;
|
|
1490
|
+
announced = true;
|
|
1491
|
+
events.emit({
|
|
1492
|
+
type: "ready",
|
|
1493
|
+
bot
|
|
1494
|
+
});
|
|
1495
|
+
};
|
|
1496
|
+
const { focus, onFocus } = focusRequests();
|
|
1497
|
+
let localId = 0;
|
|
1498
|
+
const nextLocalId = () => `local_${++localId}`;
|
|
1499
|
+
/** The current run between start() and stop(); async work of an earlier run stops there. */
|
|
1500
|
+
let run;
|
|
1501
|
+
/** Signed in (or anonymous) for good: requests may go out. */
|
|
1502
|
+
let identityReady = false;
|
|
1503
|
+
/** The visible conversation is the one this browser should show. */
|
|
1504
|
+
let loaded = false;
|
|
1505
|
+
let identities = Promise.resolve();
|
|
1506
|
+
let history;
|
|
1507
|
+
/** The turn being answered, aborted when the chat stops. */
|
|
1508
|
+
let turn;
|
|
1509
|
+
/** Reports how the turn being answered ended; stop() calls it before anyone stops listening. */
|
|
1510
|
+
let endTurn;
|
|
1511
|
+
/**
|
|
1512
|
+
* Per rating key: what the server confirmed, and the latest request. Ratings of one answer go out
|
|
1513
|
+
* one at a time, so the server ends with the latest that succeeded and a failure rolls back to it.
|
|
1514
|
+
*/
|
|
1515
|
+
const rated = /* @__PURE__ */ new Map();
|
|
1516
|
+
/** In-flight uploads by pending file key, cancelled when the file is removed. */
|
|
1517
|
+
const uploads = /* @__PURE__ */ new Map();
|
|
1518
|
+
let recording;
|
|
1519
|
+
/** Set while the browser asks for the microphone, so a double click starts one recording. */
|
|
1520
|
+
let starting = false;
|
|
1521
|
+
/** Ends the dictation at maxSeconds; a timer, because animation frames stop in hidden frames. */
|
|
1522
|
+
let limit;
|
|
1523
|
+
let clock;
|
|
1524
|
+
/** Stops a dictation and throws the audio away. */
|
|
1525
|
+
const discardRecording = () => {
|
|
1526
|
+
clearTimeout(limit);
|
|
1527
|
+
clearInterval(clock);
|
|
1528
|
+
recording?.cancel();
|
|
1529
|
+
recording = void 0;
|
|
1530
|
+
if (state.dictation !== "idle") set({ dictation: "idle" });
|
|
1531
|
+
};
|
|
1532
|
+
/** Restores the stored conversation (about 2 s upstream, so the chat shows a loading state). */
|
|
1533
|
+
const loadHistory = () => {
|
|
1534
|
+
history?.abort();
|
|
1535
|
+
if (!client.hasConversation()) {
|
|
1536
|
+
history = void 0;
|
|
1537
|
+
loaded = true;
|
|
1538
|
+
set({ phase: "ready" });
|
|
1539
|
+
announce();
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
const controller = new AbortController();
|
|
1543
|
+
history = controller;
|
|
1544
|
+
set({ phase: "loading" });
|
|
1545
|
+
client.loadHistory(controller.signal).then((messages) => {
|
|
1546
|
+
if (controller.signal.aborted) return;
|
|
1547
|
+
loaded = true;
|
|
1548
|
+
set({ messages: messages.map(fromHistory) });
|
|
1549
|
+
}).catch((error) => {
|
|
1550
|
+
if (!controller.signal.aborted) set({ error: error instanceof SessionRefused ? error.message : t("error.history") });
|
|
1551
|
+
}).finally(() => {
|
|
1552
|
+
if (history !== controller) return;
|
|
1553
|
+
history = void 0;
|
|
1554
|
+
set({ phase: "ready" });
|
|
1555
|
+
if (loaded) announce();
|
|
1556
|
+
});
|
|
1557
|
+
};
|
|
1558
|
+
const onVisibility = () => {
|
|
1559
|
+
if (document.visibilityState === "hidden") discardRecording();
|
|
1560
|
+
};
|
|
1561
|
+
const cancelUploads = (keys) => {
|
|
1562
|
+
for (const key of [...keys]) {
|
|
1563
|
+
uploads.get(key)?.abort();
|
|
1564
|
+
uploads.delete(key);
|
|
1565
|
+
}
|
|
1566
|
+
};
|
|
1567
|
+
const attach = async (file) => {
|
|
1568
|
+
if (!allowed) return;
|
|
1569
|
+
const key = nextLocalId();
|
|
1570
|
+
const update = (change) => set({ files: state.files.map((item) => item.key === key ? {
|
|
1571
|
+
...item,
|
|
1572
|
+
...change
|
|
1573
|
+
} : item) });
|
|
1574
|
+
const controller = new AbortController();
|
|
1575
|
+
uploads.set(key, controller);
|
|
1576
|
+
set({ files: [...state.files, {
|
|
1577
|
+
key,
|
|
1578
|
+
name: file.name,
|
|
1579
|
+
status: "uploading"
|
|
1580
|
+
}] });
|
|
1581
|
+
const fail = (error) => {
|
|
1582
|
+
uploads.delete(key);
|
|
1583
|
+
if (!controller.signal.aborted) update({
|
|
1584
|
+
status: "error",
|
|
1585
|
+
error
|
|
1586
|
+
});
|
|
1587
|
+
};
|
|
1588
|
+
let prepared;
|
|
1589
|
+
try {
|
|
1590
|
+
prepared = await prepareFile(file, allowed);
|
|
1591
|
+
} catch {
|
|
1592
|
+
fail(t("attachment.unsupported"));
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
if (prepared.blob.size > allowed.maxBytes) {
|
|
1596
|
+
fail(t("attachment.tooLarge", { size: megabytes(allowed.maxBytes) }));
|
|
1597
|
+
return;
|
|
1598
|
+
}
|
|
1599
|
+
if (controller.signal.aborted) return;
|
|
1600
|
+
const previewUrl = prepared.kind === "image" ? URL.createObjectURL(prepared.blob) : void 0;
|
|
1601
|
+
update({
|
|
1602
|
+
name: prepared.name,
|
|
1603
|
+
kind: prepared.kind,
|
|
1604
|
+
previewUrl
|
|
1605
|
+
});
|
|
1606
|
+
const result = await client.upload(prepared.blob, prepared.name, controller.signal);
|
|
1607
|
+
uploads.delete(key);
|
|
1608
|
+
if (controller.signal.aborted) {
|
|
1609
|
+
revokePreviews([{ previewUrl }]);
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
update(result.ok ? {
|
|
1613
|
+
status: "ready",
|
|
1614
|
+
handle: result.file.id,
|
|
1615
|
+
name: result.file.name
|
|
1616
|
+
} : {
|
|
1617
|
+
status: "error",
|
|
1618
|
+
error: result.message
|
|
1619
|
+
});
|
|
1620
|
+
};
|
|
1621
|
+
const actions = {
|
|
1622
|
+
async send(picked) {
|
|
1623
|
+
const text = (picked ?? state.draft).trim();
|
|
1624
|
+
if (picked === void 0 ? !canSend(state) : state.phase !== "ready" || state.busy || text === "") return;
|
|
1625
|
+
const ready = picked === void 0 ? state.files.filter((file) => file.status === "ready") : [];
|
|
1626
|
+
const files = ready.flatMap(({ name, kind, previewUrl }) => kind ? [{
|
|
1627
|
+
name,
|
|
1628
|
+
kind,
|
|
1629
|
+
previewUrl
|
|
1630
|
+
}] : []);
|
|
1631
|
+
const handles = ready.flatMap((file) => file.handle ? [file.handle] : []);
|
|
1632
|
+
const latest = state.messages.at(-1);
|
|
1633
|
+
const source = picked === void 0 ? "typed" : latest?.role === "assistant" && latest.replies?.includes(text) ? "reply" : "starter";
|
|
1634
|
+
if (picked === void 0) revokePreviews(state.files.filter((file) => file.status !== "ready"));
|
|
1635
|
+
set({
|
|
1636
|
+
...picked === void 0 ? {
|
|
1637
|
+
files: [],
|
|
1638
|
+
draft: ""
|
|
1639
|
+
} : {},
|
|
1640
|
+
error: void 0,
|
|
1641
|
+
busy: true,
|
|
1642
|
+
messages: [...state.messages, {
|
|
1643
|
+
id: nextLocalId(),
|
|
1644
|
+
role: "user",
|
|
1645
|
+
text,
|
|
1646
|
+
citations: [],
|
|
1647
|
+
attachments: files.length,
|
|
1648
|
+
files,
|
|
1649
|
+
status: "done"
|
|
1650
|
+
}]
|
|
1651
|
+
});
|
|
1652
|
+
events.emit({
|
|
1653
|
+
type: "message.sent",
|
|
1654
|
+
bot,
|
|
1655
|
+
length: [...text].length,
|
|
1656
|
+
attachments: files.length,
|
|
1657
|
+
source
|
|
1658
|
+
});
|
|
1659
|
+
const context = config.pageContext ? state.page.context : void 0;
|
|
1660
|
+
const controller = new AbortController();
|
|
1661
|
+
turn = controller;
|
|
1662
|
+
const begun = Date.now();
|
|
1663
|
+
let failed = false;
|
|
1664
|
+
let answer;
|
|
1665
|
+
const end = (outcome) => {
|
|
1666
|
+
if (endTurn !== end) return;
|
|
1667
|
+
endTurn = void 0;
|
|
1668
|
+
const received = state.messages.find((message) => message.id === answer);
|
|
1669
|
+
events.emit({
|
|
1670
|
+
type: "message.received",
|
|
1671
|
+
bot,
|
|
1672
|
+
outcome,
|
|
1673
|
+
durationMs: Date.now() - begun,
|
|
1674
|
+
citations: received?.citations.length ?? 0
|
|
1675
|
+
});
|
|
1676
|
+
};
|
|
1677
|
+
endTurn = end;
|
|
1678
|
+
await client.send({
|
|
1679
|
+
text,
|
|
1680
|
+
attachments: handles,
|
|
1681
|
+
context
|
|
1682
|
+
}, (event) => {
|
|
1683
|
+
const next = activityFor(event, t);
|
|
1684
|
+
if (next !== void 0) set({ activity: next });
|
|
1685
|
+
if (event.type === "message.start") answer = event.messageId;
|
|
1686
|
+
if (event.type === "error") {
|
|
1687
|
+
failed = true;
|
|
1688
|
+
events.emit({
|
|
1689
|
+
type: "error",
|
|
1690
|
+
bot,
|
|
1691
|
+
code: event.code
|
|
1692
|
+
});
|
|
1693
|
+
set({
|
|
1694
|
+
error: event.message,
|
|
1695
|
+
messages: failStreaming(state.messages)
|
|
1696
|
+
});
|
|
1697
|
+
return;
|
|
1698
|
+
}
|
|
1699
|
+
set({ messages: applyEvent(state.messages, event) });
|
|
1700
|
+
}, controller.signal);
|
|
1701
|
+
if (turn === controller) turn = void 0;
|
|
1702
|
+
end(failed ? "failed" : controller.signal.aborted ? "stopped" : "completed");
|
|
1703
|
+
if (controller.signal.aborted) {
|
|
1704
|
+
set({
|
|
1705
|
+
activity: null,
|
|
1706
|
+
busy: false,
|
|
1707
|
+
messages: failStreaming(state.messages)
|
|
1708
|
+
});
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
set({
|
|
1712
|
+
activity: null,
|
|
1713
|
+
busy: false
|
|
1714
|
+
});
|
|
1715
|
+
focus("input");
|
|
1716
|
+
},
|
|
1717
|
+
setDraft(text) {
|
|
1718
|
+
set({ draft: text });
|
|
1719
|
+
},
|
|
1720
|
+
addFiles(files) {
|
|
1721
|
+
if (!allowed || files.length === 0) return;
|
|
1722
|
+
const room = allowed.maxPerMessage - state.files.length;
|
|
1723
|
+
if (files.length > room) set({ error: t("attachment.tooMany", { count: allowed.maxPerMessage }) });
|
|
1724
|
+
for (const file of files.slice(0, Math.max(0, room))) attach(file);
|
|
1725
|
+
},
|
|
1726
|
+
removeFile(key) {
|
|
1727
|
+
cancelUploads([key]);
|
|
1728
|
+
revokePreviews(state.files.filter((item) => item.key === key));
|
|
1729
|
+
set({ files: state.files.filter((item) => item.key !== key) });
|
|
1730
|
+
},
|
|
1731
|
+
async startDictation() {
|
|
1732
|
+
if (!voice || recording || starting || state.dictation !== "idle") return;
|
|
1733
|
+
set({ error: void 0 });
|
|
1734
|
+
starting = true;
|
|
1735
|
+
let started;
|
|
1736
|
+
try {
|
|
1737
|
+
started = await recorder.startRecording(voice.maxSeconds);
|
|
1738
|
+
} catch (error) {
|
|
1739
|
+
set({ error: t(MICROPHONE_MESSAGES[error instanceof MicrophoneError ? error.reason : "failed"]) });
|
|
1740
|
+
return;
|
|
1741
|
+
} finally {
|
|
1742
|
+
starting = false;
|
|
1743
|
+
}
|
|
1744
|
+
if (!run) {
|
|
1745
|
+
started.cancel();
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
recording = started;
|
|
1749
|
+
set({
|
|
1750
|
+
elapsed: 0,
|
|
1751
|
+
dictation: "recording"
|
|
1752
|
+
});
|
|
1753
|
+
focus("dictation");
|
|
1754
|
+
limit = setTimeout(() => void actions.finishDictation(), voice.maxSeconds * 1e3);
|
|
1755
|
+
const begun = Date.now();
|
|
1756
|
+
clock = setInterval(() => {
|
|
1757
|
+
const elapsed = Math.min(voice.maxSeconds, Math.floor((Date.now() - begun) / 1e3));
|
|
1758
|
+
if (elapsed !== state.elapsed) set({ elapsed });
|
|
1759
|
+
}, 250);
|
|
1760
|
+
},
|
|
1761
|
+
async finishDictation() {
|
|
1762
|
+
const current = recording;
|
|
1763
|
+
if (!current) return;
|
|
1764
|
+
recording = void 0;
|
|
1765
|
+
clearTimeout(limit);
|
|
1766
|
+
clearInterval(clock);
|
|
1767
|
+
set({ dictation: "transcribing" });
|
|
1768
|
+
const audio = await current.stop();
|
|
1769
|
+
if (audio.size < 1e3) {
|
|
1770
|
+
set({
|
|
1771
|
+
dictation: "idle",
|
|
1772
|
+
error: t("dictation.empty")
|
|
1773
|
+
});
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
const languages = [...navigator.languages.slice(0, 2), config.widget.locale];
|
|
1777
|
+
const result = await client.transcribe(audio, languages);
|
|
1778
|
+
set({ dictation: "idle" });
|
|
1779
|
+
if (!result.ok) set({ error: result.message });
|
|
1780
|
+
else if (result.text) {
|
|
1781
|
+
const draft = state.draft;
|
|
1782
|
+
set({ draft: draft.trim() ? `${draft.trimEnd()} ${result.text}` : result.text });
|
|
1783
|
+
}
|
|
1784
|
+
focus("input");
|
|
1785
|
+
},
|
|
1786
|
+
cancelDictation() {
|
|
1787
|
+
discardRecording();
|
|
1788
|
+
focus("input");
|
|
1789
|
+
},
|
|
1790
|
+
async newConversation() {
|
|
1791
|
+
set({ busy: true });
|
|
1792
|
+
await client.deleteConversation().catch(() => void 0);
|
|
1793
|
+
revokePreviews(state.messages.flatMap((message) => message.files ?? []));
|
|
1794
|
+
cancelUploads(uploads.keys());
|
|
1795
|
+
revokePreviews(state.files);
|
|
1796
|
+
set({
|
|
1797
|
+
files: [],
|
|
1798
|
+
messages: [],
|
|
1799
|
+
error: void 0,
|
|
1800
|
+
busy: false,
|
|
1801
|
+
commenting: void 0
|
|
1802
|
+
});
|
|
1803
|
+
events.emit({
|
|
1804
|
+
type: "conversation.reset",
|
|
1805
|
+
bot
|
|
1806
|
+
});
|
|
1807
|
+
focus("input");
|
|
1808
|
+
},
|
|
1809
|
+
async rate(messageId, rating, comment) {
|
|
1810
|
+
const feedback = state.messages.find((message) => message.id === messageId)?.feedback;
|
|
1811
|
+
if (!feedback) return;
|
|
1812
|
+
const { key } = feedback;
|
|
1813
|
+
const before = state.ratings[key];
|
|
1814
|
+
const text = comment?.trim().slice(0, MAX_COMMENT);
|
|
1815
|
+
const commented = rating === "down" && Boolean(text);
|
|
1816
|
+
const ratings = (value) => {
|
|
1817
|
+
const { [key]: _previous, ...others } = state.ratings;
|
|
1818
|
+
return value ? {
|
|
1819
|
+
...others,
|
|
1820
|
+
[key]: value
|
|
1821
|
+
} : others;
|
|
1822
|
+
};
|
|
1823
|
+
const entry = rated.get(key) ?? {
|
|
1824
|
+
confirmed: before,
|
|
1825
|
+
latest: 0,
|
|
1826
|
+
queue: Promise.resolve()
|
|
1827
|
+
};
|
|
1828
|
+
rated.set(key, entry);
|
|
1829
|
+
const request = ++entry.latest;
|
|
1830
|
+
set({
|
|
1831
|
+
ratings: ratings(rating),
|
|
1832
|
+
error: void 0,
|
|
1833
|
+
commenting: commented || rating === "down" && before !== "down" ? messageId : void 0
|
|
1834
|
+
});
|
|
1835
|
+
const sent = entry.queue.then(() => client.rate(feedback.handle, rating, rating === null ? void 0 : text));
|
|
1836
|
+
entry.queue = sent;
|
|
1837
|
+
const problem = await sent;
|
|
1838
|
+
if (!problem) {
|
|
1839
|
+
entry.confirmed = rating ?? void 0;
|
|
1840
|
+
client.rememberRating(key, rating);
|
|
1841
|
+
events.emit({
|
|
1842
|
+
type: "feedback",
|
|
1843
|
+
bot,
|
|
1844
|
+
rating,
|
|
1845
|
+
commented
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
if (entry.latest !== request) return;
|
|
1849
|
+
if (problem) set({
|
|
1850
|
+
ratings: ratings(entry.confirmed),
|
|
1851
|
+
error: problem,
|
|
1852
|
+
...commented ? {} : { commenting: void 0 }
|
|
1853
|
+
});
|
|
1854
|
+
else if (commented && state.commenting === messageId) set({ commenting: void 0 });
|
|
1855
|
+
},
|
|
1856
|
+
dismissComment() {
|
|
1857
|
+
if (state.commenting !== void 0) set({ commenting: void 0 });
|
|
1858
|
+
},
|
|
1859
|
+
focus() {
|
|
1860
|
+
focus("input", true);
|
|
1861
|
+
}
|
|
1862
|
+
};
|
|
1863
|
+
/** Counts language switches, so only the latest one applies. */
|
|
1864
|
+
let switches = 0;
|
|
1865
|
+
let language;
|
|
1866
|
+
return {
|
|
1867
|
+
get config() {
|
|
1868
|
+
return config;
|
|
1869
|
+
},
|
|
1870
|
+
actions,
|
|
1871
|
+
get t() {
|
|
1872
|
+
return t;
|
|
1873
|
+
},
|
|
1874
|
+
get language() {
|
|
1875
|
+
return language;
|
|
1876
|
+
},
|
|
1877
|
+
subscribe(listener) {
|
|
1878
|
+
listeners.add(listener);
|
|
1879
|
+
return () => listeners.delete(listener);
|
|
1880
|
+
},
|
|
1881
|
+
getSnapshot: () => state,
|
|
1882
|
+
getServerSnapshot: () => initial,
|
|
1883
|
+
start(startOptions = {}) {
|
|
1884
|
+
if (run) return;
|
|
1885
|
+
const current = {};
|
|
1886
|
+
run = current;
|
|
1887
|
+
set({
|
|
1888
|
+
ratings: client.ratings(),
|
|
1889
|
+
canDictate: voice !== void 0 && recorder.canRecord(),
|
|
1890
|
+
...state.phase === "starting" && client.hasConversation() ? { phase: "loading" } : {}
|
|
1891
|
+
});
|
|
1892
|
+
document.addEventListener("visibilitychange", onVisibility);
|
|
1893
|
+
(startOptions.handshake ?? Promise.resolve()).then(() => identities, () => identities).finally(() => {
|
|
1894
|
+
if (run !== current) return;
|
|
1895
|
+
identityReady = true;
|
|
1896
|
+
if (!loaded) loadHistory();
|
|
1897
|
+
else {
|
|
1898
|
+
if (state.phase !== "ready") set({ phase: "ready" });
|
|
1899
|
+
announce();
|
|
1900
|
+
}
|
|
1901
|
+
});
|
|
1902
|
+
},
|
|
1903
|
+
stop() {
|
|
1904
|
+
if (!run) return;
|
|
1905
|
+
run = void 0;
|
|
1906
|
+
document.removeEventListener("visibilitychange", onVisibility);
|
|
1907
|
+
history?.abort();
|
|
1908
|
+
history = void 0;
|
|
1909
|
+
endTurn?.("stopped");
|
|
1910
|
+
turn?.abort();
|
|
1911
|
+
turn = void 0;
|
|
1912
|
+
discardRecording();
|
|
1913
|
+
if (uploads.size > 0) {
|
|
1914
|
+
cancelUploads(uploads.keys());
|
|
1915
|
+
set({ files: state.files.filter((file) => file.status !== "uploading") });
|
|
1916
|
+
}
|
|
1917
|
+
},
|
|
1918
|
+
identify(token) {
|
|
1919
|
+
identities = identities.then(async () => {
|
|
1920
|
+
if (!await client.identify(token)) return;
|
|
1921
|
+
loaded = false;
|
|
1922
|
+
set({
|
|
1923
|
+
messages: [],
|
|
1924
|
+
error: void 0,
|
|
1925
|
+
commenting: void 0
|
|
1926
|
+
});
|
|
1927
|
+
if (identityReady && run) loadHistory();
|
|
1928
|
+
});
|
|
1929
|
+
},
|
|
1930
|
+
configure(page) {
|
|
1931
|
+
set({ page });
|
|
1932
|
+
},
|
|
1933
|
+
async setLocale(locale, next) {
|
|
1934
|
+
const id = ++switches;
|
|
1935
|
+
const fetched = next ? {
|
|
1936
|
+
widget: next.widget,
|
|
1937
|
+
language: void 0
|
|
1938
|
+
} : await client.fetchWidget(locale);
|
|
1939
|
+
if (id !== switches || fetched === void 0) return false;
|
|
1940
|
+
const { widget } = fetched;
|
|
1941
|
+
language = fetched.language;
|
|
1942
|
+
const { title, greeting, placeholder, launcherLabel, texts } = widget;
|
|
1943
|
+
config = {
|
|
1944
|
+
...config,
|
|
1945
|
+
widget: {
|
|
1946
|
+
...config.widget,
|
|
1947
|
+
locale: widget.locale,
|
|
1948
|
+
title,
|
|
1949
|
+
greeting,
|
|
1950
|
+
placeholder,
|
|
1951
|
+
launcherLabel,
|
|
1952
|
+
texts
|
|
1953
|
+
}
|
|
1954
|
+
};
|
|
1955
|
+
t = translator(texts);
|
|
1956
|
+
client.setLocale(widget.locale);
|
|
1957
|
+
set({});
|
|
1958
|
+
return true;
|
|
1959
|
+
},
|
|
1960
|
+
hide() {
|
|
1961
|
+
discardRecording();
|
|
1962
|
+
},
|
|
1963
|
+
level: () => recording?.level(),
|
|
1964
|
+
onFocus,
|
|
1965
|
+
onEvent: (listener) => events.on("*", listener)
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
// src/react/tool-results.tsx
|
|
1969
|
+
const RenderersContext = createContext(void 0);
|
|
1970
|
+
/** Provides `Root`'s `toolRenderers` to `ToolResults`. */
|
|
1971
|
+
function ToolRenderersProvider({ renderers, children }) {
|
|
1972
|
+
return /* @__PURE__ */ jsx(RenderersContext.Provider, {
|
|
1973
|
+
value: renderers,
|
|
1974
|
+
children
|
|
1975
|
+
});
|
|
1976
|
+
}
|
|
1977
|
+
/** Tool names already reported as having no component, so the console hears about each once. */
|
|
1978
|
+
const unregistered = /* @__PURE__ */ new Set();
|
|
1979
|
+
/** One card: if the developer's component throws, the card is left out and the chat goes on. */
|
|
1980
|
+
var Card = class extends Component {
|
|
1981
|
+
state = { failed: false };
|
|
1982
|
+
static getDerivedStateFromError() {
|
|
1983
|
+
return { failed: true };
|
|
1984
|
+
}
|
|
1985
|
+
componentDidCatch(error) {
|
|
1986
|
+
console.error(`[askdare] the component for tool "${this.props.name}" failed:`, error);
|
|
1987
|
+
}
|
|
1988
|
+
render() {
|
|
1989
|
+
return this.state.failed ? null : this.props.children;
|
|
1990
|
+
}
|
|
1991
|
+
};
|
|
1992
|
+
/**
|
|
1993
|
+
* The current message's tool payloads (ADR-0017), each drawn by the component registered for its
|
|
1994
|
+
* tool in `Root`'s `toolRenderers`, in call order: a group (`tool-results`) of cards
|
|
1995
|
+
* (`tool-result`, with `data-ask-tool`). A payload without a component shows nothing, and when
|
|
1996
|
+
* `toolRenderers` is set the console says so once per tool. Use it inside `MessageList`.
|
|
1997
|
+
*/
|
|
1998
|
+
function ToolResults(props) {
|
|
1999
|
+
const { ui } = useMessage();
|
|
2000
|
+
const renderers = useContext(RenderersContext);
|
|
2001
|
+
const missing = [];
|
|
2002
|
+
const cards = (ui ?? []).flatMap(({ callId, name, data }) => {
|
|
2003
|
+
const Renderer = renderers && Object.hasOwn(renderers, name) ? renderers[name] : void 0;
|
|
2004
|
+
if (!Renderer) {
|
|
2005
|
+
if (renderers) missing.push(name);
|
|
2006
|
+
return [];
|
|
2007
|
+
}
|
|
2008
|
+
return [/* @__PURE__ */ jsx("div", {
|
|
2009
|
+
"data-ask-part": "tool-result",
|
|
2010
|
+
"data-ask-tool": name,
|
|
2011
|
+
children: /* @__PURE__ */ jsx(Card, {
|
|
2012
|
+
name,
|
|
2013
|
+
children: /* @__PURE__ */ jsx(Renderer, {
|
|
2014
|
+
data,
|
|
2015
|
+
name,
|
|
2016
|
+
callId
|
|
2017
|
+
})
|
|
2018
|
+
})
|
|
2019
|
+
}, callId)];
|
|
2020
|
+
});
|
|
2021
|
+
const key = missing.join(" ");
|
|
2022
|
+
useEffect(() => {
|
|
2023
|
+
for (const name of missing) {
|
|
2024
|
+
if (unregistered.has(name)) continue;
|
|
2025
|
+
unregistered.add(name);
|
|
2026
|
+
console.warn(`[askdare] no component in toolRenderers for tool "${name}"; its card is hidden.`);
|
|
2027
|
+
}
|
|
2028
|
+
}, [key]);
|
|
2029
|
+
if (cards.length === 0) return null;
|
|
2030
|
+
return /* @__PURE__ */ jsx("div", {
|
|
2031
|
+
"data-ask-part": "tool-results",
|
|
2032
|
+
...props,
|
|
2033
|
+
children: cards
|
|
2034
|
+
});
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
* A link for a URL from a tool's payload: only `https:`, `http:` and `mailto:`, opened in a new
|
|
2038
|
+
* tab, as links in answers are. Any other URL (`javascript:`, `data:`, a relative path) renders
|
|
2039
|
+
* the text alone.
|
|
2040
|
+
*/
|
|
2041
|
+
function Link({ href, children, ...props }) {
|
|
2042
|
+
const safe = safeUrl(href);
|
|
2043
|
+
if (!safe) return /* @__PURE__ */ jsx("span", {
|
|
2044
|
+
...props,
|
|
2045
|
+
children
|
|
2046
|
+
});
|
|
2047
|
+
return /* @__PURE__ */ jsx("a", {
|
|
2048
|
+
...props,
|
|
2049
|
+
href: safe,
|
|
2050
|
+
target: "_blank",
|
|
2051
|
+
rel: "noopener noreferrer nofollow",
|
|
2052
|
+
children
|
|
2053
|
+
});
|
|
2054
|
+
}
|
|
2055
|
+
// src/react/root.tsx
|
|
2056
|
+
/** Refuses a config that would make the chat talk to, or load styles from, anywhere but its route. */
|
|
2057
|
+
function checkConfig(config) {
|
|
2058
|
+
if (!isBasePath(config.basePath)) throw new TypeError(`[askdare] The chat's basePath must be a path on this app, like /api/chat; got "${config.basePath}".`);
|
|
2059
|
+
for (const href of Object.values(config.styles ?? {})) if (!href.startsWith(`${config.basePath}/`) || href.includes("//") || href.includes("\\")) throw new TypeError(`[askdare] The chat's stylesheets must come from ${config.basePath}.`);
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* Runs one bot's chat for the components inside it, without rendering any element. Its props
|
|
2063
|
+
* take what `askdare('identify')` and `askdare('configure')` take, checked the same way.
|
|
2064
|
+
*/
|
|
2065
|
+
function Root({ config, identity, context, greeting, starters, onEvent, toolRenderers, children }) {
|
|
2066
|
+
checkConfig(config);
|
|
2067
|
+
const page = pageOptions({
|
|
2068
|
+
greeting,
|
|
2069
|
+
starters,
|
|
2070
|
+
context
|
|
2071
|
+
});
|
|
2072
|
+
const id = `${config.basePath} ${config.botId}`;
|
|
2073
|
+
const [held, setHeld] = useState(() => ({
|
|
2074
|
+
id,
|
|
2075
|
+
store: createChatStore(config, { page })
|
|
2076
|
+
}));
|
|
2077
|
+
let { store } = held;
|
|
2078
|
+
if (held.id !== id) {
|
|
2079
|
+
store = createChatStore(config, { page });
|
|
2080
|
+
setHeld({
|
|
2081
|
+
id,
|
|
2082
|
+
store
|
|
2083
|
+
});
|
|
2084
|
+
}
|
|
2085
|
+
const listener = useRef(onEvent);
|
|
2086
|
+
useLayoutEffect(() => {
|
|
2087
|
+
listener.current = onEvent;
|
|
2088
|
+
}, [onEvent]);
|
|
2089
|
+
useEffect(() => {
|
|
2090
|
+
if (identity === void 0) return;
|
|
2091
|
+
const token = identityToken(identity);
|
|
2092
|
+
if (token !== void 0) store.identify(token);
|
|
2093
|
+
}, [identity, store]);
|
|
2094
|
+
useEffect(() => {
|
|
2095
|
+
const stopEvents = store.onEvent((event) => listener.current?.(event));
|
|
2096
|
+
store.start();
|
|
2097
|
+
return () => {
|
|
2098
|
+
store.stop();
|
|
2099
|
+
stopEvents();
|
|
2100
|
+
};
|
|
2101
|
+
}, [store]);
|
|
2102
|
+
const locale = config.widget.locale;
|
|
2103
|
+
const latest = useRef(config);
|
|
2104
|
+
useLayoutEffect(() => {
|
|
2105
|
+
latest.current = config;
|
|
2106
|
+
}, [config]);
|
|
2107
|
+
useEffect(() => {
|
|
2108
|
+
if (store.config.widget.locale !== locale) store.setLocale(locale, latest.current);
|
|
2109
|
+
}, [locale, store]);
|
|
2110
|
+
const key = JSON.stringify(page);
|
|
2111
|
+
useEffect(() => {
|
|
2112
|
+
if (JSON.stringify(store.getSnapshot().page) !== key) store.configure(page);
|
|
2113
|
+
}, [key, store]);
|
|
2114
|
+
return /* @__PURE__ */ jsx(ChatProvider, {
|
|
2115
|
+
store,
|
|
2116
|
+
children: /* @__PURE__ */ jsx(ToolRenderersProvider, {
|
|
2117
|
+
renderers: toolRenderers,
|
|
2118
|
+
children
|
|
2119
|
+
})
|
|
2120
|
+
});
|
|
2121
|
+
}
|
|
2122
|
+
export { useOptionalMessage as C, useMessage as S, useTexts as T, MessageProvider as _, ToolResults as a, useChatState as b, pageLocale as c, safeUrl as d, pluralText as f, FrameContext as g, ChatProvider as h, ToolRenderersProvider as i, pageOptions as l, acceptTypes as m, checkConfig as n, createChatStore as o, canSend as p, Link as r, identityToken as s, Root as t, Markdown as u, useChat as v, useStore as w, useFrame as x, useChatConfig as y };
|