@boldare/askdare 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @boldare/askdare
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - de9caf4: New route `GET <basePath>/config/<bot>?lang=<tag>`: the bot's public configuration in one language, built like the chat document's, so it never carries the model, instructions, tools or vector stores. It prepares switching the chat's language in place (ADR-0014, step 2). A bot with a fixed locale ignores `lang`, and an invalid tag answers `400` with `invalid_input`. Additive within protocol version 1.
8
+ - 82af455: A bot can show a page of your app in the widget's iframe instead of askdare's own (ADR-0018). Set `defineBot({ embedPath: '/askdare/support' })`, and the chat route redirects the iframe there with the visitor's language and the mode; the loader on the embedding sites doesn't change. `@boldare/askdare/next` adds `getEmbedConfig({ bots, bot, searchParams })`, the configuration for that page, and `embedPageHeaders({ bots, bot })`, the `frame-ancestors`, `Permissions-Policy` and `Referrer-Policy` headers it must send, to send from `proxy.ts`. `askdare doctor` follows the redirect and checks the page: no redirect in front of it, `EmbedRoot` on it, who may frame it and the microphone rule. The page renders the chat with `EmbedRoot` from `@boldare/askdare/embed`.
9
+ - 1e30933: Your own page in the widget's iframe (ADR-0018). A new entry, `@boldare/askdare/embed`, exports `EmbedRoot`: render it on the page a bot's `embedPath` points to, with `getEmbedConfig`, and put `DefaultChat`, an ejected copy or your own markup inside. It connects to the loader on the embedding site exactly as askdare's own page does (identity, `configure`, events, closing, language switches), so the widget on every site uses your components and draws your `toolRenderers`. Inside `EmbedRoot`, `DefaultChat` and an ejected copy of it own the document: an `h1` and a close button. A new hook, `useFrame()`, gives your own markup the same close action. The loader answers a new `askdare:hello` from its own iframe, so a page that hydrates after its load event still connects. Send the page's headers from `proxy.ts` with `embedPageHeaders`; the guide is in Embedding.
10
+ - e1fadd3: The chat switches its language in place (ADR-0014, step 2). When the page calls `askdare('configure', { locale })` or follows `<html lang>` with `data-follow-lang`, the chat no longer reloads: it fetches its texts for the new language from `GET <basePath>/config/<bot>` and keeps the conversation, the unsent message and an answer still streaming, which now finishes instead of being reported as `stopped`. New answers follow the new language. If the texts can't be loaded, the chat reloads as before. In React, a `Root` whose config changes only its `locale` switches the same chat instead of starting another one. `GET /config/<bot>` also answers `Content-Language`, the language its texts are written in.
11
+ - c994c50: A bot can give its texts per language: `widget.texts` also takes `{ en: {...}, pl: {...} }`, one set of overrides per language, so a chat with `locale: 'auto'` shows your own texts in each language (ADR-0014, step 2). A visitor gets the set for their language tag, else one for the same language; a language without a built-in dictionary gets the `en` set. The launcher on the page follows the same sets. A set's key wins over the `title`, `greeting`, `placeholder` and `launcherLabel` shortcuts for its language. The flat form is unchanged and still applies in every language. The chat document's `lang` follows a set written for the visitor's language.
12
+ - 3c7a2ca: Tool cards in the chat inside your page (ADR-0017). Give `Root` your components with `toolRenderers={{ find_slots: SlotList }}`, and the chat draws each tool's `ui` payload with its component under the answer, live and after a reload. A component gets `{ data, name, callId }`, typed from the tool with `ToolRendererProps<typeof findSlots>` and `import type`; `satisfies ToolRenderers<[typeof findSlots]>` checks the whole map. New primitives: `ToolResults` (parts `tool-results` and `tool-result`, with `data-ask-tool`), which `DefaultChat` places under the answer's text, and `Link`, which allows only `https`, `http` and `mailto` URLs from a payload. A tool without a component shows nothing, and a component that throws leaves out only its card. In the script-tag widget, a bot draws them when its iframe shows your own page (`embedPath` and `EmbedRoot`); askdare's own iframe page has no components to draw them with.
13
+ - 4ff33c4: Tools can pick what the visitor sees of their result (ADR-0017). `defineTool({ ui: (result) => data })` returns plain JSON of at most 8 KB for a card, list or table; only that reaches the browser, never the result itself. The server sends it as a new `tool.ui` event after the call (additive within protocol version 1), and `POST /history` brings every answer's payloads back as `ui` after a reload. At most 4 per answer, in call order; a failed call, a throwing `ui` or a payload over the limits shows nothing. `Tool` now carries the tool's name and payload type (`Tool<Name, Ui>`), so the React components that draw the payloads (`toolRenderers`) are typed from the tool. The browser keeps them on `ChatMessage.ui`.
14
+
15
+ ### Patch Changes
16
+
17
+ - ca03828: Dependencies: `openai` ^7.56.0 (was ^7.52.0) and `jose` ^6.2.17 (was ^6.2.15). Nothing changes in askdare's API.
18
+ - 95fb6e2: The README's "What you get" picture now shows what 0.4 adds: tool cards, drawn by your own React components, your own page inside the widget, and texts per language.
19
+
3
20
  ## 0.3.0
4
21
 
5
22
  ### Minor Changes
