@boldare/askdare 0.1.0-rc.4 → 0.2.0-rc.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,61 @@
1
1
  # @boldare/askdare
2
2
 
3
+ ## 0.2.0-rc.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1a1659f: New command `npx @boldare/askdare add ui`: copies the source of the chat's default look (React components and their stylesheet) into `components/askdare`, or the folder given with `--dir`, so you can change it freely. It never overwrites files. The copy imports only `@boldare/askdare/react`, and you switch to it by changing one import of `DefaultChat`.
8
+ - 9bd1b16: Visitors' ratings of answers reach `createChatHandler({ onFeedback })`: 👍, 👎 with an optional comment, or the rating taken back, with the conversation and answer IDs for your own review. Each answer carries an encrypted rating handle in `message.end` and in the history, bound to the visitor or signed-in user, and `POST /feedback` accepts a rating only from them. A bot turns ratings off with `widget.feedback: false`. askdare stores no ratings.
9
+ - 05076dc: The chat shows 👍 and 👎 under each answer when `createChatHandler` has `onFeedback`. After a 👎 it asks "What went wrong?" with an optional comment, a second click takes a rating back, and the browser remembers the visitor's ratings across reloads. New text keys `feedback.*` (English and Polish) and parts `feedback`, `feedback-button`, `feedback-comment` and its children. In your own React markup, use `FeedbackButton` and `actions.rate`. See the new Answer ratings guide.
10
+ - 48ddabf: New entry `@boldare/askdare/react`: the chat inside a page of your own Next.js app, without an iframe. `Root` runs one bot's chat, `DefaultChat` is the widget's look ready to place, and the hooks (`useChat`, `useChatState`, `useMessage`) and primitives (`Messages`, `MessageList`, `Message`, `MessageText`, `Composer`, `Input`, `Send` and the rest) let you write your own markup on the same parts and tokens. `getChatConfig({ bots, bot })` from `@boldare/askdare/next` gives a Server Component the public configuration to pass to `Root`. React 19 is a new optional peer dependency; the script-tag widget needs nothing new. The chat talks only to its own origin, and a page that renders it shares its scripts' access to the conversation: on sites that run scripts they don't trust, keep the iframe widget.
11
+ - 94a1e30: `createChatHandler({ onUsage })` reports every chat turn once its answer has streamed, failed turns included: the tokens it used (input, cached and cache-write input, output and reasoning), the model that answered, how long it took and which tools it called, with pseudonyms instead of IDs and never any message text. Use it for cost tracking and tracing. `onError` may now be async too, and a hook that throws no longer reaches the request: askdare logs its error's name instead.
12
+
13
+ ### Patch Changes
14
+
15
+ - 7c9fb36: Source links under an answer are checked like links inside it: only `http`, `https` and `mailto` URLs become links, and anything else shows as plain text. Before, they relied on the protocol validator alone.
16
+ - 45ef7de: Fixes in the chat inside a page and its default look:
17
+
18
+ - An answer or a transcript returns focus to the message field only when focus was in the chat or nowhere, never from the page's own fields, and without scrolling the page. `actions.focus()` still always moves it.
19
+ - Ratings of one answer go out one at a time: quick 👍 then 👎 ends with what the server took, and a failed one goes back to the last rating it confirmed.
20
+ - A comment after 👎 stays in its form until it is sent, so a failed send no longer loses the text.
21
+ - No new dictation starts while the last one is being transcribed.
22
+ - `<Root>` unmounting stops the answer being streamed and the uploads still running.
23
+ - `Composer`: an `onSubmit` that calls `preventDefault()` takes the message over, Enter in the `Input` goes through `onSubmit` too, and an `onPaste` that prevents the default keeps the files out.
24
+ - Escape outside the chat is left to the page also with `headingLevel={1}`, and Escape that a handler already used is ignored. The question before a new conversation is modal only in the iframe.
25
+ - The default look's stylesheet styles only the chat inside `DefaultChat`, never a headless chat in the same document.
26
+ - The rating buttons and the question after 👎 scroll into view at the end of the conversation, and messages no longer re-render on every change of the chat.
27
+
28
+ ## 0.1.0
29
+
30
+ ### Minor Changes
31
+
32
+ - da333a2: First release of askdare: an AI chat for any website, served by your Next.js app and built on the official OpenAI SDK (Responses and Conversations APIs). It succeeds `@boldare/openai-assistant`, which stopped working when OpenAI shut down the Assistants API.
33
+
34
+ - **Integration:** a bot in `askdare.config.ts` (`defineBot`), one catch-all route (`createChatHandler`) and one script tag on any website (`widget.js?bot=<id>`). `npx @boldare/askdare init` sets it up, and `npx @boldare/askdare doctor` checks the key, models, vector store, headers and allowed sites, locally or deployed.
35
+ - **Embedding:** a small loader and an isolated iframe served by your app, shown only on the sites in `security.allowedOrigins`. As a bubble, behind your own button (`data-launcher="none"`) or inside the page (`data-mode="inline"`), driven by `askdare('open' | 'close' | 'toggle' | 'configure' | 'identify')`.
36
+ - **No database:** conversations live in OpenAI's Conversations API, and the browser keeps an encrypted resume token. Visitors can start a new conversation, which deletes the old one and its files.
37
+ - **Knowledge base:** `npx @boldare/askdare kb sync <folder>` mirrors your documents to a vector store, and answers cite your pages.
38
+ - **Tools:** `defineTool` with Zod schemas, validated arguments, timeouts and output limits. Tools see only verified context.
39
+ - **Attachments and voice:** images and PDFs (checked by their bytes, re-encoded in the browser, referenced by encrypted handles), and dictation into the message field.
40
+ - **Signed-in visitors:** `askdare('identify', token)` with a JWT your backend signs.
41
+ - **Safety and cost:** short-lived encrypted sessions; rate limits; daily token and speech budgets per visitor, IP, bot and app, reserved per model call; a kill switch; sanitized Markdown; no cookies; no message content in logs; `onError` for your monitoring. In development, the chat and the log say what is wrong with the setup.
42
+ - **Look:** four themes (Aura, Halo, Sage, Care) in light and dark, your own with `defineTheme`, `--ask-*` tokens and `data-ask-part` parts for your CSS, English and Polish texts with overrides for every key, and an AI disclosure. Keyboard, focus and screen reader support, checked with axe.
43
+ - **Docs in the package:** the guides (`docs/`), `llms.txt` and a skill for AI coding agents (`skills/askdare`), always matching the installed version.
44
+
45
+ For limits shared across several server instances, add `@boldare/askdare-upstash`.
46
+
47
+ ### Patch Changes
48
+
49
+ - 3bf0dd0: Requires `openai` 7.52.0 and `jose` 6.2.15 or newer. Nothing changes in how askdare calls the API or signs tokens.
50
+ - ef92f7a: Closing the chat from inside it returns keyboard focus to the page in Firefox too, not only in Chromium. `doctor` and `init` no longer report `.env.local` as not ignored in a project without git when its `.gitignore` has folder negations such as `!.yarn/patches`, as create-next-app's does.
51
+ - 13259d4: When the chat opens with a stored conversation and the server refuses the session, it shows the server's reason (explained in development) instead of "Could not load the previous conversation." The conversation stays stored for the next try.
52
+ - 4b7512b: The launcher's label is a part, `launcher-label`, so a site can hide it on small screens and show only the orb or picture (see Styling). A chat placed in the page (`data-mode="inline"`) no longer sits above the page's own fixed elements, such as a sticky header or a bottom bar.
53
+ - 342a931: Requires the `openai` SDK 7.51.0 or newer (was 7.45.1). Nothing changes in how askdare calls the API.
54
+ - 9d4a548: The README is shorter, with three steps to a working chat and a map of the guides. Getting started explains how AI coding agents use the docs and the skill in the package.
55
+ - f25bb19: Docs: a database from the Vercel Marketplace (Upstash for Redis) sets `KV_REST_API_URL` and `KV_REST_API_TOKEN`, and one from the Upstash console has the `UPSTASH_REDIS_REST_*` names. The store reads both, as before.
56
+ - 68d94e6: The npm pages link to the website, https://askdare.vercel.app, with the docs and a live demo of every theme.
57
+ - 4b9cfed: The chat window is built with Preact 11. It looks and works the same.
58
+
3
59
  ## 0.1.0-rc.4
