@boldare/askdare 0.3.0 → 0.5.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +14 -4
  3. package/dist/cli.js +111 -26
  4. package/dist/define-tool.js +1006 -8
  5. package/dist/embed.d.ts +19 -0
  6. package/dist/embed.js +250 -0
  7. package/dist/{store.d.ts → events.d.ts} +163 -54
  8. package/dist/index.d.ts +28 -2
  9. package/dist/index.js +74 -158
  10. package/dist/next.d.ts +70 -9
  11. package/dist/next.js +767 -169
  12. package/dist/react-marked.js +648 -624
  13. package/dist/react.d.ts +63 -77
  14. package/dist/react.js +148 -1854
  15. package/dist/root.js +2254 -0
  16. package/dist/tool-results.d.ts +140 -0
  17. package/dist/ui/askdare.css +21 -1
  18. package/dist/ui/avatar.tsx +1 -1
  19. package/dist/ui/chat.tsx +1 -1
  20. package/dist/ui/confirm.tsx +1 -1
  21. package/dist/ui/context.ts +1 -1
  22. package/dist/ui/feedback.tsx +1 -1
  23. package/dist/ui/footer.tsx +3 -15
  24. package/dist/ui/header.tsx +1 -1
  25. package/dist/ui/icons.tsx +1 -1
  26. package/dist/ui/index.ts +1 -1
  27. package/dist/ui/message.tsx +6 -4
  28. package/dist/ui/panel.tsx +17 -6
  29. package/dist/ui/welcome.tsx +1 -1
  30. package/docs/accessibility.md +83 -0
  31. package/docs/cli.md +5 -3
  32. package/docs/compliance.md +160 -0
  33. package/docs/configuration.md +58 -2
  34. package/docs/costs.md +8 -1
  35. package/docs/custom-store.md +2 -0
  36. package/docs/embedding.md +104 -0
  37. package/docs/events.md +1 -1
  38. package/docs/feedback.md +1 -1
  39. package/docs/going-public.md +15 -3
  40. package/docs/guardrails.md +128 -0
  41. package/docs/migrating-from-openai-assistant.md +1 -1
  42. package/docs/privacy.md +27 -3
  43. package/docs/protocol.md +15 -1
  44. package/docs/react.md +57 -3
  45. package/docs/styling.md +4 -3
  46. package/docs/support.md +3 -3
  47. package/docs/texts.md +127 -98
  48. package/docs/tools.md +20 -0
  49. package/docs/troubleshooting.md +30 -3
  50. package/llms.txt +14 -11
  51. package/package.json +10 -6
  52. package/skills/askdare/SKILL.md +12 -2