package/README.md CHANGED
@@ -38,9 +38,9 @@ export const bots = [
38
38
 
39
39
  ## What you get
40
40
 
41
- [![What it does: answers from your documents with citations, your own tools, images and PDFs, voice input, secure by default, the chat inside your own page with React, thumbs-up and thumbs-down ratings of answers, observability with OpenTelemetry, and chat events for analytics. New in 0.3: clickable answers suggested by the model, reply options from your tools, switching the chat's language from the page, and a one-click deploy. No database.](https://raw.githubusercontent.com/boldare/askdare/main/.github/assets/askdare-features.png)](https://askdare.vercel.app/#features)
41
+ [![What it does: answers from your documents with citations, your own tools, images and PDFs, voice input, secure by default, the chat inside your own page with React, thumbs-up and thumbs-down ratings of answers, observability with OpenTelemetry, and chat events for analytics. Also clickable answers suggested by the model, reply options from your tools, switching the chat's language from the page, and a one-click deploy. New in 0.4: tool cards, drawn by your own React components, your own page inside the widget, and texts per language. No database.](https://raw.githubusercontent.com/boldare/askdare/main/.github/assets/askdare-features.png)](https://askdare.vercel.app/#features)
42
42
 
43
- [Knowledge base](https://askdare.vercel.app/docs/knowledge-base) · [Tools](https://askdare.vercel.app/docs/tools) · [Attachments](https://askdare.vercel.app/docs/attachments) · [Voice input](https://askdare.vercel.app/docs/voice-input) · [The chat inside your page (React)](https://askdare.vercel.app/docs/react) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Security](https://github.com/boldare/askdare/blob/main/THREAT_MODEL.md)
43
+ [Knowledge base](https://askdare.vercel.app/docs/knowledge-base) · [Tools](https://askdare.vercel.app/docs/tools) · [Tool cards](https://askdare.vercel.app/docs/react#tool-cards) · [Reply options](https://askdare.vercel.app/docs/reply-options) · [Attachments](https://askdare.vercel.app/docs/attachments) · [Voice input](https://askdare.vercel.app/docs/voice-input) · [The chat inside your page (React)](https://askdare.vercel.app/docs/react) · [Your own page in the widget](https://askdare.vercel.app/docs/embedding#your-own-page-in-the-iframe) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Security](https://github.com/boldare/askdare/blob/main/THREAT_MODEL.md)
44
44
 
45
45
  ## Themes
46
46
 
package/dist/cli.js CHANGED
@@ -19,6 +19,14 @@ import OpenAI, { NotFoundError, toFile } from "openai";
19
19
  function isBasePath(value) {
20
20
  return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
21
21
  }
22
+ /**
23
+ * Whether a bot's `embedPath` is a page of the same app, like `/askdare/support` (ADR-0018): a
24
+ * path as `isBasePath` accepts it, without `.` or `..` segments, so a redirect to it can't leave
25
+ * the app or climb out of where it points.
26
+ */
27
+ function isEmbedPath(value) {
28
+ return isBasePath(value) && !value.split("/").some((segment) => /^\.{1,2}$/.test(segment));
29
+ }
22
30
  // src/cli/project.ts
23
31
  const LOCKFILES = [
24
32
  ["pnpm-lock.yaml", "pnpm"],
@@ -248,7 +256,12 @@ const doctorReportSchema = z.object({
248
256
  bots: z.array(z.object({
249
257
  id: z.string().max(48),
250
258
  checks: z.array(check).max(20),
251
- turnTimeoutMs: z.number().int().positive().optional()
259
+ turnTimeoutMs: z.number().int().positive().optional(),
260
+ embed: z.object({
261
+ path: z.string().refine(isEmbedPath),
262
+ allowedOrigins: z.array(z.string().max(300)).max(50),
263
+ voice: z.boolean()
264
+ }).optional()
252
265
  })).max(50)
253
266
  });
254
267
  // src/security/identity.ts
@@ -751,36 +764,95 @@ async function request(fetcher, url, init = {}) {
751
764
  function redirectOrMissing(response, url) {
752
765
  if (response.status >= 300 && response.status < 400) return fail(`${url} redirects to ${response.headers.get("location") ?? "another page"}.`, PROXY_FIX);
753
766
  }
767
+ /** The sources of the response's `frame-ancestors`, one list per policy that sets it. */
768
+ function frameAncestorsOf(response) {
769
+ return [...(response.headers.get("content-security-policy") ?? "").matchAll(/frame-ancestors\s+([^;,]*)/g)].map((match) => (match[1] ?? "").trim().split(/\s+/).filter(Boolean));
770
+ }
771
+ /** Whether `origin` may frame a page whose `frame-ancestors` sources are these. */
772
+ const mayFrame = (sources, origin, appOrigin) => sources.includes(origin) || origin === appOrigin && sources.includes("'self'");
773
+ const EMBED_HEADERS_FIX = (path, botId) => `Send embedPageHeaders({ bots, bot: '${botId}' }) from @boldare/askdare/next for ${path} in the headers() of next.config.`;
774
+ /**
775
+ * A bot's own page in the widget's iframe (ADR-0018): reachable without a login or a redirect,
776
+ * rendered with EmbedRoot, framed only by the app and the bot's allowed origins, and with the
777
+ * microphone off unless the bot has voice input.
778
+ */
779
+ async function embedPage(fetcher, base, botId, embed, origin) {
780
+ const appOrigin = new URL(base).origin;
781
+ const url = `${appOrigin}${embed.path}`;
782
+ const page = await request(fetcher, url);
783
+ if (!(page instanceof Response)) return [page];
784
+ const pageFix = `Leave ${embed.path} out of proxy.ts (its matcher) and of anything that signs visitors in or rewrites the path.`;
785
+ const missing = redirectOrMissing(page, url);
786
+ if (missing) {
787
+ await page.body?.cancel();
788
+ return [{
789
+ ...missing,
790
+ fix: pageFix
791
+ }];
792
+ }
793
+ if (!page.ok) {
794
+ await page.body?.cancel();
795
+ return [fail(`${url} answered HTTP ${page.status}.`, pageFix)];
796
+ }
797
+ const checks = [];
798
+ const html = await page.text();
799
+ checks.push(html.includes("data-askdare-embed") ? ok(`${embed.path} renders the chat.`) : fail(`${embed.path} doesn't render EmbedRoot.`, "Render <EmbedRoot config={getEmbedConfig(…)}> from @boldare/askdare/embed on that page."));
800
+ const fix = EMBED_HEADERS_FIX(embed.path, botId);
801
+ const ancestors = frameAncestorsOf(page);
802
+ const sources = ancestors[0] ?? [];
803
+ const allowed = /* @__PURE__ */ new Set([
804
+ "'self'",
805
+ appOrigin,
806
+ ...embed.allowedOrigins
807
+ ]);
808
+ const wider = sources.filter((source) => !allowed.has(source));
809
+ const absent = [...mayFrame(sources, appOrigin, appOrigin) ? [] : [appOrigin], ...embed.allowedOrigins.filter((item) => !sources.includes(item))];
810
+ if (page.headers.has("x-frame-options")) checks.push(fail(`X-Frame-Options on ${embed.path} stops sites from embedding it.`, fix));
811
+ else if (ancestors.length !== 1) checks.push(fail(ancestors.length === 0 ? `Any site can frame ${embed.path}: it has no frame-ancestors policy.` : `A second Content-Security-Policy on ${embed.path} overrides who may frame it.`, fix));
812
+ else if (wider.length > 0) checks.push(fail(`${embed.path} may be framed by more than the bot allows: ${wider.join(" ")}`, fix));
813
+ else if (absent.length > 0) checks.push(fail(`${absent.join(", ")} may not frame ${embed.path}, so the widget can't open there.`, fix));
814
+ else checks.push(ok(`Sites that may frame ${embed.path}: ${sources.join(" ")}`));
815
+ if (origin !== void 0 && ancestors.length === 1) checks.push(mayFrame(sources, origin, appOrigin) ? ok(`${origin} may embed the chat.`) : fail(`${origin} may not embed the chat: it isn't in the bot's security.allowedOrigins.`, `Add '${origin}' to security.allowedOrigins of bot "${botId}" and deploy.`));
816
+ const microphone = /(?:^|,)\s*microphone=([^,]*)/.exec(page.headers.get("permissions-policy") ?? "")?.[1]?.trim();
817
+ if (!embed.voice && microphone !== "()") checks.push(fail(`${embed.path} doesn't keep the microphone off for a bot without voice input.`, fix));
818
+ else if (embed.voice && !/\bself\b|\*/.test(microphone ?? "")) checks.push(warn(`${embed.path} doesn't allow the microphone, so dictation won't start.`, fix));
819
+ if (page.headers.has("set-cookie")) checks.push(warn(`Something sets cookies on ${embed.path}.`, "askdare uses no cookies; scripts on the page could read them with the chat."));
820
+ return checks;
821
+ }
754
822
  /** What the browser needs from widget.js and the chat page; things in front of askdare can break it. */
755
- async function headers(fetcher, base, botId, origin) {
823
+ async function headers(fetcher, base, botId, origin, embed) {
756
824
  const checks = [];
757
825
  const loaderUrl = `${base}/widget.js?bot=${botId}`;
758
826
  const loader = await request(fetcher, loaderUrl);
759
827
  if (!(loader instanceof Response)) return [loader];
760
828
  const embedUrl = `${base}/embed/${botId}`;
761
- const embed = await request(fetcher, embedUrl);
762
- if (!(embed instanceof Response)) return [embed];
829
+ const embedResponse = await request(fetcher, embedUrl);
830
+ if (!(embedResponse instanceof Response)) return [embedResponse];
763
831
  const loaderProblem = redirectOrMissing(loader, loaderUrl);
764
832
  if (loaderProblem) checks.push(loaderProblem);
765
833
  else if (!loader.ok || !(loader.headers.get("content-type") ?? "").includes("javascript")) checks.push(fail(`${loaderUrl} answered HTTP ${loader.status} instead of the script.`, PROXY_FIX));
766
834
  else checks.push(ok("widget.js loads."));
767
- const embedProblem = redirectOrMissing(embed, embedUrl);
768
- if (embedProblem) checks.push(embedProblem);
769
- else if (!embed.ok) checks.push(fail(`${embedUrl} answered HTTP ${embed.status}.`, PROXY_FIX));
770
- else {
771
- const ancestors = [...(embed.headers.get("content-security-policy") ?? "").matchAll(/frame-ancestors\s+([^;,]*)/g)].map((match) => match[1]?.trim());
772
- const fix = "Leave /api/chat out of the headers() in next.config and of proxy.ts.";
773
- if (origin !== void 0 && ancestors.length === 1) {
774
- const allowed = (ancestors[0] ?? "").split(/\s+/);
775
- const self = new URL(base).origin === origin;
776
- checks.push(self || allowed.includes(origin) ? ok(`${origin} may embed the chat.`) : fail(`${origin} may not embed the chat: it isn't in the bot's security.allowedOrigins.`, `Add '${origin}' to security.allowedOrigins of bot "${botId}" and deploy.`));
835
+ if (embed) {
836
+ const location = embedResponse.headers.get("location") ?? "";
837
+ if (embedResponse.status === 302 && (location === embed.path || location.startsWith(`${embed.path}?`))) {
838
+ checks.push(ok(`The widget opens ${embed.path}.`));
839
+ checks.push(...await embedPage(fetcher, base, botId, embed, origin));
840
+ } else checks.push(fail(`${embedUrl} doesn't send the widget to ${embed.path}.`, PROXY_FIX));
841
+ } else {
842
+ const embedProblem = redirectOrMissing(embedResponse, embedUrl);
843
+ if (embedProblem) checks.push(embedProblem);
844
+ else if (!embedResponse.ok) checks.push(fail(`${embedUrl} answered HTTP ${embedResponse.status}.`, PROXY_FIX));
845
+ else {
846
+ const ancestors = frameAncestorsOf(embedResponse);
847
+ const fix = "Leave /api/chat out of the headers() in next.config and of proxy.ts.";
848
+ if (origin !== void 0 && ancestors.length === 1) checks.push(mayFrame(ancestors[0] ?? [], origin, new URL(base).origin) ? ok(`${origin} may embed the chat.`) : fail(`${origin} may not embed the chat: it isn't in the bot's security.allowedOrigins.`, `Add '${origin}' to security.allowedOrigins of bot "${botId}" and deploy.`));
849
+ if (embedResponse.headers.has("x-frame-options")) checks.push(fail("X-Frame-Options on the chat page stops sites from embedding it.", fix));
850
+ else if (ancestors.length !== 1) checks.push(fail(ancestors.length === 0 ? "The chat page lost its frame-ancestors policy." : "A second Content-Security-Policy on the chat page overrides who may embed it.", fix));
851
+ else checks.push(ok(`Sites that may embed the chat: ${(ancestors[0] ?? []).join(" ")}`));
777
852
  }
778
- if (embed.headers.has("x-frame-options")) checks.push(fail("X-Frame-Options on the chat page stops sites from embedding it.", fix));
779
- else if (ancestors.length !== 1) checks.push(fail(ancestors.length === 0 ? "The chat page lost its frame-ancestors policy." : "A second Content-Security-Policy on the chat page overrides who may embed it.", fix));
780
- else checks.push(ok(`Sites that may embed the chat: ${ancestors[0]}`));
781
853
  }
782
- if (loader.headers.has("set-cookie") || embed.headers.has("set-cookie")) checks.push(warn("Something sets cookies on askdare's responses.", "askdare uses no cookies; leave /api/chat out of the code that sets them."));
783
- await Promise.all([loader.body?.cancel(), embed.body?.cancel()]);
854
+ if (loader.headers.has("set-cookie") || embedResponse.headers.has("set-cookie")) checks.push(warn("Something sets cookies on askdare's responses.", "askdare uses no cookies; leave /api/chat out of the code that sets them."));
855
+ await Promise.all([loader.body?.cancel(), embedResponse.body?.cancel()]);
784
856
  return checks;
785
857
  }
786
858
  /** The literal `maxDuration` of the askdare route, in seconds, if the file has one. */
@@ -855,7 +927,7 @@ async function live(options, project, env) {
855
927
  title: `Bot "${bot.id}"`,
856
928
  checks: [
857
929
  ...bot.checks,
858
- ...await headers(fetcher, base, bot.id, options.origin),
930
+ ...await headers(fetcher, base, bot.id, options.origin, bot.embed),
859
931
  ...timeout(bot, routeSeconds)
860
932
  ]
861
933
  });
@@ -1,4 +1,25 @@
1
1
  import { z } from "zod";
2
+ // src/base-path.ts
3
+ /**
4
+ * Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
5
+ * origin, a relative path or anything that needs escaping (ADR-0011). The server, the React entry
6
+ * and the CLI each bundle their own copy.
7
+ */
8
+ function isBasePath(value) {
9
+ return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
10
+ }
11
+ /**
12
+ * Whether a bot's `embedPath` is a page of the same app, like `/askdare/support` (ADR-0018): a
13
+ * path as `isBasePath` accepts it, without `.` or `..` segments, so a redirect to it can't leave
14
+ * the app or climb out of where it points.
15
+ */
16
+ function isEmbedPath(value) {
17
+ return isBasePath(value) && !value.split("/").some((segment) => /^\.{1,2}$/.test(segment));
18
+ }
19
+ /** Whether `path` is `basePath` itself or inside it. */
20
+ function isInside(path, basePath) {
21
+ return path === basePath || path.startsWith(`${basePath}/`);
22
+ }
2
23
  // src/i18n/locale.ts
3
24
  /** The canonical form of a BCP 47 tag that Intl accepts (plural rules need it), else undefined. */
4
25
  function canonicalLocale(tag) {
@@ -700,6 +721,217 @@ const readSuggestedReplies = (calls) => {
700
721
  const call = calls.findLast((stored) => stored.name === "suggest_replies" && stored.output !== void 0);
701
722
  return call && suggestedReplies(call.arguments);
702
723
  };
724
+ // src/bot/define-bot.ts
725
+ const DEFAULT_LIMITS = {
726
+ maxOutputTokens: 1024,
727
+ maxInputChars: 4e3,
728
+ maxSteps: 5,
729
+ turnTimeoutMs: 12e4,
730
+ dailyTokens: 2e6,
731
+ dailyTokensPerIp: 2e5,
732
+ sessionsPerIpPerHour: 30,
733
+ conversationsPerIpPerHour: 20,
734
+ messagesPerVisitorPerMinute: 10,
735
+ messagesPerIpPerMinute: 30,
736
+ maxTurns: 50,
737
+ uploadsPerVisitorPerHour: 20,
738
+ uploadsPerIpPerHour: 60,
739
+ uploadsPerDay: 500,
740
+ transcriptionsPerVisitorPerHour: 30,
741
+ voiceSecondsPerDay: 3600,
742
+ voiceSecondsPerIpPerDay: 600
743
+ };
744
+ /** An https URL or a path on your app (no protocol-relative URLs). */
745
+ const LINK$1 = /^(https:\/\/[^\s"'<>\\]{1,500}|\/(?![/\\])[^\s"'<>\\]{0,500})$/;
746
+ /** A same-origin path (served by your app, allowed by the iframe CSP) or a small raster data URL. */
747
+ const AVATAR = /^(\/(?!\/)[\w\-./%]{1,200}|data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]{1,90000})$/;
748
+ const origin = z.string().refine((value) => {
749
+ try {
750
+ const url = new URL(value);
751
+ 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);
752
+ } catch {
753
+ return false;
754
+ }
755
+ }, "must be an https origin like https://www.example.com (no path or wildcard; http only for localhost)");
756
+ const flatTexts = z.partialRecord(z.enum(TEXT_KEYS), z.string().trim().min(1).max(300));
757
+ const textsPerLanguage = z.record(z.string(), flatTexts).refine((sets) => Object.keys(sets).every((tag) => canonicalLocale(tag) !== void 0), "must use BCP 47 tags like en or pl-PL as languages").refine((sets) => Object.keys(sets).length <= 20, "has more than 20 languages").refine((sets) => {
758
+ const tags = Object.keys(sets).map((tag) => canonicalLocale(tag));
759
+ return new Set(tags).size === tags.length;
760
+ }, "has the same language twice");
761
+ /** Per-language when any value is a set of texts; a flat set has only strings. */
762
+ const isPerLanguage = (value) => typeof value === "object" && value !== null && Object.values(value).some((entry) => typeof entry === "object" && entry !== null);
763
+ const textsSchema = z.unknown().superRefine((value, context) => {
764
+ const result = (isPerLanguage(value) ? textsPerLanguage : flatTexts).safeParse(value);
765
+ for (const issue of result.error?.issues ?? []) context.addIssue({
766
+ code: "custom",
767
+ message: issue.message,
768
+ path: issue.path
769
+ });
770
+ });
771
+ /**
772
+ * The overrides a visitor in `locale` gets: the set for every language, then the per-language set
773
+ * for the tag, else its primary subtag, else the `en` set when the language has no built-in
774
+ * dictionary (so its texts are English anyway).
775
+ */
776
+ function widgetTexts(widget, locale) {
777
+ const own = languageTexts(widget, locale) ?? (textLocale(locale) === "en" ? widget.textsByLocale["en"] : void 0);
778
+ return own ? {
779
+ ...widget.texts,
780
+ ...own
781
+ } : widget.texts;
782
+ }
783
+ /**
784
+ * The per-language set written for this language, if any: the one for its tag, else for its
785
+ * primary subtag, else the first one for another tag of the same language (`pl-PL` for `pl`).
786
+ */
787
+ function languageTexts(widget, locale) {
788
+ const tag = canonicalLocale(locale) ?? locale;
789
+ const sets = widget.textsByLocale;
790
+ const language = primarySubtag(tag);
791
+ return sets[tag] ?? sets[language] ?? Object.entries(sets).find(([other]) => primarySubtag(other) === language)?.[1];
792
+ }
793
+ /** The language part of a BCP 47 tag, lowercase: `pl` for `pl-PL`. */
794
+ const primarySubtag = (tag) => (tag.split("-")[0] ?? tag).toLowerCase();
795
+ const definitionSchema = z.object({
796
+ id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/, "use 1-48 lowercase letters, digits or dashes"),
797
+ model: z.string().trim().min(1, "is required"),
798
+ instructions: z.union([z.string().trim().min(1, "must not be empty"), z.function()]),
799
+ limits: z.object({
800
+ maxOutputTokens: z.number().int().min(16).max(128e3).optional(),
801
+ maxInputChars: z.number().int().min(1).max(1e5).optional(),
802
+ maxSteps: z.number().int().min(1).max(20).optional(),
803
+ turnTimeoutMs: z.number().int().min(1e3).max(9e5).optional(),
804
+ dailyTokens: z.number().int().min(1e3).optional(),
805
+ dailyTokensPerIp: z.number().int().min(100).optional(),
806
+ sessionsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
807
+ conversationsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
808
+ messagesPerVisitorPerMinute: z.number().int().min(1).max(1e3).optional(),
809
+ messagesPerIpPerMinute: z.number().int().min(1).max(1e4).optional(),
810
+ maxTurns: z.number().int().min(1).max(1e3).optional(),
811
+ uploadsPerVisitorPerHour: z.number().int().min(1).max(1e3).optional(),
812
+ uploadsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
813
+ uploadsPerDay: z.number().int().min(1).max(1e6).optional(),
814
+ transcriptionsPerVisitorPerHour: z.number().int().min(1).max(1e3).optional(),
815
+ voiceSecondsPerDay: z.number().int().min(60).optional(),
816
+ voiceSecondsPerIpPerDay: z.number().int().min(60).optional()
817
+ }).optional(),
818
+ 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(),
819
+ pageContext: z.boolean().optional(),
820
+ knowledge: z.object({
821
+ vectorStoreId: z.string().regex(/^vs_[A-Za-z0-9_-]+$/, "must be a vector store ID like vs_…"),
822
+ maxResults: z.number().int().min(1).max(50).optional()
823
+ }).optional(),
824
+ attachments: z.object({
825
+ images: z.boolean().optional(),
826
+ pdf: z.boolean().optional(),
827
+ maxBytes: z.number().int().min(1e3).max(2e7).optional(),
828
+ maxPerMessage: z.number().int().min(1).max(10).optional(),
829
+ maxPdfPages: z.number().int().min(1).max(500).optional()
830
+ }).refine((value) => value.images !== false || value.pdf !== false, "must allow images or pdf").optional(),
831
+ voice: z.object({
832
+ model: z.string().trim().min(1, "is required"),
833
+ maxSeconds: z.number().int().min(5).max(300).optional()
834
+ }).optional(),
835
+ security: z.object({ allowedOrigins: z.array(origin).max(50).optional() }).optional(),
836
+ embedPath: z.string().refine(isEmbedPath, "must be a path of this app like /askdare/support").optional(),
837
+ widget: z.object({
838
+ title: z.string().trim().min(1).max(80).optional(),
839
+ greeting: z.string().trim().min(1).max(500).optional(),
840
+ placeholder: z.string().trim().min(1).max(120).optional(),
841
+ 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(),
842
+ texts: textsSchema.optional(),
843
+ disclosure: z.union([z.literal(false), z.object({ privacyUrl: z.string().regex(LINK$1, "must be an https URL or a path like /privacy").optional() }).strict()]).optional(),
844
+ css: z.string().max(5e4).optional(),
845
+ subtitle: z.string().trim().min(1).max(120).optional(),
846
+ starters: z.array(z.string().trim().min(1).max(80)).max(4).optional(),
847
+ feedback: z.boolean().optional(),
848
+ replies: z.enum(["suggest", "off"]).optional(),
849
+ avatar: z.string().regex(AVATAR, "must be a path like /avatar.png or a PNG, JPEG, WebP or GIF data URL").optional(),
850
+ launcherLabel: z.string().trim().min(1).max(40).optional(),
851
+ theme: z.union([z.enum(PRESET_NAMES), themeDefinitionSchema]).optional(),
852
+ colorScheme: z.enum([
853
+ "auto",
854
+ "light",
855
+ "dark"
856
+ ]).optional()
857
+ }).optional()
858
+ });
859
+ /**
860
+ * Declares a chatbot. Validates eagerly so misconfiguration fails at startup, not on the first
861
+ * visitor's message.
862
+ */
863
+ function defineBot(definition) {
864
+ const parsed = definitionSchema.safeParse(definition);
865
+ if (!parsed.success) {
866
+ const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"} ${issue.message}`).join("; ");
867
+ 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)." : "";
868
+ throw new TypeError(`[askdare] Invalid bot "${String(definition.id)}": ${issues}.${hint}`);
869
+ }
870
+ const { instructions } = definition;
871
+ const widget = definition.widget ?? {};
872
+ const locale = widget.locale ?? "en";
873
+ const perLanguage = isPerLanguage(widget.texts);
874
+ const textsByLocale = Object.freeze(perLanguage ? Object.fromEntries(Object.entries(widget.texts).map(([tag, set]) => [canonicalLocale(tag) ?? tag, Object.freeze({ ...set })])) : {});
875
+ const overrides = Object.freeze({
876
+ ...perLanguage ? {} : widget.texts,
877
+ ...widget.title ? { "header.title": widget.title } : {},
878
+ ...widget.greeting ? { "welcome.greeting": widget.greeting } : {},
879
+ ...widget.placeholder ? { "composer.placeholder": widget.placeholder } : {},
880
+ ...widget.launcherLabel ? { "launcher.label": widget.launcherLabel } : {}
881
+ });
882
+ const ownLocale = locale === "auto" ? "en" : locale;
883
+ const texts = textsFor(ownLocale, widgetTexts({
884
+ texts: overrides,
885
+ textsByLocale
886
+ }, ownLocale));
887
+ const theme = resolveTheme(definition.widget?.theme, definition.widget?.colorScheme ?? "auto");
888
+ 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}.`);
889
+ return Object.freeze({
890
+ id: definition.id,
891
+ model: definition.model.trim(),
892
+ instructions: typeof instructions === "string" ? () => instructions : instructions,
893
+ limits: Object.freeze({
894
+ ...DEFAULT_LIMITS,
895
+ ...definition.limits
896
+ }),
897
+ tools: Object.freeze([...definition.tools ?? []]),
898
+ pageContext: definition.pageContext ?? false,
899
+ knowledge: definition.knowledge ? Object.freeze({
900
+ vectorStoreId: definition.knowledge.vectorStoreId,
901
+ maxResults: definition.knowledge.maxResults ?? 5
902
+ }) : void 0,
903
+ attachments: definition.attachments ? Object.freeze({
904
+ images: definition.attachments.images ?? true,
905
+ pdf: definition.attachments.pdf ?? true,
906
+ maxBytes: definition.attachments.maxBytes ?? 4e6,
907
+ maxPerMessage: definition.attachments.maxPerMessage ?? 3,
908
+ maxPdfPages: definition.attachments.maxPdfPages ?? 50
909
+ }) : void 0,
910
+ voice: definition.voice ? Object.freeze({
911
+ model: definition.voice.model.trim(),
912
+ maxSeconds: definition.voice.maxSeconds ?? 60
913
+ }) : void 0,
914
+ security: Object.freeze({ allowedOrigins: Object.freeze([...new Set(definition.security?.allowedOrigins ?? [])]) }),
915
+ embedPath: definition.embedPath,
916
+ widget: Object.freeze({
917
+ title: texts["header.title"] ?? "",
918
+ subtitle: widget.subtitle ?? "",
919
+ greeting: texts["welcome.greeting"] ?? "",
920
+ placeholder: texts["composer.placeholder"] ?? "",
921
+ locale,
922
+ starters: Object.freeze([...widget.starters ?? []]),
923
+ feedback: widget.feedback ?? true,
924
+ replies: widget.replies ?? "off",
925
+ avatar: widget.avatar,
926
+ launcherLabel: texts["launcher.label"] ?? "",
927
+ texts: overrides,
928
+ textsByLocale,
929
+ disclosure: widget.disclosure === false ? false : Object.freeze({ privacyUrl: widget.disclosure?.privacyUrl }),
930
+ css: widget.css ?? "",
931
+ theme
932
+ })
933
+ });
934
+ }
703
935
  // src/protocol/version.ts
704
936
  /**
705
937
  * Version of the SSE wire protocol between the askdare server and its clients.
@@ -741,8 +973,53 @@ function normalizeReplies(values) {
741
973
  }
742
974
  return replies.length > 0 ? replies : void 0;
743
975
  }
744
- // src/tools/define-tool.ts
976
+ /** A tool's name: what `defineTool` accepts and what the protocol carries. */
745
977
  const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
978
+ /** Whether a value is plain JSON: no `undefined`, functions, class instances or `NaN`. */
979
+ function isPlainJson(value, depth) {
980
+ switch (typeof value) {
981
+ case "string":
982
+ case "boolean": return true;
983
+ case "number": return Number.isFinite(value);
984
+ case "object": {
985
+ if (value === null) return true;
986
+ if (depth >= 8) return false;
987
+ if (Array.isArray(value)) {
988
+ for (let index = 0; index < value.length; index += 1) if (!(index in value) || !isPlainJson(value[index], depth + 1)) return false;
989
+ return true;
990
+ }
991
+ const prototype = Object.getPrototypeOf(value);
992
+ if (prototype !== Object.prototype && prototype !== null) return false;
993
+ return Object.values(value).every((item) => isPlainJson(item, depth + 1));
994
+ }
995
+ default: return false;
996
+ }
997
+ }
998
+ /** The payload's JSON, or undefined when it isn't plain JSON within the size and depth limits. */
999
+ function wireJson(value) {
1000
+ if (value === null || value === void 0 || !isPlainJson(value, 0)) return void 0;
1001
+ const json = JSON.stringify(value);
1002
+ return new TextEncoder().encode(json).length <= 8192 ? json : void 0;
1003
+ }
1004
+ /**
1005
+ * The payload as it goes over the wire: a fresh copy of plain JSON within the limits, or
1006
+ * undefined when it breaks one. A payload is sent whole or not at all, never cut.
1007
+ */
1008
+ function toToolUiData(value) {
1009
+ const json = wireJson(value);
1010
+ return json === void 0 ? void 0 : JSON.parse(json);
1011
+ }
1012
+ /** One payload as it goes over the wire: a call ID, a tool name and data within the limits. */
1013
+ function isToolUi(value) {
1014
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1015
+ const { callId, name, data } = value;
1016
+ return typeof callId === "string" && callId.length > 0 && callId.length <= 128 && typeof name === "string" && TOOL_NAME.test(name) && wireJson(data) !== void 0;
1017
+ }
1018
+ /** A list of payloads as it goes over the wire: 1 to 4, each valid, no call twice. */
1019
+ function isToolUiList(value) {
1020
+ return Array.isArray(value) && value.length > 0 && value.length <= 4 && value.every(isToolUi) && new Set(value.map((item) => item.callId)).size === value.length;
1021
+ }
1022
+ // src/tools/define-tool.ts
746
1023
  /** Finds fields OpenAI strict mode would reject, so they fail at startup instead of mid-chat. */
747
1024
  function strictModeProblems(schema, path) {
748
1025
  if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) return [`${path || "(root)"} is optional; use .nullable() so the field is always present`];
@@ -764,6 +1041,7 @@ function defineTool(definition) {
764
1041
  const timeoutMs = definition.timeoutMs ?? 1e4;
765
1042
  if (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 12e4) problems.push("timeoutMs must be an integer between 100 and 120000");
766
1043
  if (definition.replies !== void 0 && typeof definition.replies !== "function") problems.push("replies must be a function of the result");
1044
+ if (definition.ui !== void 0 && typeof definition.ui !== "function") problems.push("ui must be a function of the result");
767
1045
  if (problems.length > 0) throw new TypeError(`[askdare] Invalid tool "${definition.name}": ${problems.join("; ")}`);
768
1046
  return Object.freeze({
769
1047
  name: definition.name,
@@ -771,9 +1049,21 @@ function defineTool(definition) {
771
1049
  input: definition.input,
772
1050
  execute: definition.execute,
773
1051
  timeoutMs,
774
- ...definition.replies ? { replies: definition.replies } : {}
1052
+ ...definition.replies ? { replies: definition.replies } : {},
1053
+ ...definition.ui ? { ui: definition.ui } : {}
775
1054
  });
776
1055
  }
1056
+ /** The tool's output for a call, if it ran with arguments that fit its schema and succeeded. */
1057
+ function successfulOutput(tool, call) {
1058
+ if (call.output === void 0) return void 0;
1059
+ let args;
1060
+ try {
1061
+ args = JSON.parse(call.arguments);
1062
+ } catch {
1063
+ return;
1064
+ }
1065
+ return tool.input.safeParse(args).success ? JSON.parse(call.output) : void 0;
1066
+ }
777
1067
  /**
778
1068
  * The options a turn's calls define, oldest call first (ADR-0015): the last call that
779
1069
  * defines any wins. The live turn and the history both pick them here, from the stored JSON, so a
@@ -785,10 +1075,11 @@ function readToolReplies(tools, calls, onError) {
785
1075
  let replies;
786
1076
  for (const call of calls) {
787
1077
  const tool = tools.find((candidate) => candidate.name === call.name);
788
- if (!tool?.replies || call.output === void 0) continue;
1078
+ if (!tool?.replies) continue;
789
1079
  try {
790
- if (!tool.input.safeParse(JSON.parse(call.arguments)).success) continue;
791
- const items = tool.replies(JSON.parse(call.output));
1080
+ const output = successfulOutput(tool, call);
1081
+ if (output === void 0) continue;
1082
+ const items = tool.replies(output);
792
1083
  const offered = Array.isArray(items) ? normalizeReplies(items) : void 0;
793
1084
  if (offered) replies = offered;
794
1085
  } catch (error) {
@@ -797,4 +1088,41 @@ function readToolReplies(tools, calls, onError) {
797
1088
  }
798
1089
  return replies;
799
1090
  }
800
- export { TEXT_KEYS as _, PROTOCOL_VERSION as a, textsFor as b, SUGGEST_REPLIES_OUTPUT as c, suggestedReplies as d, defineTheme as f, PRESET_NAMES as g, themeWarnings as h, PROTOCOL_HEADER as i, SUGGEST_REPLIES_PARAMETERS as l, themeDefinitionSchema as m, readToolReplies as n, SUGGEST_REPLIES as o, resolveTheme as p, normalizeReplies as r, SUGGEST_REPLIES_DESCRIPTION as s, defineTool as t, readSuggestedReplies as u, TEXT_LOCALES as v, canonicalLocale as x, textLocale as y };
1091
+ /** A `ui` payload broke the limits of ADR-0017; it says so without quoting the payload. */
1092
+ var ToolUiLimitError = class extends Error {
1093
+ constructor() {
1094
+ super("the payload is not plain JSON of at most 8 KB and 8 levels");
1095
+ this.name = "ToolUiLimitError";
1096
+ }
1097
+ };
1098
+ /**
1099
+ * The payloads a turn's calls define for the visitor, in call order (ADR-0017), as the live turn
1100
+ * and the history both send them. A call without an ID, a failed call and a tool without `ui`
1101
+ * define none. A `ui` that throws, or returns a payload over the limits, defines none either;
1102
+ * `onError` hears about it. The caller keeps at most `MAX_TOOL_UI` per answer.
1103
+ */
1104
+ function readToolUi(tools, calls, onError) {
1105
+ const payloads = [];
1106
+ for (const call of calls) {
1107
+ const tool = tools.find((candidate) => candidate.name === call.name);
1108
+ if (!tool?.ui || call.callId === void 0 || call.output === void 0) continue;
1109
+ try {
1110
+ const output = successfulOutput(tool, call);
1111
+ if (output === void 0) continue;
1112
+ const value = tool.ui(output);
1113
+ if (value === void 0 || value === null) continue;
1114
+ const data = toToolUiData(value);
1115
+ if (data === void 0) throw new ToolUiLimitError();
1116
+ const payload = {
1117
+ callId: call.callId,
1118
+ name: tool.name,
1119
+ data
1120
+ };
1121
+ if (isToolUi(payload)) payloads.push(payload);
1122
+ } catch (error) {
1123
+ onError?.(tool, error);
1124
+ }
1125
+ }
1126
+ return payloads;
1127
+ }
1128
+ export { textLocale as C, isInside as D, isBasePath as E, TEXT_LOCALES as S, canonicalLocale as T, readSuggestedReplies as _, isToolUiList as a, resolveTheme as b, PROTOCOL_VERSION as c, primarySubtag as d, widgetTexts as f, SUGGEST_REPLIES_PARAMETERS as g, SUGGEST_REPLIES_OUTPUT as h, readToolUi as i, defineBot as l, SUGGEST_REPLIES_DESCRIPTION as m, defineTool as n, normalizeReplies as o, SUGGEST_REPLIES as p, readToolReplies as r, PROTOCOL_HEADER as s, ToolUiLimitError as t, languageTexts as u, suggestedReplies as v, textsFor as w, PRESET_NAMES as x, defineTheme as y };
@@ -0,0 +1,19 @@
1
+
2
+ import { d 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 };