@speeq/core 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.
@@ -0,0 +1,166 @@
1
+ import { SpeeqError, isAbortError } from './chunk-FRW2OUQL.js';
2
+
3
+ // src/language.ts
4
+ var scripts = {
5
+ latin: [/\p{Script=Latin}/u, "en"],
6
+ devanagari: [/\p{Script=Devanagari}/u, "hi"],
7
+ telugu: [/\p{Script=Telugu}/u, "te"],
8
+ tamil: [/\p{Script=Tamil}/u, "ta"],
9
+ kannada: [/\p{Script=Kannada}/u, "kn"],
10
+ malayalam: [/\p{Script=Malayalam}/u, "ml"],
11
+ bengali: [/\p{Script=Bengali}/u, "bn"],
12
+ gujarati: [/\p{Script=Gujarati}/u, "gu"],
13
+ gurmukhi: [/\p{Script=Gurmukhi}/u, "pa"],
14
+ odia: [/\p{Script=Oriya}/u, "or"],
15
+ arabic: [/\p{Script=Arabic}/u, "ur"]
16
+ };
17
+ function baseLanguage(tag) {
18
+ return tag.trim().split(/[-_]/)[0]?.toLowerCase() ?? "";
19
+ }
20
+ function toIso639_1(tag) {
21
+ try {
22
+ const base = new Intl.Locale(baseLanguage(tag)).language;
23
+ return /^[a-z]{2}$/.test(base) && new Intl.DisplayNames("en", { type: "language", fallback: "none" }).of(base) ? base : void 0;
24
+ } catch {
25
+ return void 0;
26
+ }
27
+ }
28
+ function detectScripts(text) {
29
+ const counts = {};
30
+ let dominant;
31
+ const entries = Object.entries(scripts);
32
+ for (const c of text) {
33
+ if (!/\p{L}/u.test(c)) continue;
34
+ const name = entries.find(([, s]) => s[0].test(c))?.[0];
35
+ if (!name) continue;
36
+ const count = (counts[name] ?? 0) + 1;
37
+ counts[name] = count;
38
+ if (!dominant || count > (counts[dominant] ?? 0)) dominant = name;
39
+ }
40
+ return { counts, dominant, mixed: Object.keys(counts).length > 1 };
41
+ }
42
+ function guessLanguageFromScript(text, candidates) {
43
+ const { counts, dominant, mixed } = detectScripts(text);
44
+ if (!dominant) return { confidence: 0, mixed };
45
+ if (dominant === "devanagari" && candidates.some((c) => ["mr", "ne", "sa"].includes(baseLanguage(c))))
46
+ return { confidence: 0.3, mixed };
47
+ const language = candidates.find((c) => baseLanguage(c) === scripts[dominant][1]);
48
+ const total = Object.values(counts).reduce((a, b) => a + b, 0);
49
+ return { language, confidence: language ? (counts[dominant] ?? 0) / total : 0, mixed };
50
+ }
51
+
52
+ // src/utils/sse.ts
53
+ function encodeSse(event, data) {
54
+ const lines = data.split(/\r?\n/).map((line) => `data: ${line}`);
55
+ return `event: ${event}
56
+ ${lines.join("\n")}
57
+
58
+ `;
59
+ }
60
+ var SseParser = class {
61
+ buffer = "";
62
+ event = "";
63
+ data = [];
64
+ id;
65
+ /** Adds a chunk and returns every message completed by it. */
66
+ push(chunk) {
67
+ this.buffer += chunk;
68
+ const out = [];
69
+ for (; ; ) {
70
+ const match = /\r\n|\r|\n/.exec(this.buffer);
71
+ if (!match) break;
72
+ if (match[0] === "\r" && match.index === this.buffer.length - 1) break;
73
+ const line = this.buffer.slice(0, match.index);
74
+ this.buffer = this.buffer.slice(match.index + match[0].length);
75
+ const message = this.processLine(line);
76
+ if (message) out.push(message);
77
+ }
78
+ return out;
79
+ }
80
+ /** Flushes a final message that was not followed by a blank line (end of stream). */
81
+ end() {
82
+ const out = this.buffer.length > 0 ? this.push("\n") : [];
83
+ const last = this.dispatch();
84
+ return last ? [...out, last] : out;
85
+ }
86
+ processLine(line) {
87
+ if (line === "") return this.dispatch();
88
+ if (line.startsWith(":")) return null;
89
+ const colon = line.indexOf(":");
90
+ const field = colon === -1 ? line : line.slice(0, colon);
91
+ let value = colon === -1 ? "" : line.slice(colon + 1);
92
+ if (value.startsWith(" ")) value = value.slice(1);
93
+ if (field === "event") this.event = value;
94
+ else if (field === "data") this.data.push(value);
95
+ else if (field === "id") this.id = value;
96
+ return null;
97
+ }
98
+ dispatch() {
99
+ if (this.data.length === 0) {
100
+ this.event = "";
101
+ return null;
102
+ }
103
+ const message = { event: this.event || "message", data: this.data.join("\n") };
104
+ if (this.id !== void 0) message.id = this.id;
105
+ this.event = "";
106
+ this.data = [];
107
+ return message;
108
+ }
109
+ };
110
+
111
+ // src/utils/provider-http.ts
112
+ async function* readSseData(body, signal) {
113
+ const reader = body.getReader();
114
+ const decoder = new TextDecoder();
115
+ const parser = new SseParser();
116
+ try {
117
+ for (; ; ) {
118
+ signal?.throwIfAborted();
119
+ const { value, done } = await reader.read();
120
+ const messages = done ? parser.end() : parser.push(decoder.decode(value, { stream: true }));
121
+ for (const m of messages) {
122
+ if (m.data === "[DONE]") return;
123
+ yield m.data;
124
+ }
125
+ if (done) return;
126
+ }
127
+ } finally {
128
+ reader.cancel().catch(() => void 0);
129
+ }
130
+ }
131
+ function parseRetryAfter(value) {
132
+ if (!value) return void 0;
133
+ const seconds = Number(value);
134
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1e3));
135
+ const date = Date.parse(value);
136
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
137
+ }
138
+ var QUOTA_RE = /rate.?limit|quota|resource.?exhausted|too many requests|tokens per (minute|day)/i;
139
+ function mapProviderHttpError(provider, status, bodyText, retryAfter) {
140
+ const details = { provider, status, body: bodyText.slice(0, 1e3) };
141
+ if (status === 429 || QUOTA_RE.test(bodyText)) {
142
+ return new SpeeqError("RATE_LIMITED", {
143
+ retryAfterMs: parseRetryAfter(retryAfter) ?? 5e3,
144
+ details
145
+ });
146
+ }
147
+ if (status === 401 || status === 403) {
148
+ return new SpeeqError("NOT_CONFIGURED", {
149
+ message: "The AI provider rejected the API key.",
150
+ details
151
+ });
152
+ }
153
+ return new SpeeqError("PROVIDER_ERROR", { retryable: status >= 500, details });
154
+ }
155
+ async function providerFetch(provider, fetchImpl, url, init) {
156
+ try {
157
+ return await fetchImpl(url, init);
158
+ } catch (error) {
159
+ if (isAbortError(error)) throw error;
160
+ throw new SpeeqError("PROVIDER_ERROR", { cause: error, details: { provider, network: true } });
161
+ }
162
+ }
163
+
164
+ export { SseParser, baseLanguage, detectScripts, encodeSse, guessLanguageFromScript, mapProviderHttpError, parseRetryAfter, providerFetch, readSseData, toIso639_1 };
165
+ //# sourceMappingURL=chunk-CELQUH6A.js.map
166
+ //# sourceMappingURL=chunk-CELQUH6A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/language.ts","../src/utils/sse.ts","../src/utils/provider-http.ts"],"names":[],"mappings":";;;AAaA,IAAM,OAAA,GAAgD;AAAA,EACpD,KAAA,EAAO,CAAC,mBAAA,EAAqB,IAAI,CAAA;AAAA,EACjC,UAAA,EAAY,CAAC,wBAAA,EAA0B,IAAI,CAAA;AAAA,EAC3C,MAAA,EAAQ,CAAC,oBAAA,EAAsB,IAAI,CAAA;AAAA,EACnC,KAAA,EAAO,CAAC,mBAAA,EAAqB,IAAI,CAAA;AAAA,EACjC,OAAA,EAAS,CAAC,qBAAA,EAAuB,IAAI,CAAA;AAAA,EACrC,SAAA,EAAW,CAAC,uBAAA,EAAyB,IAAI,CAAA;AAAA,EACzC,OAAA,EAAS,CAAC,qBAAA,EAAuB,IAAI,CAAA;AAAA,EACrC,QAAA,EAAU,CAAC,sBAAA,EAAwB,IAAI,CAAA;AAAA,EACvC,QAAA,EAAU,CAAC,sBAAA,EAAwB,IAAI,CAAA;AAAA,EACvC,IAAA,EAAM,CAAC,mBAAA,EAAqB,IAAI,CAAA;AAAA,EAChC,MAAA,EAAQ,CAAC,oBAAA,EAAsB,IAAI;AACrC,CAAA;AAEO,SAAS,aAAa,GAAA,EAAa;AACxC,EAAA,OAAO,GAAA,CAAI,MAAK,CAAE,KAAA,CAAM,MAAM,CAAA,CAAE,CAAC,CAAA,EAAG,WAAA,EAAY,IAAK,EAAA;AACvD;AAEO,SAAS,WAAW,GAAA,EAAa;AACtC,EAAA,IAAI;AACF,IAAA,MAAM,OAAO,IAAI,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,CAAC,CAAA,CAAE,QA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,EACA,MAAA,EACA,QAAA,EACA,UAAA,EACY;AACZ,EAAA,MAAM,OAAA,GAAU,EAAE,QAAA,EAAU,MAAA,EAAQ,MAAM,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,GAAI,CAAA,EAAE;AAClE,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,QAAA,CAAS,IAAA,CAAK,QAAQ,CAAA,EAAG;AAC7C,IAAA,OAAO,IAAI,WAAW,cAAA,EAAgB;AAAA,MACpC,YAAA,EAAc,eAAA,CAAgB,UAAU,CAAA,IAAK,GAAA;AAAA,MAC7C;AAAA,KACD,CAAA;AAAA,EACH;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,IAAA,OAAO,IAAI,WAAW,gBAAA,EAAkB;AAAA,MACtC,OAAA,EAAS,uCAAA;AAAA,MACT;AAAA,KACD,CAAA;AAAA,EACH;AACA,EAAA,OAAO,IAAI,WAAW,gBAAA,EAAkB,EAAE,WAAW,MAAA,IAAU,GAAA,EAAK,SAAS,CAAA;AAC/E;AAGA,eAAsB,aAAA,CACpB,QAAA,EACA,SAAA,EACA,GAAA,EACA,IAAA,EACmB;AACnB,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,SAAA,CAAU,GAAA,EAAK,IAAI,CAAA;AAAA,EAClC,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,YAAA,CAAa,KAAK,CAAA,EAAG,MAAM,KAAA;AAC/B,IAAA,MAAM,IAAI,UAAA,CAAW,gBAAA,EAAkB,EAAE,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,EAAE,QAAA,EAAU,OAAA,EAAS,IAAA,EAAK,EAAG,CAAA;AAAA,EAC/F;AACF","file":"chunk-CELQUH6A.js","sourcesContent":["/** Writing systems used by the lightweight language heuristic. */\nexport type ScriptName =\n | \"latin\"\n | \"devanagari\"\n | \"telugu\"\n | \"tamil\"\n | \"kannada\"\n | \"malayalam\"\n | \"bengali\"\n | \"gujarati\"\n | \"gurmukhi\"\n | \"odia\"\n | \"arabic\";\nconst scripts: Record<ScriptName, [RegExp, string]> = {\n latin: [/\\p{Script=Latin}/u, \"en\"],\n devanagari: [/\\p{Script=Devanagari}/u, \"hi\"],\n telugu: [/\\p{Script=Telugu}/u, \"te\"],\n tamil: [/\\p{Script=Tamil}/u, \"ta\"],\n kannada: [/\\p{Script=Kannada}/u, \"kn\"],\n malayalam: [/\\p{Script=Malayalam}/u, \"ml\"],\n bengali: [/\\p{Script=Bengali}/u, \"bn\"],\n gujarati: [/\\p{Script=Gujarati}/u, \"gu\"],\n gurmukhi: [/\\p{Script=Gurmukhi}/u, \"pa\"],\n odia: [/\\p{Script=Oriya}/u, \"or\"],\n arabic: [/\\p{Script=Arabic}/u, \"ur\"],\n};\n/** Extract the normalized primary language subtag. */\nexport function baseLanguage(tag: string) {\n return tag.trim().split(/[-_]/)[0]?.toLowerCase() ?? \"\";\n}\n/** Return a two-letter primary language when the tag has one. */\nexport function toIso639_1(tag: string) {\n try {\n const base = new Intl.Locale(baseLanguage(tag)).language;\n return /^[a-z]{2}$/.test(base) &&\n new Intl.DisplayNames(\"en\", { type: \"language\", fallback: \"none\" }).of(base)\n ? base\n : undefined;\n } catch {\n return undefined;\n }\n}\n/** Count letters in each script, excluding digits and punctuation. */\nexport function detectScripts(text: string) {\n const counts: Partial<Record<ScriptName, number>> = {};\n let dominant: ScriptName | undefined;\n const entries = Object.entries(scripts) as [ScriptName, [RegExp, string]][];\n for (const c of text) {\n if (!/\\p{L}/u.test(c)) continue;\n const name = entries.find(([, s]) => s[0].test(c))?.[0];\n if (!name) continue;\n const count = (counts[name] ?? 0) + 1;\n counts[name] = count;\n if (!dominant || count > (counts[dominant] ?? 0)) dominant = name;\n }\n return { counts, dominant, mixed: Object.keys(counts).length > 1 };\n}\n/** Infer a candidate language from script evidence, leaving shared Devanagari unresolved. */\nexport function guessLanguageFromScript(text: string, candidates: readonly string[]) {\n const { counts, dominant, mixed } = detectScripts(text);\n if (!dominant) return { confidence: 0, mixed };\n if (\n dominant === \"devanagari\" &&\n candidates.some((c) => [\"mr\", \"ne\", \"sa\"].includes(baseLanguage(c)))\n )\n return { confidence: 0.3, mixed };\n const language = candidates.find((c) => baseLanguage(c) === scripts[dominant][1]);\n const total = Object.values(counts).reduce((a, b) => a + b, 0);\n return { language, confidence: language ? (counts[dominant] ?? 0) / total : 0, mixed };\n}\n","/** One parsed Server-Sent Event. */\nexport interface SseMessage {\n /** The `event:` field, or `\"message\"` when absent. */\n event: string;\n /** The joined `data:` lines. */\n data: string;\n id?: string;\n}\n\n/** Encodes one SSE message (`event:` + `data:` lines + blank line). */\nexport function encodeSse(event: string, data: string): string {\n const lines = data.split(/\\r?\\n/).map((line) => `data: ${line}`);\n return `event: ${event}\\n${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * Incremental SSE parser that follows the WHATWG event-stream rules. Feed it decoded text chunks\n * in any split (mid-line, mid-field, CRLF across chunks) and it returns complete messages.\n */\nexport class SseParser {\n private buffer = \"\";\n private event = \"\";\n private data: string[] = [];\n private id: string | undefined;\n\n /** Adds a chunk and returns every message completed by it. */\n push(chunk: string): SseMessage[] {\n this.buffer += chunk;\n const out: SseMessage[] = [];\n for (;;) {\n const match = /\\r\\n|\\r|\\n/.exec(this.buffer);\n if (!match) break;\n // A lone trailing \"\\r\" may be the first half of \"\\r\\n\": wait for more input.\n if (match[0] === \"\\r\" && match.index === this.buffer.length - 1) break;\n const line = this.buffer.slice(0, match.index);\n this.buffer = this.buffer.slice(match.index + match[0].length);\n const message = this.processLine(line);\n if (message) out.push(message);\n }\n return out;\n }\n\n /** Flushes a final message that was not followed by a blank line (end of stream). */\n end(): SseMessage[] {\n const out = this.buffer.length > 0 ? this.push(\"\\n\") : [];\n const last = this.dispatch();\n return last ? [...out, last] : out;\n }\n\n private processLine(line: string): SseMessage | null {\n if (line === \"\") return this.dispatch();\n if (line.startsWith(\":\")) return null;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n if (field === \"event\") this.event = value;\n else if (field === \"data\") this.data.push(value);\n else if (field === \"id\") this.id = value;\n return null;\n }\n\n private dispatch(): SseMessage | null {\n if (this.data.length === 0) {\n this.event = \"\";\n return null;\n }\n const message: SseMessage = { event: this.event || \"message\", data: this.data.join(\"\\n\") };\n if (this.id !== undefined) message.id = this.id;\n this.event = \"\";\n this.data = [];\n return message;\n }\n}\n","import { isAbortError, SpeeqError } from \"../errors.js\";\nimport { SseParser } from \"./sse.js\";\n\n/**\n * Reads the `data:` payloads of an SSE response body. For LLM adapters: stops at `[DONE]`\n * and honors `signal`.\n */\nexport async function* readSseData(\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<string> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n const parser = new SseParser();\n try {\n for (;;) {\n signal?.throwIfAborted();\n const { value, done } = await reader.read();\n const messages = done ? parser.end() : parser.push(decoder.decode(value, { stream: true }));\n for (const m of messages) {\n if (m.data === \"[DONE]\") return;\n yield m.data;\n }\n if (done) return;\n }\n } finally {\n reader.cancel().catch(() => undefined);\n }\n}\n\n/** Parses a `Retry-After` header (seconds or HTTP date) into milliseconds. */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1000));\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nconst QUOTA_RE = /rate.?limit|quota|resource.?exhausted|too many requests|tokens per (minute|day)/i;\n\n/**\n * Maps an HTTP error from an LLM provider to a {@link SpeeqError}:\n * 429 and quota or rate-limit bodies → `RATE_LIMITED` (with a retry hint), 401/403 →\n * `NOT_CONFIGURED` (bad API key), anything else → `PROVIDER_ERROR`. The provider's raw message\n * is kept in `details` for server logs, never in the public message.\n */\nexport function mapProviderHttpError(\n provider: string,\n status: number,\n bodyText: string,\n retryAfter?: string | null,\n): SpeeqError {\n const details = { provider, status, body: bodyText.slice(0, 1000) };\n if (status === 429 || QUOTA_RE.test(bodyText)) {\n return new SpeeqError(\"RATE_LIMITED\", {\n retryAfterMs: parseRetryAfter(retryAfter) ?? 5000,\n details,\n });\n }\n if (status === 401 || status === 403) {\n return new SpeeqError(\"NOT_CONFIGURED\", {\n message: \"The AI provider rejected the API key.\",\n details,\n });\n }\n return new SpeeqError(\"PROVIDER_ERROR\", { retryable: status >= 500, details });\n}\n\n/** Wraps `fetch` so network failures become `PROVIDER_ERROR` and aborts are rethrown as-is. */\nexport async function providerFetch(\n provider: string,\n fetchImpl: typeof fetch,\n url: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetchImpl(url, init);\n } catch (error) {\n if (isAbortError(error)) throw error;\n throw new SpeeqError(\"PROVIDER_ERROR\", { cause: error, details: { provider, network: true } });\n }\n}\n"]}
@@ -6,6 +6,8 @@ var ERROR_CODES = [
6
6
  "NOT_FOUND",
7
7
  "CONFLICT",
8
8
  "RATE_LIMITED",
9
+ "SPEECH_UNAVAILABLE",
10
+ "PAYLOAD_TOO_LARGE",
9
11
  "PROVIDER_ERROR",
10
12
  "TOOL_ERROR",
11
13
  "TOOL_TIMEOUT",
@@ -21,6 +23,8 @@ var ERROR_HTTP_STATUS = {
21
23
  NOT_FOUND: 404,
22
24
  CONFLICT: 409,
23
25
  RATE_LIMITED: 429,
26
+ SPEECH_UNAVAILABLE: 503,
27
+ PAYLOAD_TOO_LARGE: 413,
24
28
  PROVIDER_ERROR: 502,
25
29
  TOOL_ERROR: 500,
26
30
  TOOL_TIMEOUT: 504,
@@ -36,6 +40,8 @@ var DEFAULT_ERROR_MESSAGES = {
36
40
  NOT_FOUND: "That could not be found.",
37
41
  CONFLICT: "That was already handled.",
38
42
  RATE_LIMITED: "The assistant is busy right now. Please try again in a moment.",
43
+ SPEECH_UNAVAILABLE: "Voice is not available right now. You can type instead.",
44
+ PAYLOAD_TOO_LARGE: "That audio is too long.",
39
45
  PROVIDER_ERROR: "The AI provider had a problem. Please try again.",
40
46
  TOOL_ERROR: "An action failed to run.",
41
47
  TOOL_TIMEOUT: "An action took too long and was stopped.",
@@ -93,5 +99,5 @@ function isAbortError(error) {
93
99
  }
94
100
 
95
101
  export { DEFAULT_ERROR_MESSAGES, ERROR_CODES, ERROR_HTTP_STATUS, SpeeqError, isAbortError, isErrorCode, isSpeeqError, toPublicError, toSpeeqError };
96
- //# sourceMappingURL=chunk-JA2L35IQ.js.map
97
- //# sourceMappingURL=chunk-JA2L35IQ.js.map
102
+ //# sourceMappingURL=chunk-FRW2OUQL.js.map
103
+ //# sourceMappingURL=chunk-FRW2OUQL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AAMO,IAAM,WAAA,GAAc;AAAA,EACzB,iBAAA;AAAA,EACA,WAAA;AAAA,EACA,eAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,cAAA;AAAA,EACA,oBAAA;AAAA,EACA,mBAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,uBAAA;AAAA,EACA,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF;AAMO,IAAM,iBAAA,GAAyD;AAAA,EACpE,eAAA,EAAiB,GAAA;AAAA,EACjB,SAAA,EAAW,GAAA;AAAA,EACX,aAAA,EAAe,GAAA;AAAA,EACf,SAAA,EAAW,GAAA;AAAA,EACX,QAAA,EAAU,GAAA;AAAA,EACV,YAAA,EAAc,GAAA;AAAA,EACd,kBAAA,EAAoB,GAAA;AAAA,EACpB,iBAAA,EAAmB,GAAA;AAAA,EACnB,cAAA,EAAgB,GAAA;AAAA,EAChB,UAAA,EAAY,GAAA;AAAA,EACZ,YAAA,EAAc,GAAA;AAAA,EACd,qBAAA,EAAuB,GAAA;AAAA,EACvB,eAAA,EA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,KAAU,SACR,KAAA,CAA6B,IAAA,KAAS,YAAA,IACrC,KAAA,CAA6B,IAAA,KAAS,cAAA,CAAA;AAE7C","file":"chunk-FRW2OUQL.js","sourcesContent":["/**\n * Errors shared by every speeq package. This module has no dependencies (no zod), so browser\n * code can import it from `@speeq/core/errors` without pulling in schemas.\n */\n\n/** Every stable error code. Codes are part of the public protocol. Never rename one. */\nexport const ERROR_CODES = [\n \"UNAUTHENTICATED\",\n \"FORBIDDEN\",\n \"INVALID_INPUT\",\n \"NOT_FOUND\",\n \"CONFLICT\",\n \"RATE_LIMITED\",\n \"SPEECH_UNAVAILABLE\",\n \"PAYLOAD_TOO_LARGE\",\n \"PROVIDER_ERROR\",\n \"TOOL_ERROR\",\n \"TOOL_TIMEOUT\",\n \"CONFIRMATION_REQUIRED\",\n \"SESSION_EXPIRED\",\n \"NOT_CONFIGURED\",\n \"INTERNAL\",\n] as const;\n\n/** A stable, machine-readable error code. */\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/** HTTP status used when an error with this code is returned as a plain JSON response. */\nexport const ERROR_HTTP_STATUS: Readonly<Record<ErrorCode, number>> = {\n UNAUTHENTICATED: 401,\n FORBIDDEN: 403,\n INVALID_INPUT: 400,\n NOT_FOUND: 404,\n CONFLICT: 409,\n RATE_LIMITED: 429,\n SPEECH_UNAVAILABLE: 503,\n PAYLOAD_TOO_LARGE: 413,\n PROVIDER_ERROR: 502,\n TOOL_ERROR: 500,\n TOOL_TIMEOUT: 504,\n CONFIRMATION_REQUIRED: 409,\n SESSION_EXPIRED: 401,\n NOT_CONFIGURED: 500,\n INTERNAL: 500,\n};\n\n/** Friendly default messages that are always safe to show to end users. */\nexport const DEFAULT_ERROR_MESSAGES: Readonly<Record<ErrorCode, string>> = {\n UNAUTHENTICATED: \"Please sign in to continue.\",\n FORBIDDEN: \"You are not allowed to do that.\",\n INVALID_INPUT: \"The request was not valid.\",\n NOT_FOUND: \"That could not be found.\",\n CONFLICT: \"That was already handled.\",\n RATE_LIMITED: \"The assistant is busy right now. Please try again in a moment.\",\n SPEECH_UNAVAILABLE: \"Voice is not available right now. You can type instead.\",\n PAYLOAD_TOO_LARGE: \"That audio is too long.\",\n PROVIDER_ERROR: \"The AI provider had a problem. Please try again.\",\n TOOL_ERROR: \"An action failed to run.\",\n TOOL_TIMEOUT: \"An action took too long and was stopped.\",\n CONFIRMATION_REQUIRED: \"This action needs your confirmation.\",\n SESSION_EXPIRED: \"Your session expired. Starting a new one.\",\n NOT_CONFIGURED: \"The assistant is not configured correctly.\",\n INTERNAL: \"Something went wrong.\",\n};\n\nconst RETRYABLE: ReadonlySet<ErrorCode> = new Set([\n \"RATE_LIMITED\",\n \"PROVIDER_ERROR\",\n \"TOOL_TIMEOUT\",\n \"SESSION_EXPIRED\",\n]);\n\n/** Options for constructing a {@link SpeeqError}. */\nexport interface SpeeqErrorOptions {\n /** Public, user-safe message. Defaults to {@link DEFAULT_ERROR_MESSAGES}. */\n message?: string;\n /** Whether retrying the same request may succeed. Defaults by code. */\n retryable?: boolean;\n /** Suggested wait before retrying, in milliseconds. */\n retryAfterMs?: number;\n /** The underlying error. Kept for server logs, never serialized to clients. */\n cause?: unknown;\n /** Extra structured detail for logs (never sent to clients). */\n details?: Record<string, unknown>;\n}\n\n/** The single error type used across speeq. Always carries a stable {@link ErrorCode}. */\nexport class SpeeqError extends Error {\n /** Brand used by {@link isSpeeqError} so checks work across bundled copies. */\n readonly isSpeeqError = true as const;\n readonly code: ErrorCode;\n readonly retryable: boolean;\n readonly retryAfterMs: number | undefined;\n readonly details: Record<string, unknown> | undefined;\n\n constructor(code: ErrorCode, options: SpeeqErrorOptions = {}) {\n super(options.message ?? DEFAULT_ERROR_MESSAGES[code], { cause: options.cause });\n this.name = \"SpeeqError\";\n this.code = code;\n this.retryable = options.retryable ?? RETRYABLE.has(code);\n this.retryAfterMs = options.retryAfterMs;\n this.details = options.details;\n }\n\n /** HTTP status for this error. */\n get status(): number {\n return ERROR_HTTP_STATUS[this.code];\n }\n}\n\n/** True if `value` is a {@link SpeeqError} (works across duplicated package copies). */\nexport function isSpeeqError(value: unknown): value is SpeeqError {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { isSpeeqError?: unknown }).isSpeeqError === true &&\n typeof (value as { code?: unknown }).code === \"string\"\n );\n}\n\n/** True if `value` is one of the known {@link ERROR_CODES}. */\nexport function isErrorCode(value: unknown): value is ErrorCode {\n return typeof value === \"string\" && (ERROR_CODES as readonly string[]).includes(value);\n}\n\n/** The client-safe shape of an error, as sent over the wire. */\nexport interface PublicError {\n code: ErrorCode;\n message: string;\n retryable: boolean;\n retryAfterMs?: number;\n}\n\n/**\n * Converts anything thrown into a {@link SpeeqError}. Unknown errors become `INTERNAL` with the\n * generic message, so raw messages and stack traces never reach clients.\n */\nexport function toSpeeqError(error: unknown, fallback: ErrorCode = \"INTERNAL\"): SpeeqError {\n if (isSpeeqError(error)) return error;\n if (isAbortError(error))\n return new SpeeqError(\"INTERNAL\", { message: \"Cancelled.\", cause: error });\n return new SpeeqError(fallback, { cause: error });\n}\n\n/** Serializes an error to its {@link PublicError} form (safe to send to the browser). */\nexport function toPublicError(error: unknown): PublicError {\n const e = toSpeeqError(error);\n const out: PublicError = { code: e.code, message: e.message, retryable: e.retryable };\n if (e.retryAfterMs !== undefined) out.retryAfterMs = e.retryAfterMs;\n return out;\n}\n\n/** True for `AbortError`s raised by `AbortSignal` / `fetch`. */\nexport function isAbortError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n ((error as { name?: unknown }).name === \"AbortError\" ||\n (error as { name?: unknown }).name === \"TimeoutError\")\n );\n}\n"]}
@@ -0,0 +1,421 @@
1
+ import { baseLanguage } from './chunk-CELQUH6A.js';
2
+
3
+ // src/utils/async.ts
4
+ function combineSignals(signals, timeoutMs) {
5
+ const list = signals.filter((s) => s !== void 0);
6
+ if (timeoutMs !== void 0) list.push(AbortSignal.timeout(timeoutMs));
7
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(list);
8
+ const controller = new AbortController();
9
+ for (const s of list) {
10
+ if (s.aborted) {
11
+ controller.abort(s.reason);
12
+ break;
13
+ }
14
+ s.addEventListener("abort", () => controller.abort(s.reason), { once: true });
15
+ }
16
+ return controller.signal;
17
+ }
18
+ function sleep(ms, signal) {
19
+ return new Promise((resolve, reject) => {
20
+ if (signal?.aborted) {
21
+ reject(signal.reason);
22
+ return;
23
+ }
24
+ const timer = setTimeout(resolve, ms);
25
+ signal?.addEventListener(
26
+ "abort",
27
+ () => {
28
+ clearTimeout(timer);
29
+ reject(signal.reason);
30
+ },
31
+ { once: true }
32
+ );
33
+ });
34
+ }
35
+
36
+ // src/utils/emitter.ts
37
+ var TypedEmitter = class {
38
+ listeners = /* @__PURE__ */ new Map();
39
+ /** Subscribes to `event`. Returns an unsubscribe function. */
40
+ on(event, listener) {
41
+ let set = this.listeners.get(event);
42
+ if (!set) {
43
+ set = /* @__PURE__ */ new Set();
44
+ this.listeners.set(event, set);
45
+ }
46
+ set.add(listener);
47
+ return () => this.off(event, listener);
48
+ }
49
+ /** Subscribes to the next `event` only. */
50
+ once(event, listener) {
51
+ const off = this.on(event, (payload) => {
52
+ off();
53
+ listener(payload);
54
+ });
55
+ return off;
56
+ }
57
+ /** Removes a listener. */
58
+ off(event, listener) {
59
+ this.listeners.get(event)?.delete(listener);
60
+ }
61
+ /** Calls every listener for `event` with `payload`. */
62
+ emit(event, payload) {
63
+ const set = this.listeners.get(event);
64
+ if (!set) return;
65
+ for (const listener of [...set]) {
66
+ try {
67
+ listener(payload);
68
+ } catch (error) {
69
+ console.error("[speeq] event listener threw", error);
70
+ }
71
+ }
72
+ }
73
+ /** Removes every listener. */
74
+ clear() {
75
+ this.listeners.clear();
76
+ }
77
+ };
78
+
79
+ // src/utils/ids.ts
80
+ function createId(prefix) {
81
+ return `${prefix}_${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
82
+ }
83
+
84
+ // src/utils/json.ts
85
+ function safeJsonParse(text) {
86
+ try {
87
+ return { ok: true, value: JSON.parse(text) };
88
+ } catch (error) {
89
+ return { ok: false, error: error instanceof Error ? error.message : "Invalid JSON" };
90
+ }
91
+ }
92
+ function safeJsonStringify(value, space) {
93
+ const seen = /* @__PURE__ */ new WeakSet();
94
+ try {
95
+ const out = JSON.stringify(
96
+ value,
97
+ (_key, v) => {
98
+ if (typeof v === "bigint") return v.toString();
99
+ if (typeof v === "function" || typeof v === "symbol") return void 0;
100
+ if (v instanceof Error) return { name: v.name, message: v.message };
101
+ if (typeof v === "object" && v !== null) {
102
+ if (seen.has(v)) return "[Circular]";
103
+ seen.add(v);
104
+ }
105
+ return v;
106
+ },
107
+ space
108
+ );
109
+ return out ?? "null";
110
+ } catch {
111
+ return '"[Unserializable]"';
112
+ }
113
+ }
114
+ function truncate(text, maxChars) {
115
+ if (text.length <= maxChars) return { text, truncated: false };
116
+ const marker = "\u2026[truncated]";
117
+ const keep = Math.max(0, maxChars - marker.length);
118
+ return { text: text.slice(0, keep) + marker, truncated: true };
119
+ }
120
+
121
+ // src/utils/redact.ts
122
+ var REDACTED = "[REDACTED]";
123
+ var DEFAULT_SECRET_KEYS = [
124
+ "password",
125
+ "passwd",
126
+ "secret",
127
+ "token",
128
+ "accesstoken",
129
+ "refreshtoken",
130
+ "apikey",
131
+ "api_key",
132
+ "authorization",
133
+ "cookie",
134
+ "creditcard",
135
+ "cardnumber",
136
+ "cvv",
137
+ "ssn"
138
+ ];
139
+ function redactKeys(value, keys = DEFAULT_SECRET_KEYS) {
140
+ const wanted = new Set(keys.map(normalizeKey));
141
+ const walk = (v, depth) => {
142
+ if (depth > 20 || v === null || typeof v !== "object") return v;
143
+ if (Array.isArray(v)) return v.map((item) => walk(item, depth + 1));
144
+ const out = {};
145
+ for (const [k, inner] of Object.entries(v)) {
146
+ out[k] = wanted.has(normalizeKey(k)) ? REDACTED : walk(inner, depth + 1);
147
+ }
148
+ return out;
149
+ };
150
+ return walk(value, 0);
151
+ }
152
+ function normalizeKey(key) {
153
+ return key.toLowerCase().replace(/[-_]/g, "");
154
+ }
155
+ var EMAIL_RE = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;
156
+ var LONG_NUMBER_RE = /\+?\d[\d\s-]{8,}\d/g;
157
+ function redactText(text) {
158
+ return text.replace(EMAIL_RE, REDACTED).replace(LONG_NUMBER_RE, REDACTED);
159
+ }
160
+
161
+ // src/utils/sentence-chunker.ts
162
+ var END_RE = /([.!?…。!?।॥]+["')\]]*)\s+/u;
163
+ var SentenceChunker = class {
164
+ buffer = "";
165
+ maxLength;
166
+ constructor(options = {}) {
167
+ this.maxLength = options.maxLength ?? 220;
168
+ }
169
+ /** Adds a delta and returns every sentence it completed (never empty strings). */
170
+ push(delta) {
171
+ this.buffer += delta;
172
+ const out = [];
173
+ for (let s = this.take(); s !== null; s = this.take()) {
174
+ if (s.length > 0) out.push(s);
175
+ }
176
+ return out;
177
+ }
178
+ /** Returns the buffered remainder (trimmed, may be empty) and resets the chunker. */
179
+ flush() {
180
+ const rest = this.buffer.trim();
181
+ this.buffer = "";
182
+ return rest;
183
+ }
184
+ take() {
185
+ const match = END_RE.exec(this.buffer);
186
+ const endIdx = match ? match.index + (match[1]?.length ?? 0) : -1;
187
+ const newline = this.buffer.indexOf("\n");
188
+ const candidates = [endIdx, newline].filter((i) => i >= 0);
189
+ if (candidates.length > 0) return this.cut(Math.min(...candidates));
190
+ if (this.buffer.length > this.maxLength) {
191
+ const window = this.buffer.slice(0, this.maxLength);
192
+ const soft = Math.max(window.lastIndexOf(", "), window.lastIndexOf(" "));
193
+ return this.cut(soft > this.maxLength / 3 ? soft + 1 : this.maxLength);
194
+ }
195
+ return null;
196
+ }
197
+ cut(at) {
198
+ const sentence = this.buffer.slice(0, at).trim();
199
+ this.buffer = this.buffer.slice(at).replace(/^\s+/, "");
200
+ return sentence;
201
+ }
202
+ };
203
+
204
+ // src/utils/vocabulary.ts
205
+ var lex = /[\p{L}\p{M}\p{N}_\u200c\u200d]+|[^\s]/gu;
206
+ var fold = (s) => s.normalize("NFC").toLowerCase();
207
+ var words = (s) => Array.from(s.matchAll(lex), (m) => fold(m[0]));
208
+ var latin = /^\p{Script=Latin}{5,}$/u;
209
+ var node = () => ({ next: /* @__PURE__ */ new Map(), entries: [] });
210
+ function deletionKeys(word, edits) {
211
+ const keys = /* @__PURE__ */ new Set([word.slice(0, 8)]);
212
+ let frontier = [...keys];
213
+ for (let edit = 0; edit < edits; edit++) {
214
+ const next = [];
215
+ for (const form of frontier)
216
+ for (let i = 0; i < form.length; i++) {
217
+ const shortened = form.slice(0, i) + form.slice(i + 1);
218
+ if (!keys.has(shortened)) {
219
+ keys.add(shortened);
220
+ next.push(shortened);
221
+ }
222
+ }
223
+ frontier = next;
224
+ }
225
+ return keys;
226
+ }
227
+ function build(v) {
228
+ const root = node();
229
+ const fuzzy = /* @__PURE__ */ new Map();
230
+ function add(s, entry) {
231
+ let n = root;
232
+ for (const token of words(s)) {
233
+ let child = n.next.get(token);
234
+ if (!child) {
235
+ child = node();
236
+ n.next.set(token, child);
237
+ }
238
+ n = child;
239
+ }
240
+ n.entries.push(entry);
241
+ const key = fold(s);
242
+ if (entry.kind !== "regional" && !entry.term.protected && latin.test(key)) {
243
+ const set = fuzzy.get(key) ?? /* @__PURE__ */ new Set();
244
+ set.add(entry.term);
245
+ fuzzy.set(key, set);
246
+ }
247
+ }
248
+ for (const source of v.terms) {
249
+ const term = /\p{N}|[@$₹€£]|:\/\//u.test(source.term) ? { ...source, protected: true } : source;
250
+ add(term.term, { term, kind: "canonical" });
251
+ for (const a of term.aliases ?? []) add(a, { term, kind: "alias" });
252
+ for (const [language, forms] of Object.entries(term.regional ?? {}))
253
+ for (const f of forms) add(f, { term, kind: "regional", language });
254
+ }
255
+ for (const term of v.terms)
256
+ if (term.protected || /\p{N}|[@$₹€£]|:\/\//u.test(term.term)) {
257
+ for (const name of [
258
+ term.term,
259
+ ...term.aliases ?? [],
260
+ ...Object.values(term.regional ?? {}).flat()
261
+ ])
262
+ fuzzy.delete(fold(name));
263
+ }
264
+ const buckets = /* @__PURE__ */ new Map();
265
+ for (const form of fuzzy.keys())
266
+ for (const key of deletionKeys(form, 2)) {
267
+ const bucket = buckets.get(key);
268
+ if (bucket) bucket.push(form);
269
+ else buckets.set(key, [form]);
270
+ }
271
+ return { root, fuzzy, buckets };
272
+ }
273
+ var indexes = /* @__PURE__ */ new WeakMap();
274
+ function indexFor(v) {
275
+ let i = indexes.get(v);
276
+ if (!i) {
277
+ i = build(v);
278
+ indexes.set(v, i);
279
+ }
280
+ return i;
281
+ }
282
+ function distance(a, b, limit) {
283
+ if (Math.abs(a.length - b.length) > limit) return limit + 1;
284
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
285
+ for (let i = 1; i <= a.length; i++) {
286
+ const row = [i];
287
+ let best = i;
288
+ for (let j = 1; j <= b.length; j++) {
289
+ const cost = Math.min(
290
+ (prev[j] ?? 0) + 1,
291
+ (row[j - 1] ?? 0) + 1,
292
+ (prev[j - 1] ?? 0) + Number(a[i - 1] !== b[j - 1])
293
+ );
294
+ row.push(cost);
295
+ best = Math.min(best, cost);
296
+ }
297
+ if (best > limit) return limit + 1;
298
+ prev = row;
299
+ }
300
+ return prev[b.length] ?? limit + 1;
301
+ }
302
+ function nearest(word, index) {
303
+ let best = word.length < 9 ? 1 : 2;
304
+ const hits = /* @__PURE__ */ new Set();
305
+ const candidates = /* @__PURE__ */ new Set();
306
+ for (const key of deletionKeys(word, best))
307
+ for (const form of index.buckets.get(key) ?? []) candidates.add(form);
308
+ for (const form of candidates) {
309
+ const terms = index.fuzzy.get(form) ?? [];
310
+ const d = distance(word, form, best);
311
+ if (d > best) continue;
312
+ if (d < best) {
313
+ best = d;
314
+ hits.clear();
315
+ }
316
+ for (const t of terms) hits.add(t.term);
317
+ }
318
+ const result = [...hits].sort();
319
+ return result;
320
+ }
321
+ var protectedPattern = /(?:https?:\/\/|www\.)[^\s]+|(?:[$₹€£]\s*|(?:rupees|dollars)\s+)\p{N}[\p{N},.]*(?:\s*%)?|\p{N}+[\s/-]+(?:January|February|March|April|May|June|July|August|September|October|November|December)\b|\p{N}[\p{N},.]*\s*(?:rupees|dollars|%)/giu;
322
+ function correctWithVocabulary(text, vocab, options = {}) {
323
+ const index = indexFor(vocab), tokens = Array.from(text.matchAll(lex));
324
+ const changes = [], ambiguous = [];
325
+ const blocked = new Uint8Array(tokens.length);
326
+ let pos = 0;
327
+ const spans = Array.from(text.matchAll(protectedPattern));
328
+ for (const m of text.matchAll(/\S+/gu)) {
329
+ if (/\p{N}/u.test(m[0])) spans.push(m);
330
+ else if (/^(?:[\p{L}\p{N}-]+\.)+[\p{L}]{2,}(?:[/?#]\S*)?$/iu.test(m[0])) spans.push(m);
331
+ else if (m[0].includes("@") && /^[^@]+@[^@]+\.[^@]+$/u.test(m[0])) spans.push(m);
332
+ }
333
+ spans.sort((a, b) => a.index - b.index);
334
+ for (const m of spans) {
335
+ while (pos < tokens.length && (tokens[pos]?.index ?? 0) + (tokens[pos]?.[0].length ?? 0) <= m.index)
336
+ pos++;
337
+ while (pos < tokens.length && (tokens[pos]?.index ?? Infinity) < m.index + m[0].length)
338
+ blocked[pos++] = 1;
339
+ }
340
+ const keys = tokens.map((m) => fold(m[0]));
341
+ function matches(i) {
342
+ const list = [];
343
+ let n = index.root;
344
+ for (let j = i; j < keys.length; j++) {
345
+ n = n.next.get(keys[j] ?? "");
346
+ if (!n) break;
347
+ if (n.entries.length) list.push({ end: j + 1, entries: n.entries });
348
+ }
349
+ return list;
350
+ }
351
+ for (let i = 0; i < keys.length; i++) {
352
+ if (/\p{N}/u.test(keys[i] ?? "")) blocked[i] = 1;
353
+ for (const m of matches(i))
354
+ if (m.entries.some((e) => e.term.protected)) blocked.fill(1, i, m.end);
355
+ }
356
+ let result = "", cursor = 0;
357
+ for (let i = 0; i < tokens.length; i++) {
358
+ const first = tokens[i];
359
+ if (!first || blocked[i]) continue;
360
+ let end = i + 1, kind = "fuzzy", names = [];
361
+ let exact = false;
362
+ const matchesHere = matches(i).reverse().filter((m) => !blocked.subarray(i, m.end).includes(1));
363
+ for (const regional of [false, true]) {
364
+ if (regional && options.regionalToCanonical === false) break;
365
+ for (const match of matchesHere) {
366
+ const forms = match.entries.filter((e) => e.kind === "regional" === regional);
367
+ if (!forms.length) continue;
368
+ end = match.end;
369
+ exact = true;
370
+ kind = regional ? "regional" : "alias";
371
+ names = [...new Set(forms.map((e) => e.term.term))].sort();
372
+ if (names.length === 1 && forms.some((e) => e.kind === "canonical")) names = [];
373
+ break;
374
+ }
375
+ if (exact) break;
376
+ }
377
+ if (!exact && options.fuzzy !== false && latin.test(keys[i] ?? ""))
378
+ names = nearest(keys[i] ?? "", index);
379
+ const last = tokens[end - 1] ?? first;
380
+ const finish = last.index + last[0].length;
381
+ const span = text.slice(first.index, finish);
382
+ if (names.length > 1) ambiguous.push({ span, candidates: names });
383
+ else if (names[0] && names[0] !== span) {
384
+ result += text.slice(cursor, first.index) + names[0];
385
+ cursor = finish;
386
+ changes.push({ from: span, to: names[0], term: names[0], kind });
387
+ }
388
+ i = end - 1;
389
+ }
390
+ return { raw: text, text: result + text.slice(cursor), changes, ambiguous };
391
+ }
392
+ function ranked(v) {
393
+ return [...v.terms].sort((a, b) => (b.weight ?? 1) - (a.weight ?? 1));
394
+ }
395
+ function vocabularyHints(v, max = 50) {
396
+ return [...new Set(ranked(v).map((t) => t.term))].slice(0, Math.max(0, max));
397
+ }
398
+ function sttPromptFromVocabulary(v, options = {}) {
399
+ let result = "";
400
+ for (const t of ranked(v)) {
401
+ const forms = [
402
+ t.term,
403
+ ...t.pronunciations ?? [],
404
+ ...t.regional?.[baseLanguage(options.language ?? "")] ?? []
405
+ ];
406
+ for (const form of forms) {
407
+ const next = [result, form].filter(Boolean).join(", ");
408
+ if (next.length <= (options.maxChars ?? 224)) result = next;
409
+ }
410
+ }
411
+ return result;
412
+ }
413
+ function autoVocabulary(input) {
414
+ return {
415
+ terms: [...input.routes ?? []].map((r) => ({ term: r.title, weight: 0 })).concat((input.tools ?? []).map((t) => ({ term: t.title ?? t.name, weight: 0 })))
416
+ };
417
+ }
418
+
419
+ export { DEFAULT_SECRET_KEYS, REDACTED, SentenceChunker, TypedEmitter, autoVocabulary, combineSignals, correctWithVocabulary, createId, indexFor, redactKeys, redactText, safeJsonParse, safeJsonStringify, sleep, sttPromptFromVocabulary, truncate, vocabularyHints };
420
+ //# sourceMappingURL=chunk-PU7PGHHO.js.map
421
+ //# sourceMappingURL=chunk-PU7PGHHO.js.map