@@ -0,0 +1,19 @@
1
+
2
+ import { f as EmbedChatConfig, i as ToolRenderers } from "./tool-results.js";
3
+ import { ReactElement, ReactNode } from "react";
4
+ interface EmbedRootProps {
5
+ /** From `getEmbedConfig()` in the page's Server Component. */
6
+ readonly config: EmbedChatConfig;
7
+ /** Your components for tools' results, by tool name, as on `Root` (ADR-0017). */
8
+ readonly toolRenderers?: ToolRenderers | undefined;
9
+ readonly children?: ReactNode;
10
+ }
11
+ /**
12
+ * `Root` for your own page in the widget's iframe (ADR-0018): the page at a bot's `embedPath`.
13
+ * It connects to the loader on the embedding site exactly as askdare's own iframe does: the
14
+ * visitor's identity, `askdare('configure')`, the events for `askdare('on')`, hiding and closing
15
+ * the panel, and language switches. Put `DefaultChat`, an ejected copy of it or your own markup
16
+ * inside; `DefaultChat` then owns the document and shows a close button. Render one per page.
17
+ */
18
+ export declare function EmbedRoot({ config, toolRenderers, children }: EmbedRootProps): ReactElement;
19
+ export type { EmbedChatConfig, EmbedRootProps };
package/dist/embed.js ADDED
@@ -0,0 +1,250 @@
1
+ 'use client';
2
+ import { _ as ChatProvider, c as pageLocale, d as noteMissingDisclosure, i as ToolRenderersProvider, l as pageOptions, n as checkConfig, o as createChatStore, s as identityToken, v as FrameContext } 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 (process.env.NODE_ENV !== "production") noteMissingDisclosure(store);
219
+ if (connection.embedded && !inline) {
220
+ setClose(() => () => {
221
+ store.hide();
222
+ connection.close();
223
+ });
224
+ store.actions.focus();
225
+ }
226
+ return () => {
227
+ stopLocale();
228
+ unbind();
229
+ };
230
+ }, [
231
+ store,
232
+ origins,
233
+ inline
234
+ ]);
235
+ const frame = useMemo(() => ({ close }), [close]);
236
+ return /* @__PURE__ */ jsx(ChatProvider, {
237
+ store,
238
+ children: /* @__PURE__ */ jsx(ToolRenderersProvider, {
239
+ renderers: toolRenderers,
240
+ children: /* @__PURE__ */ jsxs(FrameContext.Provider, {
241
+ value: frame,
242
+ children: [/* @__PURE__ */ jsx("div", {
243
+ hidden: true,
244
+ "data-askdare-embed": ""
245
+ }), children]
246
+ })
247
+ })
248
+ });
249
+ }
250
+ export { EmbedRoot };
@@ -53,6 +53,8 @@ declare const EN: {
53
53
  readonly "launcher.open": "Open chat";
54
54
  readonly "launcher.close": "Close chat";
55
55
  readonly "launcher.unavailable": "The chat couldn’t load. Please try again later.";
56
+ readonly "humanCheck.label": "Checking that you’re human";
57
+ readonly "error.humanCheck": "We couldn’t confirm you’re human. Please try again.";
56
58
  readonly "error.connection": "Connection problem. Please try again.";
57
59
  readonly "error.history": "Could not load the previous conversation.";
58
60
  readonly "error.updated": "The assistant was updated. Please reload the page.";
@@ -91,6 +93,38 @@ declare const EN: {
91
93
  declare const PLURAL_BASES: readonly ["message.attachments"];
92
94
  declare const PLURAL_FORMS: readonly ["zero", "one", "two", "few", "many", "other"];
93
95
  type TextKey = keyof typeof EN | `${(typeof PLURAL_BASES)[number]}.${(typeof PLURAL_FORMS)[number]}`;
96
+ /**
97
+ * The challenge the chat shows before a new session starts. Public: it is sent to browsers, so it
98
+ * holds the site key and never the secret.
99
+ */
100
+ interface HumanChallenge {
101
+ /** Which widget the chat renders. Cloudflare Turnstile is the only one in 0.5. */
102
+ readonly provider: "turnstile";
103
+ /** The widget's public site key. */
104
+ readonly siteKey: string;
105
+ }
106
+ /** What a verifier gets with each token. */
107
+ interface HumanCheckContext {
108
+ /** The bot the session is for. */
109
+ readonly botId: string;
110
+ /** Aborts when the check takes too long or the visitor goes away; pass it to `fetch`. */
111
+ readonly signal: AbortSignal;
112
+ }
113
+ /**
114
+ * Checks that a new session comes from a person (ADR-0004, ADR-0019). The chat renders
115
+ * `challenge`, and `/session` passes the token it got to `verify`. Renewals of a live session
116
+ * aren't checked again. Build one with `turnstile()`, or implement it to check the token some
117
+ * other way.
118
+ */
119
+ interface HumanVerifier {
120
+ readonly challenge: HumanChallenge;
121
+ /**
122
+ * Resolves true when the token proves a person, false when it doesn't (invalid, expired or
123
+ * already used): the visitor is asked to try again. Throw when the check itself can't run, such
124
+ * as a missing secret or an outage: the session is refused and `onError` hears about it.
125
+ */
126
+ verify(token: string, context: HumanCheckContext): Promise<boolean>;
127
+ }
94
128
  /** A signed-in user, as the site's backend vouched for it (ADR-0009). */
95
129
  interface VisitorIdentity {
96
130
  /** The site's own user ID: the JWT's `sub`. */
@@ -159,13 +193,6 @@ interface ThemeDefinition {
159
193
  readonly dark?: Partial<ThemeTokens>;
160
194
  readonly variants?: Partial<ThemeVariants>;
161
195
  }
162
- interface ResolvedTheme {
163
- readonly preset: PresetName;
164
- readonly colorScheme: ColorScheme;
165
- readonly light: ThemeTokens;
166
- readonly dark: ThemeTokens;
167
- readonly variants: ThemeVariants;
168
- }
169
196
  /** Validates a theme once, so several bots can share it. Throws on invalid values. */
170
197
  declare function defineTheme(definition: ThemeDefinition): ThemeDefinition;
171
198
  /** What a tool may know about the request. Identity here is verified, never chosen by the model. */
@@ -189,9 +216,9 @@ interface ToolContext {
189
216
  type Jsonified<T> = T extends {
190
217
  toJSON(): infer R;
191
218
  } ? Jsonified<R> : T extends bigint | symbol | ((...args: never[]) => unknown) | undefined ? never : T extends readonly (infer Item)[] ? Jsonified<Item>[] : T extends object ? { [Key in keyof T as Jsonified<T[Key]> extends never ? never : Key]: Jsonified<T[Key]>; } : T;
192
- interface ToolDefinition<Input extends z.ZodObject, Output = unknown> {
219
+ interface ToolDefinition<Input extends z.ZodObject, Output = unknown, Ui = unknown, Name extends string = string> {
193
220
  /** Name the model calls, 1–64 letters, digits, `_` or `-`. */
194
- readonly name: string;
221
+ readonly name: Name;
195
222
  /** Tells the model when and how to use the tool. */
196
223
  readonly description: string;
197
224
  /**
@@ -212,20 +239,105 @@ interface ToolDefinition<Input extends z.ZodObject, Output = unknown> {
212
239
  * several calls of a turn define them, the last one wins.
213
240
  */
214
241
  readonly replies?: (output: Jsonified<Output>) => readonly string[] | undefined;
242
+ /**
243
+ * What the visitor may see of a successful result, for a component the site registers with
244
+ * `toolRenderers` (ADR-0017). Only this reaches the browser, never the result itself, so pick
245
+ * the fields a visitor may see. It gets the result as the model received it, parsed back from
246
+ * JSON, and runs again on every reload, so keep it pure: the same result, the same payload.
247
+ * Return plain JSON of at most 8 KB and 8 levels, or `undefined` or `null` for none; a payload
248
+ * over a limit is dropped whole. An answer shows at most 4, in call order.
249
+ */
250
+ readonly ui?: (output: Jsonified<Output>) => Ui | null | undefined;
215
251
  }
216
- interface Tool {
217
- readonly name: string;
252
+ /**
253
+ * A tool the bot can call. `Name` and `Ui` carry the tool's name and the type its `ui` returns,
254
+ * so a page can type its renderers with `import type` (ADR-0017).
255
+ */
256
+ interface Tool<Name extends string = string, Ui = unknown> {
257
+ readonly name: Name;
218
258
  readonly description: string;
219
259
  readonly input: z.ZodObject;
220
260
  readonly execute: (input: unknown, context: ToolContext) => unknown;
221
261
  readonly timeoutMs: number;
222
262
  readonly replies?: ((output: unknown) => readonly string[] | undefined) | undefined;
263
+ readonly ui?: ((output: unknown) => Ui | null | undefined) | undefined;
223
264
  }
224
265
  /**
225
266
  * Declares a server-side function the model may call. Arguments are validated with the schema
226
267
  * before `execute` runs; failures are reported to the model, never to the visitor.
227
268
  */
228
- declare function defineTool<Input extends z.ZodObject, Output = unknown>(definition: ToolDefinition<Input, Output>): Tool;
269
+ declare function defineTool<Input extends z.ZodObject, Output = unknown, Ui = never, const Name extends string = string>(definition: ToolDefinition<Input, Output, Ui, Name>): Tool<Name, Ui>;
270
+ /**
271
+ * OpenAI moderation for a bot's messages (ADR-0019). Each checked message costs one call to the
272
+ * moderation endpoint before the turn goes on (docs/costs.md).
273
+ */
274
+ interface ModerationConfig {
275
+ /**
276
+ * OpenAI moderation model, for example `omni-moderation-latest`. Required: the library never
277
+ * assumes a model.
278
+ */
279
+ readonly model: string;
280
+ /**
281
+ * What is checked: the visitor's message before it reaches the model, the finished answer
282
+ * before the visitor sees it, or both. Checking output holds each answer back until it is
283
+ * complete (docs/guardrails.md). Default `input`.
284
+ */
285
+ readonly check?: "input" | "output" | "both";
286
+ /**
287
+ * Moderation categories that block, such as `harassment` or `self-harm/intent`. Default: any
288
+ * category the model flags.
289
+ */
290
+ readonly categories?: readonly string[];
291
+ /** What the visitor sees when moderation blocks a message. Default: the `error.content_blocked` text. */
292
+ readonly message?: string;
293
+ }
294
+ /** Who and what a guardrail hook is checking, besides the text itself. */
295
+ interface GuardContext {
296
+ /** The bot's `id`. */
297
+ readonly bot: string;
298
+ /** Validated BCP 47 tag chosen by the widget. */
299
+ readonly locale: string;
300
+ /** The signed-in user, verified with IDENTITY_SECRET (ADR-0009); undefined when anonymous. */
301
+ readonly identity?: VisitorIdentity | undefined;
302
+ }
303
+ /**
304
+ * What an `onInput` or `onOutput` hook decides: let the text through, block the turn (with an
305
+ * optional text for the visitor, at most 300 characters), or replace the text. Returning
306
+ * `undefined` lets it through.
307
+ */
308
+ type GuardVerdict = {
309
+ readonly action: "allow";
310
+ } | {
311
+ readonly action: "block";
312
+ readonly message?: string;
313
+ } | {
314
+ readonly action: "redact";
315
+ readonly text: string;
316
+ };
317
+ /** An `onInput` or `onOutput` hook. Runs on the server; whatever it throws lets the text through. */
318
+ type GuardHook = (text: string, context: GuardContext) => GuardVerdict | undefined | Promise<GuardVerdict | undefined>;
319
+ /** The guardrail options of `defineBot` (ADR-0019). Every one is off when absent. */
320
+ interface GuardrailOptions {
321
+ /** OpenAI moderation on input, output or both. Off when absent. */
322
+ readonly moderation?: ModerationConfig | undefined;
323
+ /**
324
+ * Your own rule for each visitor message, before it reaches the model (and before moderation):
325
+ * allow it, block the turn, or replace the text the model gets. Files and the page's
326
+ * description are not passed to it.
327
+ */
328
+ readonly onInput?: GuardHook | undefined;
329
+ /**
330
+ * Your own rule for each finished answer, before the visitor sees it (and before moderation).
331
+ * Setting it holds every answer back until it is complete (docs/guardrails.md).
332
+ */
333
+ readonly onOutput?: GuardHook | undefined;
334
+ /**
335
+ * `untrusted` hands your tools' results to the model wrapped as third-party data that it must
336
+ * not follow as instructions (prompt-injection hardening, ADR-0004). Recommended for tools that
337
+ * return text from outside your control. Default `trusted`: results go to the model as they are.
338
+ */
339
+ readonly toolResults?: "trusted" | "untrusted" | undefined;
340
+ }
229
341
  /** Per-request context available when building instructions. */
230
342
  interface BotContext {
231
343
  /** Validated BCP 47 tag chosen by the widget. */
@@ -275,6 +387,12 @@ interface BotSecurity {
275
387
  * always allowed. Enforced by the browser through `frame-ancestors` (ADR-0004, ADR-0005).
276
388
  */
277
389
  readonly allowedOrigins?: readonly string[];
390
+ /**
391
+ * Asks for a human check before a new session starts, such as `turnstile({ siteKey })`
392
+ * (ADR-0019). The chat shows the challenge, and the iframe's CSP allows its provider. Renewals
393
+ * of a live session aren't checked again. Off when absent.
394
+ */
395
+ readonly humanVerifier?: HumanVerifier | undefined;
278
396
  }
279
397
  interface KnowledgeConfig {
280
398
  /** Vector store filled by `askdare kb sync`, usually `process.env.KB_VECTOR_STORE_ID`. */
@@ -303,6 +421,8 @@ interface VoiceConfig {
303
421
  /** Longest dictation; recording stops by itself at this point. Default 60 seconds. */
304
422
  readonly maxSeconds?: number;
305
423
  }
424
+ /** Overrides for the texts the chat shows, by key (see the dictionary in the docs). */
425
+ type WidgetTexts = Readonly<Partial<Record<TextKey, string>>>;
306
426
  /** Public widget settings. Everything here is sent to browsers, so never put secrets in it. */
307
427
  interface WidgetConfig {
308
428
  /** Shortcut for `texts['header.title']`. */
@@ -319,8 +439,13 @@ interface WidgetConfig {
319
439
  * Polish; other languages show English unless you set `texts`. Default `en`.
320
440
  */
321
441
  readonly locale?: string;
322
- /** Overrides for any text the widget shows, by key (see the dictionary in the docs). */
323
- readonly texts?: Readonly<Partial<Record<TextKey, string>>>;
442
+ /**
443
+ * Overrides for any text the widget shows, by key (see the dictionary in the docs). Either one
444
+ * set for every language (`{ 'launcher.label': 'Questions?' }`), or one set per language
445
+ * (`{ en: {...}, pl: {...} }`): a visitor gets the set for their language tag, else one for
446
+ * the same language, and a language without a built-in dictionary gets the `en` set.
447
+ */
448
+ readonly texts?: WidgetTexts | Readonly<Record<string, WidgetTexts>>;
324
449
  /**
325
450
  * The note that visitors are talking to an AI (EU AI Act, art. 50), shown under the message
326
451
  * field, with an optional link to your privacy policy (an https URL or a path on your app).
@@ -356,31 +481,8 @@ interface WidgetConfig {
356
481
  /** Default `auto`: follows the visitor's system setting. */
357
482
  readonly colorScheme?: ColorScheme;
358
483
  }
359
- /** Widget settings with defaults applied and the theme resolved. */
360
- interface BotWidget {
361
- /** In the configured locale (English for `auto`); the visitor may see another language. */
362
- readonly title: string;
363
- readonly subtitle: string;
364
- readonly greeting: string;
365
- readonly placeholder: string;
366
- /** The configured BCP 47 tag, or `auto`. */
367
- readonly locale: string;
368
- readonly starters: readonly string[];
369
- /** Whether this bot lets visitors rate answers, when the handler has `onFeedback`. */
370
- readonly feedback: boolean;
371
- /** Whether the model suggests reply options. Only the server reads it. */
372
- readonly replies: "suggest" | "off";
373
- readonly avatar: string | undefined;
374
- readonly launcherLabel: string;
375
- /** Text overrides, including the title, greeting, placeholder and launcher label shortcuts. */
376
- readonly texts: Readonly<Partial<Record<TextKey, string>>>;
377
- readonly disclosure: false | {
378
- readonly privacyUrl: string | undefined;
379
- };
380
- readonly css: string;
381
- readonly theme: ResolvedTheme;
382
- }
383
- interface BotDefinition {
484
+ /** A bot's settings; the guardrail options (`moderation`, `onInput`, …) are in `GuardrailOptions`. */
485
+ interface BotDefinition extends GuardrailOptions {
384
486
  /** URL-safe identifier used in the script tag (`widget.js?bot=<id>`) and routes. */
385
487
  readonly id: string;
386
488
  /** OpenAI model ID. Required on purpose: the library never assumes a model (ADR-0002). */
@@ -409,27 +511,29 @@ interface BotDefinition {
409
511
  readonly voice?: VoiceConfig | undefined;
410
512
  readonly security?: BotSecurity;
411
513
  readonly widget?: WidgetConfig;
514
+ /**
515
+ * A page of this app to show in the widget's iframe instead of askdare's own, such as
516
+ * `/askdare/support` (ADR-0018): the chat route redirects the iframe there. Render it with
517
+ * `EmbedRoot` from `@boldare/askdare/embed` and `getEmbedConfig`, and send `embedPageHeaders`
518
+ * with it. Off when absent: askdare's page, which needs nothing from you.
519
+ */
520
+ readonly embedPath?: string | undefined;
412
521
  }
413
- interface Bot {
522
+ /**
523
+ * What `defineBot` returns. Pass it to `createChatHandler`, `getChatConfig` and `getEmbedConfig`;
524
+ * the settings it resolved are internal (ADR-0020).
525
+ */
526
+ interface BotHandle {
527
+ /** The bot's `id` from its definition. */
414
528
  readonly id: string;
415
- readonly model: string;
416
- readonly instructions: (context: BotContext) => string;
417
- readonly limits: Required<BotLimits>;
418
- readonly tools: readonly Tool[];
419
- readonly pageContext: boolean;
420
- readonly knowledge: Required<KnowledgeConfig> | undefined;
421
- readonly attachments: Required<AttachmentConfig> | undefined;
422
- readonly voice: Required<VoiceConfig> | undefined;
423
- readonly security: {
424
- readonly allowedOrigins: readonly string[];
425
- };
426
- readonly widget: BotWidget;
529
+ /** The bot's `embedPath` from its definition, for matching its page in `proxy.ts` (ADR-0018). */
530
+ readonly embedPath: string | undefined;
427
531
  }
428
532
  /**
429
533
  * Declares a chatbot. Validates eagerly so misconfiguration fails at startup, not on the first
430
534
  * visitor's message.
431
535
  */
432
- declare function defineBot(definition: BotDefinition): Bot;
536
+ declare function defineBot(definition: BotDefinition): BotHandle;
433
537
  /** Result of incrementing a fixed-window counter. */
434
538
  interface CounterHit {
435
539
  /** Counter value after the increment. */
@@ -451,4 +555,9 @@ interface RateLimitStore {
451
555
  /** True for stores that are shared across server instances. */
452
556
  readonly shared: boolean;
453
557
  }
454
- export { VisitorIdentity as C, ThemeVariants as S, ColorScheme as _, BotContext as a, PresetName as b, BotSecurity as c, WidgetConfig as d, defineBot as f, defineTool as g, ToolDefinition as h, Bot as i, KnowledgeConfig as l, ToolContext as m, RateLimitStore as n, BotDefinition as o, Tool as p, AttachmentConfig as r, BotLimits as s, CounterHit as t, VoiceConfig as u, ThemeDefinition as v, ThemeTokens as x, defineTheme as y };
558
+ /** Stable error codes sent to clients. The accompanying message never contains internals. */
559
+ declare const ERROR_CODES: readonly ["invalid_input", "unauthorized", "session_expired", "not_found", "rate_limited", "budget_exceeded", "bot_unavailable", "content_blocked", "timeout", "upstream_error", "internal_error"];
560
+ type ErrorCode = (typeof ERROR_CODES)[number];
561
+ declare const MESSAGE_END_REASONS: readonly ["completed", "max_steps", "max_output_tokens", "timeout", "content_filter", "aborted"];
562
+ type MessageEndReason = (typeof MESSAGE_END_REASONS)[number];
563
+ export { ThemeVariants as A, ToolDefinition as C, defineTheme as D, ThemeDefinition as E, HumanChallenge as M, HumanCheckContext as N, PresetName as O, HumanVerifier as P, ToolContext as S, ColorScheme as T, GuardHook as _, RateLimitStore as a, ModerationConfig as b, BotDefinition as c, BotSecurity as d, KnowledgeConfig as f, GuardContext as g, defineBot as h, CounterHit as i, VisitorIdentity as j, ThemeTokens as k, BotHandle as l, WidgetConfig as m, ErrorCode as n, AttachmentConfig as o, VoiceConfig as p, MessageEndReason as r, BotContext as s, ERROR_CODES as t, BotLimits as u, GuardVerdict as v, defineTool as w, Tool as x, GuardrailOptions as y };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,33 @@
1
- import { C as VisitorIdentity, S as ThemeVariants, _ as ColorScheme, a as BotContext, b as PresetName, c as BotSecurity, d as WidgetConfig, f as defineBot, g as defineTool, h as ToolDefinition, i as Bot, l as KnowledgeConfig, m as ToolContext, n as RateLimitStore, o as BotDefinition, p as Tool, r as AttachmentConfig, s as BotLimits, t as CounterHit, u as VoiceConfig, v as ThemeDefinition, x as ThemeTokens, y as defineTheme } from "./store.js";
1
+ import { A as ThemeVariants, C as ToolDefinition, D as defineTheme, E as ThemeDefinition, M as HumanChallenge, N as HumanCheckContext, O as PresetName, P as HumanVerifier, S as ToolContext, T as ColorScheme, _ as GuardHook, a as RateLimitStore, b as ModerationConfig, c as BotDefinition, d as BotSecurity, f as KnowledgeConfig, g as GuardContext, h as defineBot, i as CounterHit, j as VisitorIdentity, k as ThemeTokens, l as BotHandle, m as WidgetConfig, n as ErrorCode, o as AttachmentConfig, p as VoiceConfig, s as BotContext, t as ERROR_CODES, u as BotLimits, v as GuardVerdict, w as defineTool, x as Tool, y as GuardrailOptions } from "./events.js";
2
2
  /**
3
3
  * Version of the SSE wire protocol between the askdare server and its clients.
4
4
  * Bumped on any breaking change to event names or payloads (ADR-0006).
5
5
  */
6
6
  export declare const PROTOCOL_VERSION: 1;
7
- export { type AttachmentConfig, type Bot, type BotContext, type BotDefinition, type BotLimits, type BotSecurity, type ColorScheme, type CounterHit, type KnowledgeConfig, type PresetName, type RateLimitStore, type ThemeDefinition, type ThemeTokens, type ThemeVariants, type Tool, type ToolContext, type ToolDefinition, type VisitorIdentity, type VoiceConfig, type WidgetConfig, defineBot, defineTheme, defineTool };
7
+ interface TurnstileOptions {
8
+ /** The widget's site key from the Cloudflare dashboard. Public: browsers receive it. */
9
+ readonly siteKey: string;
10
+ /**
11
+ * The widget's secret key. Default `process.env.TURNSTILE_SECRET_KEY`, read at the first check,
12
+ * so building the app never needs it.
13
+ */
14
+ readonly secretKey?: string;
15
+ /**
16
+ * Host names the challenge may have been solved on, compared with siteverify's `hostname`, such
17
+ * as `['www.example.com']`: the host of your chat route's app. Off by default, because the
18
+ * dashboard's hostname list already limits where the widget runs, and a proxy that serves the
19
+ * app under another name would be refused. Skipped with Cloudflare's test secret keys.
20
+ */
21
+ readonly hostnames?: readonly string[];
22
+ }
23
+ /**
24
+ * A `HumanVerifier` backed by Cloudflare Turnstile: the chat shows the Turnstile widget before a
25
+ * new session starts, and the server checks its token with Cloudflare's siteverify endpoint.
26
+ *
27
+ * ```ts
28
+ * // The site key is public; the secret key comes from TURNSTILE_SECRET_KEY.
29
+ * security: { humanVerifier: turnstile({ siteKey: '0x4AAAAAAA…' }) }
30
+ * ```
31
+ */
32
+ export declare function turnstile(options: TurnstileOptions): HumanVerifier;
33
+ export { type AttachmentConfig, type BotContext, type BotDefinition, type BotHandle, type BotLimits, type BotSecurity, type ColorScheme, type CounterHit, ERROR_CODES, type ErrorCode, type GuardContext, type GuardHook, type GuardVerdict, type GuardrailOptions, type HumanChallenge, type HumanCheckContext, type HumanVerifier, type KnowledgeConfig, type ModerationConfig, type PresetName, type RateLimitStore, type ThemeDefinition, type ThemeTokens, type ThemeVariants, type Tool, type ToolContext, type ToolDefinition, type TurnstileOptions, type VisitorIdentity, type VoiceConfig, type WidgetConfig, defineBot, defineTheme, defineTool };