@mccaskie-labs/workbench-ask 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ // npx workbench-ask init writes the starter workbench/ask.json
3
+ // npx workbench-ask build [--check] reads the sources and writes src/ask.generated.ts
4
+ // npx workbench-ask check checks workbench/ask.json, and that the generated file is current
5
+ //
6
+ // Run from the project's root. Build again whenever the site's pages or the
7
+ // answers file change; `build --check` (or `check`) fails when the generated
8
+ // file is out of date, so a project can run it in its checks.
9
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
10
+ import { fileURLToPath } from "node:url";
11
+ import { dirname, join, relative, sep } from "node:path";
12
+ import { buildKnowledge } from "./knowledge.js";
13
+ import { resolveAskSettings, STARTER_ASK } from "./settings.js";
14
+ const SETTINGS = "workbench/ask.json";
15
+ const GENERATED = "src/ask.generated.ts";
16
+ const EXTENSIONS = /\.(md|html?|txt)$/i;
17
+ const MAX_FILE_BYTES = 2_000_000;
18
+ function readSources(root, sources, exclude) {
19
+ const out = [];
20
+ const posix = (p) => relative(root, p).split(sep).join("/");
21
+ const excluded = (rel) => exclude.some((e) => rel === e.replace(/\/+$/, "") || rel.startsWith(e.replace(/\/+$/, "") + "/"));
22
+ const walk = (abs) => {
23
+ const rel = posix(abs);
24
+ if (excluded(rel))
25
+ return;
26
+ const st = statSync(abs);
27
+ if (st.isDirectory()) {
28
+ for (const name of readdirSync(abs).sort()) {
29
+ if (name.startsWith(".") || name === "node_modules")
30
+ continue;
31
+ walk(join(abs, name));
32
+ }
33
+ return;
34
+ }
35
+ if (!EXTENSIONS.test(abs) || st.size > MAX_FILE_BYTES)
36
+ return;
37
+ out.push({ path: rel, text: readFileSync(abs, "utf8") });
38
+ };
39
+ for (const s of sources) {
40
+ const abs = join(root, s);
41
+ if (!existsSync(abs))
42
+ throw new Error(`${SETTINGS}: source ${s} doesn't exist`);
43
+ walk(abs);
44
+ }
45
+ return out;
46
+ }
47
+ /** The generated file's text for the project at `root`. */
48
+ export function generate(root) {
49
+ const path = join(root, SETTINGS);
50
+ if (!existsSync(path))
51
+ throw new Error(`${SETTINGS} is missing: run npx workbench-ask init`);
52
+ const settings = resolveAskSettings(JSON.parse(readFileSync(path, "utf8")));
53
+ const knowledge = buildKnowledge(settings, readSources(root, settings.sources, settings.exclude));
54
+ return [
55
+ `// Generated by \`npx workbench-ask build\` from ${SETTINGS} and the pages it names. Don't edit:`,
56
+ "// build again when they change (`npx workbench-ask check` fails when this file is out of date).",
57
+ "",
58
+ 'import type { AskKnowledge } from "@mccaskie-labs/workbench-ask";',
59
+ "",
60
+ `export const ASK_KNOWLEDGE: AskKnowledge = ${JSON.stringify(knowledge, null, 2)};`,
61
+ "",
62
+ ].join("\n");
63
+ }
64
+ export function main(argv) {
65
+ const [command, ...rest] = argv;
66
+ const root = process.cwd();
67
+ if (command === "init") {
68
+ const path = join(root, SETTINGS);
69
+ if (existsSync(path)) {
70
+ console.log(`${SETTINGS} is already there; nothing written.`);
71
+ return 0;
72
+ }
73
+ mkdirSync(dirname(path), { recursive: true });
74
+ writeFileSync(path, JSON.stringify(STARTER_ASK, null, 2) + "\n");
75
+ console.log(`Wrote ${SETTINGS}. Set business, sources and handover, then run npx workbench-ask build.`);
76
+ return 0;
77
+ }
78
+ if (command === "build" || command === "check") {
79
+ const check = command === "check" || rest.includes("--check");
80
+ const text = generate(root);
81
+ const out = join(root, GENERATED);
82
+ const current = existsSync(out) ? readFileSync(out, "utf8") : null;
83
+ if (check) {
84
+ if (current !== text) {
85
+ console.error(`${GENERATED} is out of date with ${SETTINGS} or the pages: run npx workbench-ask build.`);
86
+ return 1;
87
+ }
88
+ console.log(`${GENERATED} is current.`);
89
+ return 0;
90
+ }
91
+ mkdirSync(dirname(out), { recursive: true });
92
+ writeFileSync(out, text);
93
+ const n = (text.match(/"id": "/g) ?? []).length;
94
+ console.log(`Wrote ${GENERATED}: ${n} passages.`);
95
+ return 0;
96
+ }
97
+ console.error("Usage: npx workbench-ask init | build [--check] | check");
98
+ return 2;
99
+ }
100
+ const isMain = (() => {
101
+ try {
102
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ })();
108
+ if (isMain) {
109
+ try {
110
+ process.exitCode = main(process.argv.slice(2));
111
+ }
112
+ catch (e) {
113
+ console.error(e instanceof Error ? e.message : String(e));
114
+ process.exitCode = 1;
115
+ }
116
+ }
@@ -0,0 +1,9 @@
1
+ export type AskErrorCode =
2
+ /** workbench/ask.json (or the knowledge built from it) is out of shape. */
3
+ "bad_config"
4
+ /** A call's arguments are out of shape. */
5
+ | "bad_input";
6
+ export declare class AskError extends Error {
7
+ readonly code: AskErrorCode;
8
+ constructor(code: AskErrorCode, message: string);
9
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,10 @@
1
+ // Every failure carries a permanent code, so an app can act on it without
2
+ // reading the words.
3
+ export class AskError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "AskError";
8
+ this.code = code;
9
+ }
10
+ }
@@ -0,0 +1,7 @@
1
+ export { ASK_JOB, ASK_LIMITS, ASK_PROMPT_VERSION, createAsk, parseAnswer, uncheckedFacts, type Ask, type AskAi, type AskHandover, type AskLimiter, type AskMailer, type AskOptions, type AskReason, type AskRecord, type AskReply, type AskStatus, type AskTurn } from "./ask.ts";
2
+ export { buildKnowledge, htmlSections, KNOWLEDGE_LIMITS, markdownSections, pageUrl, type AskKnowledge, type AskPassage, type AskSourceFile } from "./knowledge.ts";
3
+ export { askSettingsProblems, ASK_LANGUAGES, ASK_SPELLINGS, ASK_VOICES, resolveAskSettings, STARTER_ASK, type AskFaq, type AskLanguage, type AskSettings, type AskSpelling, type AskVoice, type ResolvedAskSettings } from "./settings.ts";
4
+ export { renderAskWidget, ASK_SCRIPT, type AskWidgetOptions } from "./widget.ts";
5
+ export { ASK_WORDS, ASK_WORD_KEYS, type AskWordKey, type AskWordsLang, type Words } from "./words.ts";
6
+ export { ASK_STYLES } from "./styles.ts";
7
+ export { AskError, type AskErrorCode } from "./errors.ts";
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ // @mccaskie-labs/workbench-ask: the website question box (capabilities/ask.json).
2
+ // Answers a visitor's questions from the project's own pages and
3
+ // questions-and-answers (built into src/ask.generated.ts by
4
+ // `npx workbench-ask build`), through the Gateway with its own `ask` budget;
5
+ // says so when it isn't sure, and hands the question to the owner by email or
6
+ // to the app. Workbench keeps no visitor's words.
7
+ export { ASK_JOB, ASK_LIMITS, ASK_PROMPT_VERSION, createAsk, parseAnswer, uncheckedFacts } from "./ask.js";
8
+ export { buildKnowledge, htmlSections, KNOWLEDGE_LIMITS, markdownSections, pageUrl } from "./knowledge.js";
9
+ export { askSettingsProblems, ASK_LANGUAGES, ASK_SPELLINGS, ASK_VOICES, resolveAskSettings, STARTER_ASK } from "./settings.js";
10
+ export { renderAskWidget, ASK_SCRIPT } from "./widget.js";
11
+ export { ASK_WORDS, ASK_WORD_KEYS } from "./words.js";
12
+ export { ASK_STYLES } from "./styles.js";
13
+ export { AskError } from "./errors.js";
@@ -0,0 +1,52 @@
1
+ import type { ResolvedAskSettings } from "./settings.ts";
2
+ /** One piece of the site the box may answer from. */
3
+ export interface AskPassage {
4
+ /** `faq:3`, or the file and the passage's place in it (`public/about/index.html#2`). */
5
+ id: string;
6
+ /** The page's or the section's heading, or the FAQ question. */
7
+ title: string;
8
+ /** Where a visitor reads more: a path on the site, or an https address. */
9
+ url?: string;
10
+ text: string;
11
+ }
12
+ /** What src/ask.generated.ts exports as ASK_KNOWLEDGE. */
13
+ export interface AskKnowledge {
14
+ format: 1;
15
+ /** A short hash of the settings and passages, sent as the prompt version, so a call says what it answered from. */
16
+ version: string;
17
+ settings: ResolvedAskSettings;
18
+ passages: readonly AskPassage[];
19
+ }
20
+ /** A source file as the CLI read it. */
21
+ export interface AskSourceFile {
22
+ /** Relative to the project, with forward slashes. */
23
+ path: string;
24
+ text: string;
25
+ }
26
+ export declare const KNOWLEDGE_LIMITS: {
27
+ /** Words in one passage; a longer section is cut into several. */
28
+ readonly passageWords: 120;
29
+ readonly passages: 3000;
30
+ /** All passages' text together. */
31
+ readonly totalChars: 1500000;
32
+ };
33
+ interface Section {
34
+ title: string;
35
+ text: string;
36
+ }
37
+ /** An HTML page's sections: its title, then each heading with the text under it. Scripts, styles, forms and navigation are left out. */
38
+ export declare function htmlSections(html: string): {
39
+ title: string;
40
+ sections: Section[];
41
+ };
42
+ /** A Markdown file's sections, by heading. A front matter `url:` and `title:` are read; the rest of it is left out. */
43
+ export declare function markdownSections(md: string): {
44
+ title: string;
45
+ url?: string;
46
+ sections: Section[];
47
+ };
48
+ /** The address a page file is served at: public/about/index.html is /about/, public/prices.html is /prices. */
49
+ export declare function pageUrl(path: string, pagesRoot: string): string | undefined;
50
+ /** Turns the project's files and FAQ into passages. Throws bad_config past the limits. */
51
+ export declare function buildKnowledge(settings: ResolvedAskSettings, files: readonly AskSourceFile[]): AskKnowledge;
52
+ export {};
@@ -0,0 +1,183 @@
1
+ // The box's knowledge: the project's own pages and questions-and-answers,
2
+ // cut into short passages at build time (`npx workbench-ask build` writes them
3
+ // into src/ask.generated.ts), so answering needs no database, no index service
4
+ // and no fetch of the site. Only what the project publishes goes in.
5
+ import { AskError } from "./errors.js";
6
+ export const KNOWLEDGE_LIMITS = {
7
+ /** Words in one passage; a longer section is cut into several. */
8
+ passageWords: 120,
9
+ passages: 3000,
10
+ /** All passages' text together. */
11
+ totalChars: 1_500_000,
12
+ };
13
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", "#39": "'", ndash: "–", mdash: "—", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", hellip: "…" };
14
+ function decode(s) {
15
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z0-9]+);/gi, (m, e) => {
16
+ if (e[0] === "#") {
17
+ const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
18
+ return Number.isFinite(n) && n > 0 && n < 0x110000 ? String.fromCodePoint(n) : m;
19
+ }
20
+ return ENTITIES[e.toLowerCase()] ?? m;
21
+ });
22
+ }
23
+ const clean = (s) => decode(s).replace(/\s+/g, " ").trim();
24
+ /** An HTML page's sections: its title, then each heading with the text under it. Scripts, styles, forms and navigation are left out. */
25
+ export function htmlSections(html) {
26
+ const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
27
+ let body = /<body[^>]*>([\s\S]*)<\/body>/i.exec(html)?.[1] ?? html;
28
+ body = body
29
+ .replace(/<!--[\s\S]*?-->/g, " ")
30
+ .replace(/<(script|style|noscript|template|svg|nav|form|header|footer|iframe|select|button)\b[\s\S]*?<\/\1>/gi, " ")
31
+ // Anything the page marks as not for the box.
32
+ .replace(/<(\w+)\b[^>]*\bdata-ask-skip\b[^>]*>[\s\S]*?<\/\1>/gi, " ");
33
+ const title = clean(titleMatch?.[1] ?? "");
34
+ const sections = [];
35
+ let current = { title, text: "" };
36
+ const parts = body.split(/(<h[1-4]\b[^>]*>[\s\S]*?<\/h[1-4]>)/i);
37
+ for (const part of parts) {
38
+ const h = /^<h[1-4]\b[^>]*>([\s\S]*?)<\/h[1-4]>$/i.exec(part);
39
+ if (h) {
40
+ if (current.text.trim())
41
+ sections.push(current);
42
+ current = { title: clean(h[1].replace(/<[^>]+>/g, " ")) || title, text: "" };
43
+ continue;
44
+ }
45
+ current.text += " " + part.replace(/<(br|\/p|\/li|\/div|\/tr|\/td|\/th|\/dd|\/dt)\b[^>]*>/gi, " . ").replace(/<[^>]+>/g, " ");
46
+ }
47
+ if (current.text.trim())
48
+ sections.push(current);
49
+ return {
50
+ title,
51
+ sections: sections.map((s) => ({ title: s.title, text: clean(s.text).replace(/(\s\.)+/g, ".").replace(/^\.\s*/, "").replace(/\.\.+/g, ".") })).filter((s) => s.text.length > 0),
52
+ };
53
+ }
54
+ /** A Markdown file's sections, by heading. A front matter `url:` and `title:` are read; the rest of it is left out. */
55
+ export function markdownSections(md) {
56
+ let text = md.replace(/\r\n/g, "\n");
57
+ let url;
58
+ let title = "";
59
+ const fm = /^---\n([\s\S]*?)\n---\n/.exec(text);
60
+ if (fm) {
61
+ text = text.slice(fm[0].length);
62
+ for (const line of fm[1].split("\n")) {
63
+ const m = /^(url|title):\s*["']?(.*?)["']?\s*$/.exec(line);
64
+ if (m?.[1] === "url" && m[2])
65
+ url = m[2];
66
+ if (m?.[1] === "title" && m[2])
67
+ title = m[2];
68
+ }
69
+ }
70
+ const sections = [];
71
+ let current = { title, text: "" };
72
+ for (const line of text.split("\n")) {
73
+ const h = /^#{1,4}\s+(.*)$/.exec(line);
74
+ if (h) {
75
+ if (current.text.trim())
76
+ sections.push(current);
77
+ if (!title)
78
+ title = h[1].trim();
79
+ current = { title: h[1].trim(), text: "" };
80
+ continue;
81
+ }
82
+ current.text += line + "\n";
83
+ }
84
+ if (current.text.trim())
85
+ sections.push(current);
86
+ const plain = (s) => clean(s
87
+ .replace(/```[\s\S]*?```/g, " ")
88
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
89
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
90
+ .replace(/<[^>]+>/g, " ")
91
+ .replace(/[*_`]/g, "")
92
+ .replace(/[>#|]/g, " ")
93
+ .replace(/\n\s*[-+]\s+/g, ". ")
94
+ .replace(/\n{2,}/g, ". "));
95
+ return { title, ...(url ? { url } : {}), sections: sections.map((s) => ({ title: s.title, text: plain(s.text) })).filter((s) => s.text.length > 0) };
96
+ }
97
+ /** The address a page file is served at: public/about/index.html is /about/, public/prices.html is /prices. */
98
+ export function pageUrl(path, pagesRoot) {
99
+ const root = pagesRoot.replace(/\/+$/, "") + "/";
100
+ if (!path.startsWith(root) || !/\.html?$/i.test(path))
101
+ return undefined;
102
+ const rest = path.slice(root.length);
103
+ if (/(^|\/)index\.html?$/i.test(rest))
104
+ return "/" + rest.replace(/index\.html?$/i, "");
105
+ return "/" + rest.replace(/\.html?$/i, "");
106
+ }
107
+ /** Cuts a section into passages of about `passageWords` words, at sentence ends where it can. */
108
+ function cut(text, max) {
109
+ // A sentence ends at . ! or ? followed by a space, so an email address, a web address or $8.50 stays whole.
110
+ const sentences = text.split(/(?<=[.!?]["')\]]*)\s+/);
111
+ const out = [];
112
+ let cur = [];
113
+ let words = 0;
114
+ for (const raw of sentences) {
115
+ const s = raw.trim();
116
+ if (!s)
117
+ continue;
118
+ const n = s.split(/\s+/).length;
119
+ if (words + n > max && cur.length > 0) {
120
+ out.push(cur.join(" "));
121
+ cur = [];
122
+ words = 0;
123
+ }
124
+ if (n > max) {
125
+ const w = s.split(/\s+/);
126
+ for (let i = 0; i < w.length; i += max)
127
+ out.push(w.slice(i, i + max).join(" "));
128
+ continue;
129
+ }
130
+ cur.push(s);
131
+ words += n;
132
+ }
133
+ if (cur.length > 0)
134
+ out.push(cur.join(" "));
135
+ return out;
136
+ }
137
+ function faqPassages(faq) {
138
+ return faq.map((f, i) => ({ id: `faq:${i + 1}`, title: f.q.trim(), ...(f.url ? { url: f.url } : {}), text: `${f.q.trim()} ${f.a.trim()}` }));
139
+ }
140
+ /** A short, stable hash (two FNV-1a 32-bit passes), so this file needs no crypto module and runs anywhere. */
141
+ function shortHash(text) {
142
+ let a = 0x811c9dc5;
143
+ let b = 0x01000193 ^ 0x5bd1e995;
144
+ for (let i = 0; i < text.length; i++) {
145
+ const c = text.charCodeAt(i);
146
+ a = Math.imul(a ^ c, 0x01000193) >>> 0;
147
+ b = Math.imul(b ^ c, 0x5bd1e995) >>> 0;
148
+ }
149
+ return a.toString(16).padStart(8, "0") + b.toString(16).padStart(8, "0").slice(0, 4);
150
+ }
151
+ /** Turns the project's files and FAQ into passages. Throws bad_config past the limits. */
152
+ export function buildKnowledge(settings, files) {
153
+ const passages = faqPassages(settings.faq);
154
+ for (const f of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
155
+ const lower = f.path.toLowerCase();
156
+ let doc;
157
+ if (lower.endsWith(".html") || lower.endsWith(".htm")) {
158
+ const h = htmlSections(f.text);
159
+ const url = pageUrl(f.path, settings.pages_root);
160
+ doc = { ...h, ...(url ? { url } : {}) };
161
+ }
162
+ else if (lower.endsWith(".md"))
163
+ doc = markdownSections(f.text);
164
+ else
165
+ doc = { title: "", sections: [{ title: "", text: clean(f.text) }] };
166
+ let n = 0;
167
+ for (const s of doc.sections) {
168
+ for (const text of cut(s.text, KNOWLEDGE_LIMITS.passageWords)) {
169
+ n += 1;
170
+ passages.push({ id: `${f.path}#${n}`, title: s.title || doc.title || f.path, ...(doc.url ? { url: doc.url } : {}), text });
171
+ }
172
+ }
173
+ }
174
+ if (passages.length === 0)
175
+ throw new AskError("bad_config", "Nothing to answer from: the sources had no text and there is no faq.");
176
+ if (passages.length > KNOWLEDGE_LIMITS.passages)
177
+ throw new AskError("bad_config", `${passages.length} passages is more than ${KNOWLEDGE_LIMITS.passages}: leave some files out with exclude.`);
178
+ const total = passages.reduce((s, p) => s + p.text.length, 0);
179
+ if (total > KNOWLEDGE_LIMITS.totalChars)
180
+ throw new AskError("bad_config", `The sources hold ${total} characters, more than ${KNOWLEDGE_LIMITS.totalChars}: leave some files out with exclude.`);
181
+ const version = shortHash(JSON.stringify({ settings, passages }));
182
+ return { format: 1, version, settings, passages };
183
+ }
@@ -0,0 +1,12 @@
1
+ import type { AskPassage } from "./knowledge.ts";
2
+ /** A passage with its score for one question. */
3
+ interface Found {
4
+ passage: AskPassage;
5
+ score: number;
6
+ }
7
+ export interface Index {
8
+ find(question: string, max: number): Found[];
9
+ }
10
+ /** Builds the scoring tables once, when the box starts. */
11
+ export declare function buildIndex(passages: readonly AskPassage[]): Index;
12
+ export {};
package/dist/search.js ADDED
@@ -0,0 +1,76 @@
1
+ // Finds the passages a question is about: plain keyword scoring (BM25) over
2
+ // the passages built into the project, in English and Tagalog. No embeddings
3
+ // and no index service, so it costs nothing per question, and a question that
4
+ // matches nothing is answered "not sure" without any AI call at all.
5
+ // Words too common to tell passages apart, in English and Tagalog.
6
+ const STOP = new Set(("a an and are as at be been but by can could did do does for from had has have how i if in into is it its me my of on or our so than that the their them then there these they this to us was we were what when where which who why will with would you your yours " +
7
+ "ang ng mga sa si ni na ay at ba po ko mo ka kayo ako siya kami tayo sila ito iyan iyon dito diyan doon may mayroon wala ano saan kailan paano bakit sino lang din rin pa naman nga yung yun kung para hindi oo opo").split(" "));
8
+ /** Lower case words, without stop words, with a light English ending trim (prices → price, booking → book). */
9
+ function terms(text) {
10
+ const out = [];
11
+ for (const raw of text.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").match(/[\p{L}\p{N}]+/gu) ?? []) {
12
+ if (STOP.has(raw) || raw.length < 2)
13
+ continue;
14
+ out.push(stem(raw));
15
+ }
16
+ return out;
17
+ }
18
+ function stem(w) {
19
+ if (/^\d/.test(w) || w.length <= 4)
20
+ return w;
21
+ if (w.endsWith("ies") && w.length > 5)
22
+ return w.slice(0, -3) + "y";
23
+ if (w.endsWith("ing") && w.length > 6)
24
+ return w.slice(0, -3);
25
+ if (w.endsWith("ed") && w.length > 5)
26
+ return w.slice(0, -2);
27
+ if (w.endsWith("es") && /(ss|x|ch|sh)es$/.test(w))
28
+ return w.slice(0, -2);
29
+ if (w.endsWith("s") && !w.endsWith("ss"))
30
+ return w.slice(0, -1);
31
+ return w;
32
+ }
33
+ const K1 = 1.2;
34
+ const B = 0.75;
35
+ /** Builds the scoring tables once, when the box starts. */
36
+ export function buildIndex(passages) {
37
+ const docs = passages.map((p) => {
38
+ // The title counts twice: a heading says what a passage is about.
39
+ const t = [...terms(p.title), ...terms(p.title), ...terms(p.text)];
40
+ const tf = new Map();
41
+ for (const w of t)
42
+ tf.set(w, (tf.get(w) ?? 0) + 1);
43
+ return { passage: p, tf, length: t.length };
44
+ });
45
+ const df = new Map();
46
+ for (const d of docs)
47
+ for (const w of d.tf.keys())
48
+ df.set(w, (df.get(w) ?? 0) + 1);
49
+ const avg = docs.reduce((s, d) => s + d.length, 0) / Math.max(1, docs.length);
50
+ const n = docs.length;
51
+ const idf = (w) => {
52
+ const f = df.get(w) ?? 0;
53
+ return f === 0 ? 0 : Math.log(1 + (n - f + 0.5) / (f + 0.5));
54
+ };
55
+ return {
56
+ find(question, max) {
57
+ const q = [...new Set(terms(question))];
58
+ if (q.length === 0)
59
+ return [];
60
+ const scored = [];
61
+ for (const d of docs) {
62
+ let score = 0;
63
+ for (const w of q) {
64
+ const f = d.tf.get(w);
65
+ if (!f)
66
+ continue;
67
+ score += idf(w) * ((f * (K1 + 1)) / (f + K1 * (1 - B + (B * d.length) / avg)));
68
+ }
69
+ if (score > 0)
70
+ scored.push({ passage: d.passage, score });
71
+ }
72
+ scored.sort((a, b) => b.score - a.score || a.passage.id.localeCompare(b.passage.id));
73
+ return scored.slice(0, max);
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,69 @@
1
+ export type AskLanguage = "match" | "en" | "tl" | "taglish";
2
+ export declare const ASK_LANGUAGES: readonly AskLanguage[];
3
+ /** The Workbench voices (capabilities/ai.json), so the box can name one without depending on workbench-ai. */
4
+ export declare const ASK_VOICES: readonly ["casual", "conversational", "plain", "formal", "strict-formal"];
5
+ export type AskVoice = (typeof ASK_VOICES)[number];
6
+ export declare const ASK_SPELLINGS: readonly ["en-AU", "en-PH", "en-GB", "en-US"];
7
+ export type AskSpelling = (typeof ASK_SPELLINGS)[number];
8
+ /** One question and its answer, written by the owner. */
9
+ export interface AskFaq {
10
+ q: string;
11
+ a: string;
12
+ /** Where on the site to read more: a path such as `/contact`, or an https address. */
13
+ url?: string;
14
+ }
15
+ /** workbench/ask.json. */
16
+ export interface AskSettings {
17
+ format: 1;
18
+ /** The business's name, as visitors know it. */
19
+ business: string;
20
+ /**
21
+ * Files and folders, relative to the project, whose words the box answers from: `.md`, `.html`
22
+ * and `.txt`. Default `["public"]`, the site's own pages. Leave it empty to answer from `faq` only.
23
+ */
24
+ sources?: readonly string[];
25
+ /** The folder the site is served from, so a page's address can be worked out from its file. Default `public`. */
26
+ pages_root?: string;
27
+ /** Files and folders under `sources` to leave out (private pages, the app's own screens). */
28
+ exclude?: readonly string[];
29
+ faq?: readonly AskFaq[];
30
+ /** A Workbench alias. Default `claude-fast`: quick and cheap, which a public box needs. */
31
+ model?: string;
32
+ /** Default `conversational`. */
33
+ voice?: AskVoice;
34
+ /** Default `en-AU`. */
35
+ spelling?: AskSpelling;
36
+ /** `match`: answer in the visitor's language (English, Tagalog or Taglish). Default `match`. */
37
+ language?: AskLanguage;
38
+ /** Plain sentences the owner writes about how to answer ("Never quote a price: say to ask for a quote"). At most 12. */
39
+ notes?: readonly string[];
40
+ /** When the box isn't sure, or a visitor asks for a person, what happens to the question. */
41
+ handover: {
42
+ /** Email the owner the question and the visitor's address (workbench-email, through the Gateway). */
43
+ email: boolean;
44
+ /** Hand it to the app's own `onHandover`, to keep in the app's own database or read with message intake. */
45
+ app: boolean;
46
+ };
47
+ /**
48
+ * `none` (the default): visitors' questions and answers are kept nowhere. `app`: each is handed to the
49
+ * app's `onAnswer`, which keeps it in the project's own database for `keep_days`. Workbench keeps
50
+ * none of it either way.
51
+ */
52
+ keep?: "none" | "app";
53
+ /** With `keep: app`: how long the app keeps them. Default 30, at most 365. */
54
+ keep_days?: number;
55
+ /** Where the chat button shows: on every page, or only on the pages the app puts it on. Default `every_page`. */
56
+ where?: "every_page" | "chosen_pages";
57
+ }
58
+ /** The settings with every default filled in. */
59
+ export type ResolvedAskSettings = Required<Omit<AskSettings, "faq" | "notes" | "exclude">> & {
60
+ faq: readonly AskFaq[];
61
+ notes: readonly string[];
62
+ exclude: readonly string[];
63
+ };
64
+ /** What's wrong with an answers file, as plain lines. Empty when it is fine. */
65
+ export declare function askSettingsProblems(input: unknown): string[];
66
+ /** Checks the answers file and fills in its defaults. Throws bad_config naming every problem. */
67
+ export declare function resolveAskSettings(input: unknown): ResolvedAskSettings;
68
+ /** The starter answers file `npx workbench-ask init` writes. */
69
+ export declare const STARTER_ASK: AskSettings;