4
60
 
5
61
  ### Patch Changes
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  In a Next.js 16 app:
14
14
 
15
15
  ```bash
16
- npm install @boldare/askdare@rc zod
16
+ npm install @boldare/askdare zod
17
17
  npx @boldare/askdare init
18
18
  ```
19
19
 
@@ -34,13 +34,13 @@ export const bots = [
34
34
  ];
35
35
  ```
36
36
 
37
- **[Getting started](https://askdare.vercel.app/docs/getting-started)** takes you from an empty app to a working chat in about 15 minutes. askdare is a release candidate, so pin the exact version.
37
+ **[Getting started](https://askdare.vercel.app/docs/getting-started)** takes you from an empty app to a working chat in about 15 minutes.
38
38
 
39
39
  ## What you get
40
40
 
41
41
  [![What it does: answers from your documents with citations, your own tools, images and PDFs, voice input, secure by default, and 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) · [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) · [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)
44
44
 
45
45
  ## Themes
46
46
 
@@ -53,10 +53,18 @@ Pick a theme, set your brand's colors, or restyle any part with your own CSS, th
53
53
  The guides are on [askdare.vercel.app/docs](https://askdare.vercel.app/docs), with search. They also ship in this package, in `node_modules/@boldare/askdare/docs/`, so they match the version you installed.
54
54
 
55
55
  - **Start:** [Getting started](https://askdare.vercel.app/docs/getting-started) · [Embedding the chat](https://askdare.vercel.app/docs/embedding) · [Command line](https://askdare.vercel.app/docs/cli)
56
- - **Going live:** [Deployment](https://askdare.vercel.app/docs/deployment) · [Going-public checklist](https://askdare.vercel.app/docs/going-public) · [Costs](https://askdare.vercel.app/docs/costs) · [Privacy](https://askdare.vercel.app/docs/privacy)
56
+ - **Look and language:** [Themes](https://askdare.vercel.app/docs/themes) · [Styling](https://askdare.vercel.app/docs/styling) · [Texts](https://askdare.vercel.app/docs/texts) · [The chat inside your page (React)](https://askdare.vercel.app/docs/react)
57
+ - **Going live:** [Deployment](https://askdare.vercel.app/docs/deployment) · [Going-public checklist](https://askdare.vercel.app/docs/going-public) · [Costs](https://askdare.vercel.app/docs/costs) · [Observability](https://askdare.vercel.app/docs/observability) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Privacy](https://askdare.vercel.app/docs/privacy)
57
58
  - **Reference:** [Configuration](https://askdare.vercel.app/docs/configuration) · [Troubleshooting](https://askdare.vercel.app/docs/troubleshooting) · [Support matrix](https://askdare.vercel.app/docs/support)
58
59
  - **AI coding agents:** `llms.txt` and the `askdare` skill ship in the package ([how to use them](https://askdare.vercel.app/docs/getting-started#working-with-an-ai-coding-agent))
59
60
 
61
+ ## Add-ons
62
+
63
+ | Package | What it adds |
64
+ | --- | --- |
65
+ | [`@boldare/askdare-upstash`](https://www.npmjs.com/package/@boldare/askdare-upstash) | Rate limits and budgets shared by every server instance, in Upstash Redis |
66
+ | [`@boldare/askdare-otel`](https://www.npmjs.com/package/@boldare/askdare-otel) | OpenTelemetry spans for every chat turn, following the GenAI conventions |
67
+
60
68
  ## Requirements
61
69
 
62
70
  Node.js 22 or later, Next.js 16 with the App Router on the Node.js runtime, React 19 and zod 4.1 or later.
package/dist/cli.js CHANGED
@@ -1,14 +1,236 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { parseArgs, parseEnv } from "node:util";
4
- import { appendFile, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { appendFile, copyFile, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
5
6
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { execFile } from "node:child_process";
6
9
  import { z } from "zod";
7
10
  import { EncryptJWT, errors, jwtDecrypt, jwtVerify } from "jose";
8
- import { execFile } from "node:child_process";
9
- import { existsSync, readFileSync } from "node:fs";
10
11
  import { createHash, randomBytes } from "node:crypto";
11
12
  import OpenAI, { NotFoundError, toFile } from "openai";
13
+ // src/base-path.ts
14
+ /**
15
+ * Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
16
+ * origin, a relative path or anything that needs escaping (ADR-0011). The server, the React entry
17
+ * and the CLI each bundle their own copy.
18
+ */
19
+ function isBasePath(value) {
20
+ return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
21
+ }
22
+ // src/cli/project.ts
23
+ const LOCKFILES = [
24
+ ["pnpm-lock.yaml", "pnpm"],
25
+ ["yarn.lock", "yarn"],
26
+ ["bun.lock", "bun"],
27
+ ["bun.lockb", "bun"],
28
+ ["package-lock.json", "npm"]
29
+ ];
30
+ /** Walks up from `start` (a monorepo keeps its lockfile and .gitignore at the top). */
31
+ function findUp(start, test) {
32
+ for (let dir = start;; dir = dirname(dir)) {
33
+ if (test(dir)) return dir;
34
+ if (dirname(dir) === dir || existsSync(join(dir, ".git"))) return void 0;
35
+ }
36
+ }
37
+ async function readProject(root) {
38
+ let dependencies;
39
+ try {
40
+ const json = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
41
+ dependencies = {
42
+ ...json.devDependencies,
43
+ ...json.dependencies
44
+ };
45
+ } catch {
46
+ dependencies = void 0;
47
+ }
48
+ const appDir = [join(root, "app"), join(root, "src", "app")].find((dir) => existsSync(dir));
49
+ let packageManager = "npm";
50
+ findUp(root, (dir) => {
51
+ const lock = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
52
+ if (lock) packageManager = lock[1];
53
+ return lock !== void 0;
54
+ });
55
+ return {
56
+ root,
57
+ dependencies,
58
+ appDir,
59
+ typescript: existsSync(join(root, "tsconfig.json")),
60
+ packageManager
61
+ };
62
+ }
63
+ /** The version installed in `node_modules`; undefined when the package isn't installed. */
64
+ function installedVersion(project, name) {
65
+ let version;
66
+ findUp(project.root, (dir) => {
67
+ try {
68
+ const manifest = readFileSync(join(dir, "node_modules", name, "package.json"), "utf8");
69
+ version = JSON.parse(manifest).version;
70
+ return true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ });
75
+ return version;
76
+ }
77
+ /** Whether a version (or range like `^4.1.0`) is at least `major.minor`; undefined if unreadable. */
78
+ function atLeast(version, major, minor = 0) {
79
+ const match = /(\d+)(?:\.(\d+))?/.exec(version ?? "");
80
+ if (match?.[1] === void 0) return void 0;
81
+ const [have, haveMinor] = [Number(match[1]), Number(match[2] ?? 0)];
82
+ return have > major || have === major && haveMinor >= minor;
83
+ }
84
+ function majorOf(version) {
85
+ const match = /(\d+)/.exec(version ?? "");
86
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
87
+ }
88
+ /** The catch-all route file for a base path, e.g. `app/api/chat/[...path]/route.ts`. */
89
+ function routeDir(project, basePath) {
90
+ return project.appDir && join(project.appDir, ...basePath.split("/").filter(Boolean), "[...path]");
91
+ }
92
+ function findFile(dir, name) {
93
+ if (dir === void 0) return void 0;
94
+ return [
95
+ "ts",
96
+ "tsx",
97
+ "js",
98
+ "jsx",
99
+ "mjs"
100
+ ].map((extension) => join(dir, `${name}.${extension}`)).find((file) => existsSync(file));
101
+ }
102
+ /** A path relative to the project, with forward slashes, for messages. */
103
+ function shown(project, file) {
104
+ return relative(project.root, file).split(sep).join("/");
105
+ }
106
+ function runScript(project, script) {
107
+ return project.packageManager === "npm" ? `npm run ${script}` : `${project.packageManager} ${script}`;
108
+ }
109
+ function addCommand(project, packages) {
110
+ return `${project.packageManager === "npm" ? "npm install" : `${project.packageManager} add`} ${packages.join(" ")}`;
111
+ }
112
+ /**
113
+ * Environment as `next dev` sees it: the shell, then `.env.development.local`, `.env.local`,
114
+ * `.env.development` and `.env`. An explicit `envFile` wins over the shell instead: it is what
115
+ * the user asked to check. Read without changing `process.env`.
116
+ */
117
+ async function readEnv(root, envFile, shell = process.env) {
118
+ const files = envFile ? [envFile] : [
119
+ ".env.development.local",
120
+ ".env.local",
121
+ ".env.development",
122
+ ".env"
123
+ ];
124
+ const loaded = [];
125
+ const env = {};
126
+ for (const file of files.toReversed()) {
127
+ let text;
128
+ try {
129
+ text = await readFile(resolve(root, file), "utf8");
130
+ } catch (error) {
131
+ if (envFile) throw error;
132
+ continue;
133
+ }
134
+ Object.assign(env, parseEnv(text));
135
+ loaded.unshift(file);
136
+ }
137
+ return {
138
+ env: envFile ? {
139
+ ...shell,
140
+ ...env
141
+ } : {
142
+ ...env,
143
+ ...shell
144
+ },
145
+ files: loaded
146
+ };
147
+ }
148
+ /** Whether git ignores `name`, a file in `root`: git's own answer, or 'unknown' without git. */
149
+ function gitCheckIgnore(root, name) {
150
+ return new Promise((done) => {
151
+ execFile("git", [
152
+ "check-ignore",
153
+ "-q",
154
+ "--",
155
+ name
156
+ ], {
157
+ cwd: root,
158
+ timeout: 5e3
159
+ }, (error) => {
160
+ if (error === null) done(true);
161
+ else done(error.code === 1 ? false : "unknown");
162
+ });
163
+ });
164
+ }
165
+ const GLOB_ONLY = /^[^/?[\]\\]+$/;
166
+ /**
167
+ * Whether git ignores `name`, a file in `root`. Asks git; outside a repository (or without git)
168
+ * reads the project's own .gitignore, and answers no whenever a line is beyond a simple glob.
169
+ */
170
+ async function gitIgnores(root, name) {
171
+ const verdict = await gitCheckIgnore(root, name);
172
+ if (verdict !== "unknown") return verdict;
173
+ let text;
174
+ try {
175
+ text = await readFile(join(root, ".gitignore"), "utf8");
176
+ } catch {
177
+ return false;
178
+ }
179
+ let ignored = false;
180
+ for (const line of text.split(/\r?\n/)) {
181
+ const trimmed = line.trim();
182
+ if (!trimmed || trimmed.startsWith("#")) continue;
183
+ const negated = trimmed.startsWith("!");
184
+ const pattern = (negated ? trimmed.slice(1) : trimmed).replace(/^\//, "");
185
+ if (pattern.includes("/") && !pattern.startsWith("**/")) continue;
186
+ if (!GLOB_ONLY.test(pattern)) {
187
+ if (negated) return false;
188
+ continue;
189
+ }
190
+ if (new RegExp(`^${pattern.replace(/[.+^${}()|]/g, "\\$&").replaceAll("*", "[^/]*")}$`).test(name)) ignored = !negated;
191
+ }
192
+ return ignored;
193
+ }
194
+ // src/cli/add-ui.ts
195
+ var AddUiError = class extends Error {};
196
+ /** `dist/ui`, next to `dist/cli.js`. */
197
+ const SHIPPED = fileURLToPath(new URL("./ui/", import.meta.url));
198
+ /**
199
+ * `askdare add ui`: copies the default look's source into the app, shadcn-style (ADR-0011). It
200
+ * never overwrites: if any of the files is already there, nothing is written.
201
+ */
202
+ async function addUi(options) {
203
+ const { root, print } = options;
204
+ const project = await readProject(root);
205
+ if (!project.dependencies?.["next"]) throw new AddUiError("This folder has no Next.js app (no \"next\" in package.json).");
206
+ if (!project.dependencies["react"]) throw new AddUiError("The chat inside a page needs React 19 (no \"react\" in package.json).");
207
+ const inSrc = project.appDir?.endsWith(join("src", "app"));
208
+ const dir = options.dir ?? join(inSrc ? "src" : "", "components", "askdare");
209
+ const target = resolve(root, dir);
210
+ const inside = relative(root, target);
211
+ if (inside === "" || inside.startsWith(`..${sep}`) || inside === ".." || isAbsolute(inside)) throw new AddUiError(`--dir must be a folder inside the app, got "${dir}".`);
212
+ const source = options.source ?? SHIPPED;
213
+ let files;
214
+ try {
215
+ files = (await readdir(source)).sort();
216
+ } catch {
217
+ throw new AddUiError("The package has no UI source (dist/ui). Reinstall @boldare/askdare.");
218
+ }
219
+ const existing = files.filter((file) => existsSync(join(target, file)));
220
+ if (existing.length > 0) throw new AddUiError(`${inside}${sep} already has ${existing.join(", ")}. Nothing was written: askdare never overwrites your files. Remove them or choose another folder with --dir.`);
221
+ await mkdir(target, { recursive: true });
222
+ for (const file of files) await copyFile(join(source, file), join(target, file));
223
+ const shown = inside.split(sep).join("/");
224
+ print(`Added the chat's default look to ${shown}/ (${files.length} files).`);
225
+ print("");
226
+ print("It is your code now. To use it, change one import where you render the chat:");
227
+ print("");
228
+ print(` - import { DefaultChat } from '@boldare/askdare/react';`);
229
+ print(` + import { DefaultChat } from '@/${shown.replace(/^src\//, "")}';`);
230
+ print("");
231
+ print("Root, the hooks and the primitives still come from @boldare/askdare/react.");
232
+ print("The stylesheet is askdare.css in that folder; see docs/react.md in the package.");
233
+ }
12
234
  // src/protocol/doctor.ts
