@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/embed.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { c as pageLocale, g as FrameContext, h as ChatProvider, i as ToolRenderersProvider, l as pageOptions, n as checkConfig, o as createChatStore, s as identityToken } from "./root.js";
|
|
3
|
+
import { useEffect, useMemo, useState } from "react";
|
|
4
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
5
|
+
// src/chat/bind-bridge.ts
|
|
6
|
+
/**
|
|
7
|
+
* Connects the iframe's chat store to the loader on the host page: per-page greeting, starters
|
|
8
|
+
* and context, the page's identity, hiding the panel, and the chat's events for the page's
|
|
9
|
+
* listeners. Returns a function that disconnects it.
|
|
10
|
+
*/
|
|
11
|
+
function bindBridge(store, bridge) {
|
|
12
|
+
let active = true;
|
|
13
|
+
let stopIdentify = () => {};
|
|
14
|
+
const stopConfigure = bridge.onConfigure((page) => store.configure(page));
|
|
15
|
+
const stopHidden = bridge.onHidden(() => store.hide());
|
|
16
|
+
const stopEvents = store.onEvent((event) => bridge.emit(event));
|
|
17
|
+
store.start({ handshake: bridge.handshake.then(() => {
|
|
18
|
+
if (active) stopIdentify = bridge.onIdentify((token) => store.identify(token));
|
|
19
|
+
}) });
|
|
20
|
+
return () => {
|
|
21
|
+
active = false;
|
|
22
|
+
stopConfigure();
|
|
23
|
+
stopHidden();
|
|
24
|
+
stopIdentify();
|
|
25
|
+
store.stop();
|
|
26
|
+
stopEvents();
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
// src/chat/host-bridge.ts
|
|
30
|
+
/** Handshakes that arrived before the chat connected, kept by `holdHandshake`. */
|
|
31
|
+
const held = [];
|
|
32
|
+
/** Stops holding: the first `connectToHost` takes over, and nothing is kept after it. */
|
|
33
|
+
let release = () => {};
|
|
34
|
+
/**
|
|
35
|
+
* Keeps the loader's handshake if it arrives before `connectToHost` runs: the loader sends it once,
|
|
36
|
+
* when the iframe has loaded, and a page that hydrates later (the site's own page at `embedPath`,
|
|
37
|
+
* ADR-0018) would miss it. Only messages from the parent window are kept; `connectToHost` checks
|
|
38
|
+
* their origin as it checks any other.
|
|
39
|
+
*/
|
|
40
|
+
function holdHandshake() {
|
|
41
|
+
if (typeof window === "undefined" || window.parent === window) return;
|
|
42
|
+
const hold = (event) => {
|
|
43
|
+
const data = event.data;
|
|
44
|
+
if (event.source === window.parent && data?.v === 1 && data.type === "askdare:init") held.push(event);
|
|
45
|
+
};
|
|
46
|
+
window.addEventListener("message", hold);
|
|
47
|
+
release = () => window.removeEventListener("message", hold);
|
|
48
|
+
}
|
|
49
|
+
/** How long to wait for the loader before the first request, when it never says hello. */
|
|
50
|
+
const HANDSHAKE_TIMEOUT_MS = 3e3;
|
|
51
|
+
/**
|
|
52
|
+
* Accepts the loader's handshake only from the parent window and an allowed origin, then talks
|
|
53
|
+
* exclusively over the transferred port (ADR-0005). Messages from anywhere else are ignored.
|
|
54
|
+
*/
|
|
55
|
+
function connectToHost(allowedOrigins, options = {}) {
|
|
56
|
+
const embedded = window.parent !== window;
|
|
57
|
+
let port;
|
|
58
|
+
const hiddenListeners = /* @__PURE__ */ new Set();
|
|
59
|
+
const configureListeners = /* @__PURE__ */ new Set();
|
|
60
|
+
let latest;
|
|
61
|
+
const identifyListeners = /* @__PURE__ */ new Set();
|
|
62
|
+
const localeListeners = /* @__PURE__ */ new Set();
|
|
63
|
+
let identity;
|
|
64
|
+
const setIdentity = (token) => {
|
|
65
|
+
if (token === void 0) return;
|
|
66
|
+
identity = token;
|
|
67
|
+
for (const listener of identifyListeners) listener(token);
|
|
68
|
+
};
|
|
69
|
+
let connected = () => {};
|
|
70
|
+
const handshake = new Promise((resolve) => {
|
|
71
|
+
connected = resolve;
|
|
72
|
+
if (embedded) setTimeout(resolve, HANDSHAKE_TIMEOUT_MS);
|
|
73
|
+
else resolve();
|
|
74
|
+
});
|
|
75
|
+
const allowed = /* @__PURE__ */ new Set([window.location.origin, ...allowedOrigins]);
|
|
76
|
+
const onMessage = (event) => {
|
|
77
|
+
if (port && !options.hello || event.source !== window.parent || !allowed.has(event.origin)) return;
|
|
78
|
+
const data = event.data;
|
|
79
|
+
if (data?.v !== 1 || data.type !== "askdare:init" || !event.ports[0]) return;
|
|
80
|
+
port = event.ports[0];
|
|
81
|
+
port.onmessage = (portEvent) => {
|
|
82
|
+
if (portEvent.data?.["v"] !== 1) return;
|
|
83
|
+
if (portEvent.data["type"] === "hidden") for (const listener of hiddenListeners) listener();
|
|
84
|
+
else if (portEvent.data["type"] === "configure") {
|
|
85
|
+
latest = pageOptions(portEvent.data);
|
|
86
|
+
for (const listener of configureListeners) listener(latest);
|
|
87
|
+
} else if (portEvent.data["type"] === "identify") setIdentity(identityToken(portEvent.data["token"]));
|
|
88
|
+
else if (portEvent.data["type"] === "locale") {
|
|
89
|
+
const locale = pageLocale(portEvent.data["locale"]);
|
|
90
|
+
const inPlace = portEvent.data["inPlace"] === 1;
|
|
91
|
+
if (locale) for (const listener of localeListeners) listener(locale, inPlace);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
port.start();
|
|
95
|
+
port.postMessage({
|
|
96
|
+
v: 1,
|
|
97
|
+
type: "ready"
|
|
98
|
+
});
|
|
99
|
+
if (!options.hello) window.removeEventListener("message", onMessage);
|
|
100
|
+
setIdentity(identityToken(data.identity));
|
|
101
|
+
connected();
|
|
102
|
+
};
|
|
103
|
+
if (embedded) {
|
|
104
|
+
window.addEventListener("message", onMessage);
|
|
105
|
+
release();
|
|
106
|
+
for (const event of held.splice(0)) onMessage(event);
|
|
107
|
+
if (options.hello && !port) for (const origin of allowed) window.parent.postMessage({
|
|
108
|
+
v: 1,
|
|
109
|
+
type: "askdare:hello"
|
|
110
|
+
}, origin);
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
embedded,
|
|
114
|
+
close() {
|
|
115
|
+
port?.postMessage({
|
|
116
|
+
v: 1,
|
|
117
|
+
type: "close"
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
emit(event) {
|
|
121
|
+
port?.postMessage({
|
|
122
|
+
v: 1,
|
|
123
|
+
type: "event",
|
|
124
|
+
event
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
onHidden(listener) {
|
|
128
|
+
hiddenListeners.add(listener);
|
|
129
|
+
return () => hiddenListeners.delete(listener);
|
|
130
|
+
},
|
|
131
|
+
onConfigure(listener) {
|
|
132
|
+
configureListeners.add(listener);
|
|
133
|
+
if (latest) listener(latest);
|
|
134
|
+
return () => configureListeners.delete(listener);
|
|
135
|
+
},
|
|
136
|
+
handshake,
|
|
137
|
+
onIdentify(listener) {
|
|
138
|
+
identifyListeners.add(listener);
|
|
139
|
+
if (identity !== void 0) listener(identity);
|
|
140
|
+
return () => identifyListeners.delete(listener);
|
|
141
|
+
},
|
|
142
|
+
onLocale(listener) {
|
|
143
|
+
localeListeners.add(listener);
|
|
144
|
+
return () => localeListeners.delete(listener);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// src/chat/switch-locale.ts
|
|
149
|
+
/**
|
|
150
|
+
* Switches the chat's language when the page asks (ADR-0014). In place when the loader says so
|
|
151
|
+
* (`inPlace`, step 2): new texts, and the conversation, the draft and an answer under way stay.
|
|
152
|
+
* A loader from before step 2, or texts that can't be loaded for the language the page wants
|
|
153
|
+
* last, reload the chat instead; a switch overtaken by a later one does nothing.
|
|
154
|
+
*/
|
|
155
|
+
function switchLocale(store, bridge, effects) {
|
|
156
|
+
let wanted;
|
|
157
|
+
return bridge.onLocale((locale, inPlace) => {
|
|
158
|
+
wanted = locale;
|
|
159
|
+
if (!inPlace) {
|
|
160
|
+
effects.reload(locale);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
store.setLocale(locale).then((switched) => {
|
|
164
|
+
if (switched) effects.switched(locale, store.language ?? locale);
|
|
165
|
+
else if (wanted === locale) effects.reload(locale);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** This page's URL in `locale`, so a reload, by the visitor or after an error, keeps it. */
|
|
170
|
+
function withLang(locale) {
|
|
171
|
+
const url = new URL(location.href);
|
|
172
|
+
url.searchParams.set("lang", locale);
|
|
173
|
+
return url;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Follows the page's language in the chat's iframe, askdare's own page or a site's (ADR-0014,
|
|
177
|
+
* ADR-0018): in place when it can, else by reloading with the new `lang`. `unbind` disconnects the
|
|
178
|
+
* chat first, so the page hears an answer under way as stopped before the reload cuts it off.
|
|
179
|
+
*/
|
|
180
|
+
function followLocale(store, bridge, unbind) {
|
|
181
|
+
return switchLocale(store, bridge, {
|
|
182
|
+
reload(locale) {
|
|
183
|
+
unbind();
|
|
184
|
+
location.replace(withLang(locale));
|
|
185
|
+
},
|
|
186
|
+
switched(locale, language) {
|
|
187
|
+
document.documentElement.lang = language;
|
|
188
|
+
document.title = store.config.widget.title;
|
|
189
|
+
history.replaceState(history.state, "", withLang(locale));
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
// src/embed-root/embed-root.tsx
|
|
194
|
+
holdHandshake();
|
|
195
|
+
/**
|
|
196
|
+
* One connection to the loader per page, kept across remounts (React's Strict Mode runs effects
|
|
197
|
+
* twice). A page renders one EmbedRoot: the loader hands one port to the iframe's document.
|
|
198
|
+
*/
|
|
199
|
+
let bridge;
|
|
200
|
+
/**
|
|
201
|
+
* `Root` for your own page in the widget's iframe (ADR-0018): the page at a bot's `embedPath`.
|
|
202
|
+
* It connects to the loader on the embedding site exactly as askdare's own iframe does: the
|
|
203
|
+
* visitor's identity, `askdare('configure')`, the events for `askdare('on')`, hiding and closing
|
|
204
|
+
* the panel, and language switches. Put `DefaultChat`, an ejected copy of it or your own markup
|
|
205
|
+
* inside; `DefaultChat` then owns the document and shows a close button. Render one per page.
|
|
206
|
+
*/
|
|
207
|
+
function EmbedRoot({ config, toolRenderers, children }) {
|
|
208
|
+
checkConfig(config);
|
|
209
|
+
const [store] = useState(() => createChatStore(config));
|
|
210
|
+
const [close, setClose] = useState(void 0);
|
|
211
|
+
const inline = config.mode === "inline";
|
|
212
|
+
const origins = config.allowedOrigins.join(" ");
|
|
213
|
+
useEffect(() => {
|
|
214
|
+
bridge ??= connectToHost(origins.split(" ").filter(Boolean), { hello: true });
|
|
215
|
+
const connection = bridge;
|
|
216
|
+
const unbind = bindBridge(store, connection);
|
|
217
|
+
const stopLocale = followLocale(store, connection, unbind);
|
|
218
|
+
if (connection.embedded && !inline) {
|
|
219
|
+
setClose(() => () => {
|
|
220
|
+
store.hide();
|
|
221
|
+
connection.close();
|
|
222
|
+
});
|
|
223
|
+
store.actions.focus();
|
|
224
|
+
}
|
|
225
|
+
return () => {
|
|
226
|
+
stopLocale();
|
|
227
|
+
unbind();
|
|
228
|
+
};
|
|
229
|
+
}, [
|
|
230
|
+
store,
|
|
231
|
+
origins,
|
|
232
|
+
inline
|
|
233
|
+
]);
|
|
234
|
+
const frame = useMemo(() => ({ close }), [close]);
|
|
235
|
+
return /* @__PURE__ */ jsx(ChatProvider, {
|
|
236
|
+
store,
|
|
237
|
+
children: /* @__PURE__ */ jsx(ToolRenderersProvider, {
|
|
238
|
+
renderers: toolRenderers,
|
|
239
|
+
children: /* @__PURE__ */ jsxs(FrameContext.Provider, {
|
|
240
|
+
value: frame,
|
|
241
|
+
children: [/* @__PURE__ */ jsx("div", {
|
|
242
|
+
hidden: true,
|
|
243
|
+
"data-askdare-embed": ""
|
|
244
|
+
}), children]
|
|
245
|
+
})
|
|
246
|
+
})
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
export { EmbedRoot };
|
package/dist/index.js
CHANGED
|
@@ -1,166 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
// src/bot/define-bot.ts
|
|
4
|
-
const DEFAULT_LIMITS = {
|
|
5
|
-
maxOutputTokens: 1024,
|
|
6
|
-
maxInputChars: 4e3,
|
|
7
|
-
maxSteps: 5,
|
|
8
|
-
turnTimeoutMs: 12e4,
|
|
9
|
-
dailyTokens: 2e6,
|
|
10
|
-
dailyTokensPerIp: 2e5,
|
|
11
|
-
sessionsPerIpPerHour: 30,
|
|
12
|
-
conversationsPerIpPerHour: 20,
|
|
13
|
-
messagesPerVisitorPerMinute: 10,
|
|
14
|
-
messagesPerIpPerMinute: 30,
|
|
15
|
-
maxTurns: 50,
|
|
16
|
-
uploadsPerVisitorPerHour: 20,
|
|
17
|
-
uploadsPerIpPerHour: 60,
|
|
18
|
-
uploadsPerDay: 500,
|
|
19
|
-
transcriptionsPerVisitorPerHour: 30,
|
|
20
|
-
voiceSecondsPerDay: 3600,
|
|
21
|
-
voiceSecondsPerIpPerDay: 600
|
|
22
|
-
};
|
|
23
|
-
/** An https URL or a path on your app (no protocol-relative URLs). */
|
|
24
|
-
const LINK = /^(https:\/\/[^\s"'<>\\]{1,500}|\/(?![/\\])[^\s"'<>\\]{0,500})$/;
|
|
25
|
-
/** A same-origin path (served by your app, allowed by the iframe CSP) or a small raster data URL. */
|
|
26
|
-
const AVATAR = /^(\/(?!\/)[\w\-./%]{1,200}|data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]{1,90000})$/;
|
|
27
|
-
const origin = z.string().refine((value) => {
|
|
28
|
-
try {
|
|
29
|
-
const url = new URL(value);
|
|
30
|
-
return (url.protocol === "https:" || url.protocol === "http:" && /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost)$/.test(url.hostname)) && url.origin === value && /^[a-z0-9.-]+$|^\[[0-9a-f:]+\]$/i.test(url.hostname);
|
|
31
|
-
} catch {
|
|
32
|
-
return false;
|
|
33
|
-
}
|
|
34
|
-
}, "must be an https origin like https://www.example.com (no path or wildcard; http only for localhost)");
|
|
35
|
-
const definitionSchema = z.object({
|
|
36
|
-
id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/, "use 1-48 lowercase letters, digits or dashes"),
|
|
37
|
-
model: z.string().trim().min(1, "is required"),
|
|
38
|
-
instructions: z.union([z.string().trim().min(1, "must not be empty"), z.function()]),
|
|
39
|
-
limits: z.object({
|
|
40
|
-
maxOutputTokens: z.number().int().min(16).max(128e3).optional(),
|
|
41
|
-
maxInputChars: z.number().int().min(1).max(1e5).optional(),
|
|
42
|
-
maxSteps: z.number().int().min(1).max(20).optional(),
|
|
43
|
-
turnTimeoutMs: z.number().int().min(1e3).max(9e5).optional(),
|
|
44
|
-
dailyTokens: z.number().int().min(1e3).optional(),
|
|
45
|
-
dailyTokensPerIp: z.number().int().min(100).optional(),
|
|
46
|
-
sessionsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
|
|
47
|
-
conversationsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
|
|
48
|
-
messagesPerVisitorPerMinute: z.number().int().min(1).max(1e3).optional(),
|
|
49
|
-
messagesPerIpPerMinute: z.number().int().min(1).max(1e4).optional(),
|
|
50
|
-
maxTurns: z.number().int().min(1).max(1e3).optional(),
|
|
51
|
-
uploadsPerVisitorPerHour: z.number().int().min(1).max(1e3).optional(),
|
|
52
|
-
uploadsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
|
|
53
|
-
uploadsPerDay: z.number().int().min(1).max(1e6).optional(),
|
|
54
|
-
transcriptionsPerVisitorPerHour: z.number().int().min(1).max(1e3).optional(),
|
|
55
|
-
voiceSecondsPerDay: z.number().int().min(60).optional(),
|
|
56
|
-
voiceSecondsPerIpPerDay: z.number().int().min(60).optional()
|
|
57
|
-
}).optional(),
|
|
58
|
-
tools: z.array(z.custom((value) => typeof value === "object" && value !== null && "execute" in value, "must be created with defineTool()")).max(64).refine((tools) => new Set(tools.map((tool) => tool.name)).size === tools.length, "must have unique names").refine((tools) => tools.every((tool) => tool.name !== "file_search"), "must not use the reserved name file_search").refine((tools) => tools.every((tool) => tool.name !== SUGGEST_REPLIES), `must not use the reserved name ${SUGGEST_REPLIES}`).optional(),
|
|
59
|
-
pageContext: z.boolean().optional(),
|
|
60
|
-
knowledge: z.object({
|
|
61
|
-
vectorStoreId: z.string().regex(/^vs_[A-Za-z0-9_-]+$/, "must be a vector store ID like vs_…"),
|
|
62
|
-
maxResults: z.number().int().min(1).max(50).optional()
|
|
63
|
-
}).optional(),
|
|
64
|
-
attachments: z.object({
|
|
65
|
-
images: z.boolean().optional(),
|
|
66
|
-
pdf: z.boolean().optional(),
|
|
67
|
-
maxBytes: z.number().int().min(1e3).max(2e7).optional(),
|
|
68
|
-
maxPerMessage: z.number().int().min(1).max(10).optional(),
|
|
69
|
-
maxPdfPages: z.number().int().min(1).max(500).optional()
|
|
70
|
-
}).refine((value) => value.images !== false || value.pdf !== false, "must allow images or pdf").optional(),
|
|
71
|
-
voice: z.object({
|
|
72
|
-
model: z.string().trim().min(1, "is required"),
|
|
73
|
-
maxSeconds: z.number().int().min(5).max(300).optional()
|
|
74
|
-
}).optional(),
|
|
75
|
-
security: z.object({ allowedOrigins: z.array(origin).max(50).optional() }).optional(),
|
|
76
|
-
widget: z.object({
|
|
77
|
-
title: z.string().trim().min(1).max(80).optional(),
|
|
78
|
-
greeting: z.string().trim().min(1).max(500).optional(),
|
|
79
|
-
placeholder: z.string().trim().min(1).max(120).optional(),
|
|
80
|
-
locale: z.string().refine((value) => value === "auto" || canonicalLocale(value) !== void 0, "must be auto or a BCP 47 tag like en or pl-PL").optional(),
|
|
81
|
-
texts: z.partialRecord(z.enum(TEXT_KEYS), z.string().trim().min(1).max(300)).optional(),
|
|
82
|
-
disclosure: z.union([z.literal(false), z.object({ privacyUrl: z.string().regex(LINK, "must be an https URL or a path like /privacy").optional() }).strict()]).optional(),
|
|
83
|
-
css: z.string().max(5e4).optional(),
|
|
84
|
-
subtitle: z.string().trim().min(1).max(120).optional(),
|
|
85
|
-
starters: z.array(z.string().trim().min(1).max(80)).max(4).optional(),
|
|
86
|
-
feedback: z.boolean().optional(),
|
|
87
|
-
replies: z.enum(["suggest", "off"]).optional(),
|
|
88
|
-
avatar: z.string().regex(AVATAR, "must be a path like /avatar.png or a PNG, JPEG, WebP or GIF data URL").optional(),
|
|
89
|
-
launcherLabel: z.string().trim().min(1).max(40).optional(),
|
|
90
|
-
theme: z.union([z.enum(PRESET_NAMES), themeDefinitionSchema]).optional(),
|
|
91
|
-
colorScheme: z.enum([
|
|
92
|
-
"auto",
|
|
93
|
-
"light",
|
|
94
|
-
"dark"
|
|
95
|
-
]).optional()
|
|
96
|
-
}).optional()
|
|
97
|
-
});
|
|
98
|
-
/**
|
|
99
|
-
* Declares a chatbot. Validates eagerly so misconfiguration fails at startup, not on the first
|
|
100
|
-
* visitor's message.
|
|
101
|
-
*/
|
|
102
|
-
function defineBot(definition) {
|
|
103
|
-
const parsed = definitionSchema.safeParse(definition);
|
|
104
|
-
if (!parsed.success) {
|
|
105
|
-
const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"} ${issue.message}`).join("; ");
|
|
106
|
-
const hint = parsed.error.issues.some((issue) => issue.path.join(".") === "model") ? " Set the model in the bot definition, usually as model: process.env.ASKDARE_MODEL with ASKDARE_MODEL in .env.local and in every environment that builds or runs the app (on Vercel: Production and Preview)." : "";
|
|
107
|
-
throw new TypeError(`[askdare] Invalid bot "${String(definition.id)}": ${issues}.${hint}`);
|
|
108
|
-
}
|
|
109
|
-
const { instructions } = definition;
|
|
110
|
-
const widget = definition.widget ?? {};
|
|
111
|
-
const locale = widget.locale ?? "en";
|
|
112
|
-
const overrides = Object.freeze({
|
|
113
|
-
...widget.texts,
|
|
114
|
-
...widget.title ? { "header.title": widget.title } : {},
|
|
115
|
-
...widget.greeting ? { "welcome.greeting": widget.greeting } : {},
|
|
116
|
-
...widget.placeholder ? { "composer.placeholder": widget.placeholder } : {},
|
|
117
|
-
...widget.launcherLabel ? { "launcher.label": widget.launcherLabel } : {}
|
|
118
|
-
});
|
|
119
|
-
const texts = textsFor(locale === "auto" ? "en" : locale, overrides);
|
|
120
|
-
const theme = resolveTheme(definition.widget?.theme, definition.widget?.colorScheme ?? "auto");
|
|
121
|
-
if (typeof definition.widget?.theme === "object" && globalThis.process?.env?.["NODE_ENV"] !== "production") for (const warning of themeWarnings(theme)) console.warn(`[askdare] Bot "${definition.id}" theme: ${warning}.`);
|
|
122
|
-
return Object.freeze({
|
|
123
|
-
id: definition.id,
|
|
124
|
-
model: definition.model.trim(),
|
|
125
|
-
instructions: typeof instructions === "string" ? () => instructions : instructions,
|
|
126
|
-
limits: Object.freeze({
|
|
127
|
-
...DEFAULT_LIMITS,
|
|
128
|
-
...definition.limits
|
|
129
|
-
}),
|
|
130
|
-
tools: Object.freeze([...definition.tools ?? []]),
|
|
131
|
-
pageContext: definition.pageContext ?? false,
|
|
132
|
-
knowledge: definition.knowledge ? Object.freeze({
|
|
133
|
-
vectorStoreId: definition.knowledge.vectorStoreId,
|
|
134
|
-
maxResults: definition.knowledge.maxResults ?? 5
|
|
135
|
-
}) : void 0,
|
|
136
|
-
attachments: definition.attachments ? Object.freeze({
|
|
137
|
-
images: definition.attachments.images ?? true,
|
|
138
|
-
pdf: definition.attachments.pdf ?? true,
|
|
139
|
-
maxBytes: definition.attachments.maxBytes ?? 4e6,
|
|
140
|
-
maxPerMessage: definition.attachments.maxPerMessage ?? 3,
|
|
141
|
-
maxPdfPages: definition.attachments.maxPdfPages ?? 50
|
|
142
|
-
}) : void 0,
|
|
143
|
-
voice: definition.voice ? Object.freeze({
|
|
144
|
-
model: definition.voice.model.trim(),
|
|
145
|
-
maxSeconds: definition.voice.maxSeconds ?? 60
|
|
146
|
-
}) : void 0,
|
|
147
|
-
security: Object.freeze({ allowedOrigins: Object.freeze([...new Set(definition.security?.allowedOrigins ?? [])]) }),
|
|
148
|
-
widget: Object.freeze({
|
|
149
|
-
title: texts["header.title"] ?? "",
|
|
150
|
-
subtitle: widget.subtitle ?? "",
|
|
151
|
-
greeting: texts["welcome.greeting"] ?? "",
|
|
152
|
-
placeholder: texts["composer.placeholder"] ?? "",
|
|
153
|
-
locale,
|
|
154
|
-
starters: Object.freeze([...widget.starters ?? []]),
|
|
155
|
-
feedback: widget.feedback ?? true,
|
|
156
|
-
replies: widget.replies ?? "off",
|
|
157
|
-
avatar: widget.avatar,
|
|
158
|
-
launcherLabel: texts["launcher.label"] ?? "",
|
|
159
|
-
texts: overrides,
|
|
160
|
-
disclosure: widget.disclosure === false ? false : Object.freeze({ privacyUrl: widget.disclosure?.privacyUrl }),
|
|
161
|
-
css: widget.css ?? "",
|
|
162
|
-
theme
|
|
163
|
-
})
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
export { PROTOCOL_VERSION, defineBot, defineTheme, defineTool };
|
|
1
|
+
export { c as PROTOCOL_VERSION, l as defineBot, y as defineTheme, n as defineTool } from "./define-tool.js";
|
package/dist/next.d.ts
CHANGED
|
@@ -57,6 +57,13 @@ interface ChatConfig {
|
|
|
57
57
|
/** From `getChatConfig`, for a chat inside a page. The iframe links its own stylesheets. */
|
|
58
58
|
readonly styles?: ChatStyles;
|
|
59
59
|
}
|
|
60
|
+
/** What `EmbedRoot` from `@boldare/askdare/embed` needs; `getEmbedConfig` builds it (ADR-0018). */
|
|
61
|
+
interface EmbedChatConfig extends ChatConfig {
|
|
62
|
+
/** Origins whose pages may hand the chat its connection to the loader (ADR-0005). */
|
|
63
|
+
readonly allowedOrigins: readonly string[];
|
|
64
|
+
/** `inline` inside an element of the host page, `floating` in the widget's panel. */
|
|
65
|
+
readonly mode: "floating" | "inline";
|
|
66
|
+
}
|
|
60
67
|
/**
|
|
61
68
|
* Which proxy to trust when reading the client IP:
|
|
62
69
|
* - `vercel`: Vercel overwrites `x-forwarded-for` and sets `x-real-ip`, so both are reliable.
|
|
@@ -248,4 +255,47 @@ interface ChatConfigOptions {
|
|
|
248
255
|
* ```
|
|
249
256
|
*/
|
|
250
257
|
export declare function getChatConfig(options: ChatConfigOptions): ChatConfig;
|
|
251
|
-
|
|
258
|
+
/** A page's search parameters, as Next.js hands them to it or as `URLSearchParams`. */
|
|
259
|
+
type EmbedSearchParams = URLSearchParams | Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
260
|
+
interface EmbedConfigOptions {
|
|
261
|
+
/** The same bots as in `createChatHandler`. */
|
|
262
|
+
readonly bots: readonly Bot[];
|
|
263
|
+
/** The id of the bot whose `embedPath` this page is. */
|
|
264
|
+
readonly bot: string;
|
|
265
|
+
/** Path of the chat route, the same as in `createChatHandler`. Default `/api/chat`. */
|
|
266
|
+
readonly basePath?: string;
|
|
267
|
+
/** The page's search parameters: the chat route passes the language and the mode in them. */
|
|
268
|
+
readonly searchParams: EmbedSearchParams;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* The configuration for the page at a bot's `embedPath` (ADR-0018), read in its Server Component
|
|
272
|
+
* from the language and the mode that the chat route passes in the URL:
|
|
273
|
+
*
|
|
274
|
+
* ```tsx
|
|
275
|
+
* // app/(askdare)/askdare/support/page.tsx
|
|
276
|
+
* const config = getEmbedConfig({ bots, bot: 'support', searchParams: await searchParams });
|
|
277
|
+
* return <Frame config={config} />; // a client component with <EmbedRoot> and <DefaultChat>
|
|
278
|
+
* ```
|
|
279
|
+
*/
|
|
280
|
+
export declare function getEmbedConfig(options: EmbedConfigOptions): EmbedChatConfig;
|
|
281
|
+
/** One response header, in the shape of `headers()` in `next.config.ts`. */
|
|
282
|
+
interface EmbedPageHeader {
|
|
283
|
+
readonly key: string;
|
|
284
|
+
readonly value: string;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* The headers the page at a bot's `embedPath` must send, as askdare's own iframe page does
|
|
288
|
+
* (ADR-0018): who may frame it, the microphone only with voice input, and the referrer policy.
|
|
289
|
+
* Set them for the page's path in `next.config.ts`:
|
|
290
|
+
*
|
|
291
|
+
* ```ts
|
|
292
|
+
* async headers() {
|
|
293
|
+
* return [{ source: '/askdare/support', headers: embedPageHeaders({ bots, bot: 'support' }) }];
|
|
294
|
+
* }
|
|
295
|
+
* ```
|
|
296
|
+
*/
|
|
297
|
+
export declare function embedPageHeaders(options: {
|
|
298
|
+
readonly bots: readonly Bot[];
|
|
299
|
+
readonly bot: string;
|
|
300
|
+
}): EmbedPageHeader[];
|
|
301
|
+
export type { ChatAttachments, ChatConfig, ChatConfigOptions, ChatErrorReport, ChatFeedbackReport, ChatHandlerLimitsOptions, ChatHandlerOptions, ChatHandlers, ChatStyles, ChatTokenUsage, ChatToolCallReport, ChatUsageReport, ChatWidget, EmbedChatConfig, EmbedConfigOptions, EmbedPageHeader, EmbedSearchParams, RouteHandler, TrustProxy };
|