13
235
  const check = z.object({
14
236
  status: z.enum([
@@ -211,6 +433,7 @@ const ISSUER = "askdare";
211
433
  const ACCESS_TYP = "askdare-access+jwt";
212
434
  const RESUME_TYP = "askdare-resume+jwt";
213
435
  const ATTACHMENT_TYP = "askdare-attachment+jwt";
436
+ const FEEDBACK_TYP = "askdare-feedback+jwt";
214
437
  const DOCTOR_TYP = "askdare-doctor+jwt";
215
438
  const DOCTOR_AUDIENCE = "askdare-doctor";
216
439
  const DOCTOR_TTL_SECONDS = 120;
@@ -219,6 +442,7 @@ const MIN_DISTINCT_CHARACTERS = 12;
219
442
  const VISITOR_ID = /^v_[0-9a-f]{32}$/;
220
443
  const CONVERSATION_ID = /^conv_[A-Za-z0-9_-]{1,128}$/;
221
444
  const FILE_ID = /^file-[A-Za-z0-9_-]{1,128}$/;
445
+ const ITEM_ID = /^msg_[A-Za-z0-9_-]{1,128}$/;
222
446
  /** How long after expiry an access token still identifies its visitor for a renewal. */
223
447
  const RENEWAL_GRACE_SECONDS = 3600;
224
448
  const encoder = new TextEncoder();
@@ -373,6 +597,26 @@ async function createTokenService(options) {
373
597
  tokens: est
374
598
  };
375
599
  },
600
+ issueFeedback: (botId, grant) => issue(FEEDBACK_TYP, botId, grant.visitorId, resumeTtl, {
601
+ cid: grant.conversationId,
602
+ iid: grant.itemId,
603
+ ...grant.identityKey ? { ids: grant.identityKey } : {}
604
+ }),
605
+ async verifyFeedback(token, botId) {
606
+ try {
607
+ const { payload } = await verify(token, FEEDBACK_TYP, botId);
608
+ const { cid, iid, ids } = payload;
609
+ if (typeof payload.sub !== "string" || !VISITOR_ID.test(payload.sub) || typeof cid !== "string" || !CONVERSATION_ID.test(cid) || typeof iid !== "string" || !ITEM_ID.test(iid) || ids !== void 0 && typeof ids !== "string") throw new AskdareError("not_found");
610
+ return {
611
+ visitorId: payload.sub,
612
+ conversationId: cid,
613
+ itemId: iid,
614
+ ...ids === void 0 ? {} : { identityKey: ids }
615
+ };
616
+ } catch (error) {
617
+ throw new AskdareError("not_found", { cause: error });
618
+ }
619
+ },
376
620
  issueDoctor: () => issue(DOCTOR_TYP, DOCTOR_AUDIENCE, "doctor", DOCTOR_TTL_SECONDS),
377
621
  async verifyDoctor(token) {
378
622
  try {
@@ -383,178 +627,6 @@ async function createTokenService(options) {
383
627
  }
384
628
  };
385
629
  }
386
- // src/cli/project.ts
387
- const LOCKFILES = [
388
- ["pnpm-lock.yaml", "pnpm"],
389
- ["yarn.lock", "yarn"],
390
- ["bun.lock", "bun"],
391
- ["bun.lockb", "bun"],
392
- ["package-lock.json", "npm"]
393
- ];
394
- /** Walks up from `start` (a monorepo keeps its lockfile and .gitignore at the top). */
395
- function findUp(start, test) {
396
- for (let dir = start;; dir = dirname(dir)) {
397
- if (test(dir)) return dir;
398
- if (dirname(dir) === dir || existsSync(join(dir, ".git"))) return void 0;
399
- }
400
- }
401
- async function readProject(root) {
402
- let dependencies;
403
- try {
404
- const json = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
405
- dependencies = {
406
- ...json.devDependencies,
407
- ...json.dependencies
408
- };
409
- } catch {
410
- dependencies = void 0;
411
- }
412
- const appDir = [join(root, "app"), join(root, "src", "app")].find((dir) => existsSync(dir));
413
- let packageManager = "npm";
414
- findUp(root, (dir) => {
415
- const lock = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
416
- if (lock) packageManager = lock[1];
417
- return lock !== void 0;
418
- });
419
- return {
420
- root,
421
- dependencies,
422
- appDir,
423
- typescript: existsSync(join(root, "tsconfig.json")),
424
- packageManager
425
- };
426
- }
427
- /** The version installed in `node_modules`; undefined when the package isn't installed. */
428
- function installedVersion(project, name) {
429
- let version;
430
- findUp(project.root, (dir) => {
431
- try {
432
- const manifest = readFileSync(join(dir, "node_modules", name, "package.json"), "utf8");
433
- version = JSON.parse(manifest).version;
434
- return true;
435
- } catch {
436
- return false;
437
- }
438
- });
439
- return version;
440
- }
441
- /** Whether a version (or range like `^4.1.0`) is at least `major.minor`; undefined if unreadable. */
442
- function atLeast(version, major, minor = 0) {
443
- const match = /(\d+)(?:\.(\d+))?/.exec(version ?? "");
444
- if (match?.[1] === void 0) return void 0;
445
- const [have, haveMinor] = [Number(match[1]), Number(match[2] ?? 0)];
446
- return have > major || have === major && haveMinor >= minor;
447
- }
448
- function majorOf(version) {
449
- const match = /(\d+)/.exec(version ?? "");
450
- return match?.[1] === void 0 ? void 0 : Number(match[1]);
451
- }
452
- /** The catch-all route file for a base path, e.g. `app/api/chat/[...path]/route.ts`. */
453
- function routeDir(project, basePath) {
454
- return project.appDir && join(project.appDir, ...basePath.split("/").filter(Boolean), "[...path]");
455
- }
456
- function findFile(dir, name) {
457
- if (dir === void 0) return void 0;
458
- return [
459
- "ts",
460
- "tsx",
461
- "js",
462
- "jsx",
463
- "mjs"
464
- ].map((extension) => join(dir, `${name}.${extension}`)).find((file) => existsSync(file));
465
- }
466
- /** A path relative to the project, with forward slashes, for messages. */
467
- function shown(project, file) {
468
- return relative(project.root, file).split(sep).join("/");
469
- }
470
- function runScript(project, script) {
471
- return project.packageManager === "npm" ? `npm run ${script}` : `${project.packageManager} ${script}`;
472
- }
473
- function addCommand(project, packages) {
474
- return `${project.packageManager === "npm" ? "npm install" : `${project.packageManager} add`} ${packages.join(" ")}`;
475
- }
476
- /**
477
- * Environment as `next dev` sees it: the shell, then `.env.development.local`, `.env.local`,
478
- * `.env.development` and `.env`. An explicit `envFile` wins over the shell instead: it is what
479
- * the user asked to check. Read without changing `process.env`.
480
- */
481
- async function readEnv(root, envFile, shell = process.env) {
482
- const files = envFile ? [envFile] : [
483
- ".env.development.local",
484
- ".env.local",
485
- ".env.development",
486
- ".env"
487
- ];
488
- const loaded = [];
489
- const env = {};
490
- for (const file of files.toReversed()) {
491
- let text;
492
- try {
493
- text = await readFile(resolve(root, file), "utf8");
494
- } catch (error) {
495
- if (envFile) throw error;
496
- continue;
497
- }
498
- Object.assign(env, parseEnv(text));
499
- loaded.unshift(file);
500
- }
501
- return {
502
- env: envFile ? {
503
- ...shell,
504
- ...env
505
- } : {
506
- ...env,
507
- ...shell
508
- },
509
- files: loaded
510
- };
511
- }
512
- /** Whether git ignores `name`, a file in `root`: git's own answer, or 'unknown' without git. */
513
- function gitCheckIgnore(root, name) {
514
- return new Promise((done) => {
515
- execFile("git", [
516
- "check-ignore",
517
- "-q",
518
- "--",
519
- name
520
- ], {
521
- cwd: root,
522
- timeout: 5e3
523
- }, (error) => {
524
- if (error === null) done(true);
525
- else done(error.code === 1 ? false : "unknown");
526
- });
527
- });
528
- }
529
- const GLOB_ONLY = /^[^/?[\]\\]+$/;
530
- /**
531
- * Whether git ignores `name`, a file in `root`. Asks git; outside a repository (or without git)
532
- * reads the project's own .gitignore, and answers no whenever a line is beyond a simple glob.
533
- */
534
- async function gitIgnores(root, name) {
535
- const verdict = await gitCheckIgnore(root, name);
536
- if (verdict !== "unknown") return verdict;
537
- let text;
538
- try {
539
- text = await readFile(join(root, ".gitignore"), "utf8");
540
- } catch {
541
- return false;
542
- }
543
- let ignored = false;
544
- for (const line of text.split(/\r?\n/)) {
545
- const trimmed = line.trim();
546
- if (!trimmed || trimmed.startsWith("#")) continue;
547
- const negated = trimmed.startsWith("!");
548
- const pattern = (negated ? trimmed.slice(1) : trimmed).replace(/^\//, "");
549
- if (pattern.includes("/") && !pattern.startsWith("**/")) continue;
550
- if (!GLOB_ONLY.test(pattern)) {
551
- if (negated) return false;
552
- continue;
553
- }
554
- if (new RegExp(`^${pattern.replace(/[.+^${}()|]/g, "\\$&").replaceAll("*", "[^/]*")}$`).test(name)) ignored = !negated;
555
- }
556
- return ignored;
557
- }
558
630
  // src/cli/doctor.ts
559
631
  const ok = (title) => ({
560
632
  status: "ok",
@@ -1339,6 +1411,12 @@ Commands:
1339
1411
  --origin <url> Check that this site may embed the chat (the bot's
1340
1412
  security.allowedOrigins), e.g. https://www.example.com
1341
1413
 
1414
+ add ui Copy the chat's default look (React components and their
1415
+ stylesheet) into the app, to change it freely. Never
1416
+ overwrites files. For the chat inside a page: docs/react.md
1417
+ --dir <folder> Where to put it (default: components/askdare, under src/
1418
+ if the app has one)
1419
+
1342
1420
  kb sync <folder> Make an OpenAI vector store mirror a folder of documents.
1343
1421
  See: npx @boldare/askdare kb sync --help
1344
1422
 
@@ -1385,6 +1463,37 @@ async function runInit(args) {
1385
1463
  }
1386
1464
  return 0;
1387
1465
  }
1466
+ async function runAddUi(args) {
1467
+ const { values } = parseArgs({
1468
+ args: [...args],
1469
+ options: {
1470
+ dir: { type: "string" },
1471
+ help: {
1472
+ type: "boolean",
1473
+ short: "h",
1474
+ default: false
1475
+ }
1476
+ }
1477
+ });
1478
+ if (values.help) {
1479
+ console.log(USAGE);
1480
+ return 0;
1481
+ }
1482
+ try {
1483
+ await addUi({
1484
+ root: process.cwd(),
1485
+ dir: values.dir,
1486
+ print: (line) => console.log(line)
1487
+ });
1488
+ } catch (error) {
1489
+ if (error instanceof AddUiError) {
1490
+ console.error(`askdare add ui: ${error.message}`);
1491
+ return 1;
1492
+ }
1493
+ throw error;
1494
+ }
1495
+ return 0;
1496
+ }
1388
1497
  async function runDoctor(args) {
1389
1498
  const { values } = parseArgs({
1390
1499
  args: [...args],
@@ -1417,7 +1526,7 @@ async function runDoctor(args) {
1417
1526
  throw new UsageError("--url must be a URL such as https://your-app.example.com.");
1418
1527
  }
1419
1528
  if (target.protocol !== "https:" && !(target.protocol === "http:" && isLocal(values.url))) throw new UsageError("--url must use https (plain http only for localhost).");
1420
- if (!/^(\/[a-zA-Z0-9._~-]+)+$/.test(values["base-path"])) throw new UsageError("--base-path must look like /api/chat.");
1529
+ if (!isBasePath(values["base-path"])) throw new UsageError("--base-path must look like /api/chat.");
1421
1530
  let origin;
1422
1531
  if (values.origin !== void 0) try {
1423
1532
  origin = new URL(values.origin).origin;
@@ -1437,6 +1546,7 @@ async function main(argv) {
1437
1546
  const [command, ...rest] = argv;
1438
1547
  if (command === "init") return runInit(rest);
1439
1548
  if (command === "doctor") return runDoctor(rest);
1549
+ if (command === "add" && rest[0] === "ui") return runAddUi(rest.slice(1));
1440
1550
  if (command === "kb" && rest[0] === "sync") return kbSync(rest.slice(1));
1441
1551
  if (command === "-v" || command === "--version") {
1442
1552
  console.log(version());
package/dist/index.js CHANGED
@@ -83,6 +83,7 @@ const definitionSchema = z.object({
83
83
  css: z.string().max(5e4).optional(),
84
84
  subtitle: z.string().trim().min(1).max(120).optional(),
85
85
  starters: z.array(z.string().trim().min(1).max(80)).max(4).optional(),
86
+ feedback: z.boolean().optional(),
86
87
  avatar: z.string().regex(AVATAR, "must be a path like /avatar.png or a PNG, JPEG, WebP or GIF data URL").optional(),
87
88
  launcherLabel: z.string().trim().min(1).max(40).optional(),
88
89
  theme: z.union([z.enum(PRESET_NAMES), themeDefinitionSchema]).optional(),
@@ -150,6 +151,7 @@ function defineBot(definition) {
150
151
  placeholder: texts["composer.placeholder"] ?? "",
151
152
  locale,
152
153
  starters: Object.freeze([...widget.starters ?? []]),
154
+ feedback: widget.feedback ?? true,
153
155
  avatar: widget.avatar,
154
156
  launcherLabel: texts["launcher.label"] ?? "",
155
157
  texts: overrides,