@speeq/core 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-CELQUH6A.js +166 -0
- package/dist/chunk-CELQUH6A.js.map +1 -0
- package/dist/{chunk-JA2L35IQ.js → chunk-FRW2OUQL.js} +8 -2
- package/dist/chunk-FRW2OUQL.js.map +1 -0
- package/dist/chunk-PU7PGHHO.js +421 -0
- package/dist/chunk-PU7PGHHO.js.map +1 -0
- package/dist/errors.cjs +6 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/index-DPp4Fwdy.d.cts +236 -0
- package/dist/index-I0oTxGMf.d.ts +236 -0
- package/dist/index.cjs +365 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +176 -3
- package/dist/index.d.ts +176 -3
- package/dist/index.js +87 -4
- package/dist/index.js.map +1 -1
- package/dist/manifest.cjs +230 -0
- package/dist/manifest.cjs.map +1 -0
- package/dist/manifest.d.cts +2523 -0
- package/dist/manifest.d.ts +2523 -0
- package/dist/manifest.js +218 -0
- package/dist/manifest.js.map +1 -0
- package/dist/speech-http.cjs +346 -0
- package/dist/speech-http.cjs.map +1 -0
- package/dist/speech-http.d.cts +41 -0
- package/dist/speech-http.d.ts +41 -0
- package/dist/speech-http.js +264 -0
- package/dist/speech-http.js.map +1 -0
- package/dist/speech-provider-D0YChUSt.d.cts +103 -0
- package/dist/speech-provider-D0YChUSt.d.ts +103 -0
- package/dist/utils.cjs +237 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +2 -156
- package/dist/utils.d.ts +2 -156
- package/dist/utils.js +3 -2
- package/package.json +24 -2
- package/dist/chunk-JA2L35IQ.js.map +0 -1
- package/dist/chunk-JOTEKM5R.js +0 -318
- package/dist/chunk-JOTEKM5R.js.map +0 -1
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { SpeeqError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
/** Writing systems used by the lightweight language heuristic. */
|
|
4
|
+
type ScriptName = "latin" | "devanagari" | "telugu" | "tamil" | "kannada" | "malayalam" | "bengali" | "gujarati" | "gurmukhi" | "odia" | "arabic";
|
|
5
|
+
/** Extract the normalized primary language subtag. */
|
|
6
|
+
declare function baseLanguage(tag: string): string;
|
|
7
|
+
/** Return a two-letter primary language when the tag has one. */
|
|
8
|
+
declare function toIso639_1(tag: string): string | undefined;
|
|
9
|
+
/** Count letters in each script, excluding digits and punctuation. */
|
|
10
|
+
declare function detectScripts(text: string): {
|
|
11
|
+
counts: Partial<Record<ScriptName, number>>;
|
|
12
|
+
dominant: ScriptName | undefined;
|
|
13
|
+
mixed: boolean;
|
|
14
|
+
};
|
|
15
|
+
/** Infer a candidate language from script evidence, leaving shared Devanagari unresolved. */
|
|
16
|
+
declare function guessLanguageFromScript(text: string, candidates: readonly string[]): {
|
|
17
|
+
confidence: number;
|
|
18
|
+
mixed: boolean;
|
|
19
|
+
language?: undefined;
|
|
20
|
+
} | {
|
|
21
|
+
language: string | undefined;
|
|
22
|
+
confidence: number;
|
|
23
|
+
mixed: boolean;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Returns an `AbortSignal` that aborts when any input signal aborts, or after `timeoutMs`.
|
|
28
|
+
* It uses `AbortSignal.any` / `AbortSignal.timeout` when available, with a manual fallback.
|
|
29
|
+
*/
|
|
30
|
+
declare function combineSignals(signals: ReadonlyArray<AbortSignal | undefined>, timeoutMs?: number): AbortSignal;
|
|
31
|
+
/** Resolves after `ms` milliseconds, or rejects early when `signal` aborts. */
|
|
32
|
+
declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
33
|
+
|
|
34
|
+
/** A listener for event `K` of an event map `E`. */
|
|
35
|
+
type Listener<E, K extends keyof E> = (payload: E[K]) => void;
|
|
36
|
+
/**
|
|
37
|
+
* A tiny, typed event emitter. A listener that throws never breaks other listeners or the
|
|
38
|
+
* emitter (the error is reported with `console.error`).
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* const em = new TypedEmitter<{ state: "idle" | "busy" }>();
|
|
42
|
+
* const off = em.on("state", (s) => console.log(s));
|
|
43
|
+
* em.emit("state", "busy");
|
|
44
|
+
* off();
|
|
45
|
+
*/
|
|
46
|
+
declare class TypedEmitter<E extends Record<string, unknown>> {
|
|
47
|
+
private readonly listeners;
|
|
48
|
+
/** Subscribes to `event`. Returns an unsubscribe function. */
|
|
49
|
+
on<K extends keyof E>(event: K, listener: Listener<E, K>): () => void;
|
|
50
|
+
/** Subscribes to the next `event` only. */
|
|
51
|
+
once<K extends keyof E>(event: K, listener: Listener<E, K>): () => void;
|
|
52
|
+
/** Removes a listener. */
|
|
53
|
+
off<K extends keyof E>(event: K, listener: Listener<E, K>): void;
|
|
54
|
+
/** Calls every listener for `event` with `payload`. */
|
|
55
|
+
emit<K extends keyof E>(event: K, payload: E[K]): void;
|
|
56
|
+
/** Removes every listener. */
|
|
57
|
+
clear(): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Returns a random, URL-safe id such as `ses_3f9a…`. It uses `crypto.randomUUID()`, which is
|
|
62
|
+
* available in browsers, Node 20+ and edge runtimes. Ids never encode user data.
|
|
63
|
+
*
|
|
64
|
+
* @param prefix - A short readable prefix such as `ses`, `evt` or `turn`.
|
|
65
|
+
*/
|
|
66
|
+
declare function createId(prefix: string): string;
|
|
67
|
+
|
|
68
|
+
/** Result of {@link safeJsonParse}. */
|
|
69
|
+
type SafeJsonResult<T = unknown> = {
|
|
70
|
+
ok: true;
|
|
71
|
+
value: T;
|
|
72
|
+
} | {
|
|
73
|
+
ok: false;
|
|
74
|
+
error: string;
|
|
75
|
+
};
|
|
76
|
+
/** Parses JSON without throwing. */
|
|
77
|
+
declare function safeJsonParse<T = unknown>(text: string): SafeJsonResult<T>;
|
|
78
|
+
/**
|
|
79
|
+
* Stringifies any value without throwing: handles cycles (`"[Circular]"`), `bigint`, `Error`,
|
|
80
|
+
* `undefined` at the top level and functions. Use it for tool output before sending it to a model.
|
|
81
|
+
*/
|
|
82
|
+
declare function safeJsonStringify(value: unknown, space?: number): string;
|
|
83
|
+
/** Result of {@link truncate}. */
|
|
84
|
+
interface TruncateResult {
|
|
85
|
+
text: string;
|
|
86
|
+
truncated: boolean;
|
|
87
|
+
}
|
|
88
|
+
/** Cuts `text` to at most `maxChars` characters and marks whether it was cut. */
|
|
89
|
+
declare function truncate(text: string, maxChars: number): TruncateResult;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Reads the `data:` payloads of an SSE response body. For LLM adapters: stops at `[DONE]`
|
|
93
|
+
* and honors `signal`.
|
|
94
|
+
*/
|
|
95
|
+
declare function readSseData(body: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncGenerator<string>;
|
|
96
|
+
/** Parses a `Retry-After` header (seconds or HTTP date) into milliseconds. */
|
|
97
|
+
declare function parseRetryAfter(value: string | null | undefined): number | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Maps an HTTP error from an LLM provider to a {@link SpeeqError}:
|
|
100
|
+
* 429 and quota or rate-limit bodies → `RATE_LIMITED` (with a retry hint), 401/403 →
|
|
101
|
+
* `NOT_CONFIGURED` (bad API key), anything else → `PROVIDER_ERROR`. The provider's raw message
|
|
102
|
+
* is kept in `details` for server logs, never in the public message.
|
|
103
|
+
*/
|
|
104
|
+
declare function mapProviderHttpError(provider: string, status: number, bodyText: string, retryAfter?: string | null): SpeeqError;
|
|
105
|
+
/** Wraps `fetch` so network failures become `PROVIDER_ERROR` and aborts are rethrown as-is. */
|
|
106
|
+
declare function providerFetch(provider: string, fetchImpl: typeof fetch, url: string, init: RequestInit): Promise<Response>;
|
|
107
|
+
|
|
108
|
+
/** The placeholder written in place of redacted values. */
|
|
109
|
+
declare const REDACTED = "[REDACTED]";
|
|
110
|
+
/** Keys that are redacted by default by {@link redactKeys}. Matching ignores case. */
|
|
111
|
+
declare const DEFAULT_SECRET_KEYS: readonly string[];
|
|
112
|
+
/**
|
|
113
|
+
* Returns a deep copy of `value` with the values of matching keys replaced by `[REDACTED]`.
|
|
114
|
+
* Matching ignores case and also strips `-` / `_`, so `api-key` matches `apikey`.
|
|
115
|
+
*/
|
|
116
|
+
declare function redactKeys<T>(value: T, keys?: readonly string[]): T;
|
|
117
|
+
/** Replaces email addresses and long digit sequences (phones, cards) in free text. */
|
|
118
|
+
declare function redactText(text: string): string;
|
|
119
|
+
|
|
120
|
+
/** Options for {@link SentenceChunker}. */
|
|
121
|
+
interface SentenceChunkerOptions {
|
|
122
|
+
/** Force a split (at the last comma or space) once a sentence grows past this length. */
|
|
123
|
+
maxLength?: number;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Splits streamed text deltas into whole sentences, so text-to-speech can start speaking the
|
|
127
|
+
* first sentence while the rest is still generating.
|
|
128
|
+
*
|
|
129
|
+
* A sentence ends at end-punctuation followed by whitespace, or at a newline. Punctuation at the
|
|
130
|
+
* very end of the buffer waits for more input, so `3.` + `5` stays `3.5`. Overlong text is split
|
|
131
|
+
* at the last comma or space before `maxLength`.
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* const c = new SentenceChunker();
|
|
135
|
+
* c.push("Hello the"); // []
|
|
136
|
+
* c.push("re. How are"); // ["Hello there."]
|
|
137
|
+
* c.flush(); // "How are"
|
|
138
|
+
*/
|
|
139
|
+
declare class SentenceChunker {
|
|
140
|
+
private buffer;
|
|
141
|
+
private readonly maxLength;
|
|
142
|
+
constructor(options?: SentenceChunkerOptions);
|
|
143
|
+
/** Adds a delta and returns every sentence it completed (never empty strings). */
|
|
144
|
+
push(delta: string): string[];
|
|
145
|
+
/** Returns the buffered remainder (trimmed, may be empty) and resets the chunker. */
|
|
146
|
+
flush(): string;
|
|
147
|
+
private take;
|
|
148
|
+
private cut;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** One parsed Server-Sent Event. */
|
|
152
|
+
interface SseMessage {
|
|
153
|
+
/** The `event:` field, or `"message"` when absent. */
|
|
154
|
+
event: string;
|
|
155
|
+
/** The joined `data:` lines. */
|
|
156
|
+
data: string;
|
|
157
|
+
id?: string;
|
|
158
|
+
}
|
|
159
|
+
/** Encodes one SSE message (`event:` + `data:` lines + blank line). */
|
|
160
|
+
declare function encodeSse(event: string, data: string): string;
|
|
161
|
+
/**
|
|
162
|
+
* Incremental SSE parser that follows the WHATWG event-stream rules. Feed it decoded text chunks
|
|
163
|
+
* in any split (mid-line, mid-field, CRLF across chunks) and it returns complete messages.
|
|
164
|
+
*/
|
|
165
|
+
declare class SseParser {
|
|
166
|
+
private buffer;
|
|
167
|
+
private event;
|
|
168
|
+
private data;
|
|
169
|
+
private id;
|
|
170
|
+
/** Adds a chunk and returns every message completed by it. */
|
|
171
|
+
push(chunk: string): SseMessage[];
|
|
172
|
+
/** Flushes a final message that was not followed by a blank line (end of stream). */
|
|
173
|
+
end(): SseMessage[];
|
|
174
|
+
private processLine;
|
|
175
|
+
private dispatch;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Canonical domain term, spoken forms and relative hint priority. */
|
|
179
|
+
interface VocabularyTerm {
|
|
180
|
+
term: string;
|
|
181
|
+
aliases?: readonly string[];
|
|
182
|
+
pronunciations?: readonly string[];
|
|
183
|
+
regional?: Readonly<Record<string, readonly string[]>>;
|
|
184
|
+
protected?: boolean;
|
|
185
|
+
weight?: number;
|
|
186
|
+
}
|
|
187
|
+
/** Developer-owned terminology. */
|
|
188
|
+
interface Vocabulary {
|
|
189
|
+
terms: readonly VocabularyTerm[];
|
|
190
|
+
}
|
|
191
|
+
/** One deterministic replacement in a transcript. */
|
|
192
|
+
interface CorrectionChange {
|
|
193
|
+
from: string;
|
|
194
|
+
to: string;
|
|
195
|
+
term: string;
|
|
196
|
+
kind: "alias" | "regional" | "fuzzy";
|
|
197
|
+
}
|
|
198
|
+
/** Original transcript, corrected display text and unresolved spans. */
|
|
199
|
+
interface CorrectionResult {
|
|
200
|
+
raw: string;
|
|
201
|
+
text: string;
|
|
202
|
+
changes: readonly CorrectionChange[];
|
|
203
|
+
ambiguous: readonly {
|
|
204
|
+
span: string;
|
|
205
|
+
candidates: readonly string[];
|
|
206
|
+
}[];
|
|
207
|
+
}
|
|
208
|
+
/** Optional correction controls. */
|
|
209
|
+
interface CorrectionOptions {
|
|
210
|
+
language?: string;
|
|
211
|
+
regionalToCanonical?: boolean;
|
|
212
|
+
fuzzy?: boolean;
|
|
213
|
+
}
|
|
214
|
+
/** Correct whole spans conservatively and preserve all unmatched original characters. */
|
|
215
|
+
declare function correctWithVocabulary(text: string, vocab: Vocabulary, options?: CorrectionOptions): CorrectionResult;
|
|
216
|
+
/** Most important canonical terms for native hints and agent instructions. */
|
|
217
|
+
declare function vocabularyHints(v: Vocabulary, max?: number): string[];
|
|
218
|
+
/** Build a bounded recognizer prompt without splitting a term. */
|
|
219
|
+
declare function sttPromptFromVocabulary(v: Vocabulary, options?: {
|
|
220
|
+
language?: string;
|
|
221
|
+
maxChars?: number;
|
|
222
|
+
}): string;
|
|
223
|
+
/** Low-priority terms derived from host routes and tools. */
|
|
224
|
+
declare function autoVocabulary(input: {
|
|
225
|
+
routes?: readonly {
|
|
226
|
+
id: string;
|
|
227
|
+
title: string;
|
|
228
|
+
}[];
|
|
229
|
+
tools?: readonly {
|
|
230
|
+
name: string;
|
|
231
|
+
title?: string;
|
|
232
|
+
}[];
|
|
233
|
+
}): Vocabulary;
|
|
234
|
+
|
|
235
|
+
export { sttPromptFromVocabulary as A, toIso639_1 as B, DEFAULT_SECRET_KEYS as D, truncate as E, vocabularyHints as F, REDACTED as R, SentenceChunker as d, SseParser as g, TypedEmitter as h, autoVocabulary as j, baseLanguage as k, combineSignals as l, correctWithVocabulary as m, createId as n, detectScripts as o, encodeSse as p, guessLanguageFromScript as q, mapProviderHttpError as r, parseRetryAfter as s, providerFetch as t, readSseData as u, redactKeys as v, redactText as w, safeJsonParse as x, safeJsonStringify as y, sleep as z };
|
|
236
|
+
export type { CorrectionChange as C, Listener as L, SafeJsonResult as S, TruncateResult as T, Vocabulary as V, CorrectionOptions as a, CorrectionResult as b, ScriptName as c, SentenceChunkerOptions as e, SseMessage as f, VocabularyTerm as i };
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,8 @@ var ERROR_CODES = [
|
|
|
21
21
|
"NOT_FOUND",
|
|
22
22
|
"CONFLICT",
|
|
23
23
|
"RATE_LIMITED",
|
|
24
|
+
"SPEECH_UNAVAILABLE",
|
|
25
|
+
"PAYLOAD_TOO_LARGE",
|
|
24
26
|
"PROVIDER_ERROR",
|
|
25
27
|
"TOOL_ERROR",
|
|
26
28
|
"TOOL_TIMEOUT",
|
|
@@ -36,6 +38,8 @@ var ERROR_HTTP_STATUS = {
|
|
|
36
38
|
NOT_FOUND: 404,
|
|
37
39
|
CONFLICT: 409,
|
|
38
40
|
RATE_LIMITED: 429,
|
|
41
|
+
SPEECH_UNAVAILABLE: 503,
|
|
42
|
+
PAYLOAD_TOO_LARGE: 413,
|
|
39
43
|
PROVIDER_ERROR: 502,
|
|
40
44
|
TOOL_ERROR: 500,
|
|
41
45
|
TOOL_TIMEOUT: 504,
|
|
@@ -51,6 +55,8 @@ var DEFAULT_ERROR_MESSAGES = {
|
|
|
51
55
|
NOT_FOUND: "That could not be found.",
|
|
52
56
|
CONFLICT: "That was already handled.",
|
|
53
57
|
RATE_LIMITED: "The assistant is busy right now. Please try again in a moment.",
|
|
58
|
+
SPEECH_UNAVAILABLE: "Voice is not available right now. You can type instead.",
|
|
59
|
+
PAYLOAD_TOO_LARGE: "That audio is too long.",
|
|
54
60
|
PROVIDER_ERROR: "The AI provider had a problem. Please try again.",
|
|
55
61
|
TOOL_ERROR: "An action failed to run.",
|
|
56
62
|
TOOL_TIMEOUT: "An action took too long and was stopped.",
|
|
@@ -106,6 +112,55 @@ function toPublicError(error) {
|
|
|
106
112
|
function isAbortError(error) {
|
|
107
113
|
return typeof error === "object" && error !== null && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
108
114
|
}
|
|
115
|
+
|
|
116
|
+
// src/language.ts
|
|
117
|
+
var scripts = {
|
|
118
|
+
latin: [/\p{Script=Latin}/u, "en"],
|
|
119
|
+
devanagari: [/\p{Script=Devanagari}/u, "hi"],
|
|
120
|
+
telugu: [/\p{Script=Telugu}/u, "te"],
|
|
121
|
+
tamil: [/\p{Script=Tamil}/u, "ta"],
|
|
122
|
+
kannada: [/\p{Script=Kannada}/u, "kn"],
|
|
123
|
+
malayalam: [/\p{Script=Malayalam}/u, "ml"],
|
|
124
|
+
bengali: [/\p{Script=Bengali}/u, "bn"],
|
|
125
|
+
gujarati: [/\p{Script=Gujarati}/u, "gu"],
|
|
126
|
+
gurmukhi: [/\p{Script=Gurmukhi}/u, "pa"],
|
|
127
|
+
odia: [/\p{Script=Oriya}/u, "or"],
|
|
128
|
+
arabic: [/\p{Script=Arabic}/u, "ur"]
|
|
129
|
+
};
|
|
130
|
+
function baseLanguage(tag) {
|
|
131
|
+
return tag.trim().split(/[-_]/)[0]?.toLowerCase() ?? "";
|
|
132
|
+
}
|
|
133
|
+
function toIso639_1(tag) {
|
|
134
|
+
try {
|
|
135
|
+
const base2 = new Intl.Locale(baseLanguage(tag)).language;
|
|
136
|
+
return /^[a-z]{2}$/.test(base2) && new Intl.DisplayNames("en", { type: "language", fallback: "none" }).of(base2) ? base2 : void 0;
|
|
137
|
+
} catch {
|
|
138
|
+
return void 0;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function detectScripts(text) {
|
|
142
|
+
const counts = {};
|
|
143
|
+
let dominant;
|
|
144
|
+
const entries = Object.entries(scripts);
|
|
145
|
+
for (const c of text) {
|
|
146
|
+
if (!/\p{L}/u.test(c)) continue;
|
|
147
|
+
const name = entries.find(([, s]) => s[0].test(c))?.[0];
|
|
148
|
+
if (!name) continue;
|
|
149
|
+
const count2 = (counts[name] ?? 0) + 1;
|
|
150
|
+
counts[name] = count2;
|
|
151
|
+
if (!dominant || count2 > (counts[dominant] ?? 0)) dominant = name;
|
|
152
|
+
}
|
|
153
|
+
return { counts, dominant, mixed: Object.keys(counts).length > 1 };
|
|
154
|
+
}
|
|
155
|
+
function guessLanguageFromScript(text, candidates) {
|
|
156
|
+
const { counts, dominant, mixed } = detectScripts(text);
|
|
157
|
+
if (!dominant) return { confidence: 0, mixed };
|
|
158
|
+
if (dominant === "devanagari" && candidates.some((c) => ["mr", "ne", "sa"].includes(baseLanguage(c))))
|
|
159
|
+
return { confidence: 0.3, mixed };
|
|
160
|
+
const language = candidates.find((c) => baseLanguage(c) === scripts[dominant][1]);
|
|
161
|
+
const total = Object.values(counts).reduce((a, b) => a + b, 0);
|
|
162
|
+
return { language, confidence: language ? (counts[dominant] ?? 0) / total : 0, mixed };
|
|
163
|
+
}
|
|
109
164
|
var LanguageSchema = zod.z.string().regex(/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/, "Expected a BCP 47 language tag like en-IN");
|
|
110
165
|
var ErrorCodeSchema = zod.z.enum(ERROR_CODES);
|
|
111
166
|
var PageContextSchema = zod.z.object({
|
|
@@ -271,6 +326,7 @@ var CreateSessionRequestSchema = zod.z.object({
|
|
|
271
326
|
context: PageContextSchema.optional()
|
|
272
327
|
});
|
|
273
328
|
var ClientConfigSchema = zod.z.object({
|
|
329
|
+
speech: zod.z.object({ stt: zod.z.boolean(), tts: zod.z.boolean(), detectsLanguage: zod.z.boolean().optional() }).optional(),
|
|
274
330
|
agentName: zod.z.string(),
|
|
275
331
|
languages: zod.z.array(LanguageSchema).min(1),
|
|
276
332
|
defaultLanguage: LanguageSchema,
|
|
@@ -292,6 +348,14 @@ var CreateSessionResponseSchema = zod.z.object({
|
|
|
292
348
|
config: ClientConfigSchema
|
|
293
349
|
});
|
|
294
350
|
var TurnRequestSchema = zod.z.object({
|
|
351
|
+
inputLanguage: LanguageSchema.optional(),
|
|
352
|
+
transcript: zod.z.object({
|
|
353
|
+
raw: zod.z.string().max(MAX_TURN_TEXT_CHARS * 4),
|
|
354
|
+
confidence: zod.z.number().min(0).max(1).optional(),
|
|
355
|
+
provider: zod.z.string().max(200).optional(),
|
|
356
|
+
corrected: zod.z.boolean().optional(),
|
|
357
|
+
ambiguous: zod.z.array(zod.z.string().max(2e3)).max(200).optional()
|
|
358
|
+
}).optional(),
|
|
295
359
|
text: zod.z.string().trim().min(1).max(MAX_TURN_TEXT_CHARS),
|
|
296
360
|
language: LanguageSchema,
|
|
297
361
|
context: PageContextSchema.optional(),
|
|
@@ -322,6 +386,7 @@ var base = {
|
|
|
322
386
|
var TurnStartedEventSchema = zod.z.object({
|
|
323
387
|
...base,
|
|
324
388
|
type: zod.z.literal("turn.started"),
|
|
389
|
+
inputLanguage: LanguageSchema.optional(),
|
|
325
390
|
sessionId: zod.z.string(),
|
|
326
391
|
language: LanguageSchema
|
|
327
392
|
});
|
|
@@ -406,6 +471,52 @@ var PROTOCOL_EVENT_TYPES = [
|
|
|
406
471
|
"error",
|
|
407
472
|
"turn.finished"
|
|
408
473
|
];
|
|
474
|
+
var VoiceInfoSchema = zod.z.object({
|
|
475
|
+
id: zod.z.string(),
|
|
476
|
+
name: zod.z.string(),
|
|
477
|
+
languages: zod.z.array(LanguageSchema),
|
|
478
|
+
locale: LanguageSchema.optional(),
|
|
479
|
+
gender: zod.z.enum(["female", "male", "neutral"]).optional(),
|
|
480
|
+
accent: zod.z.string().optional(),
|
|
481
|
+
styles: zod.z.array(zod.z.string()).optional(),
|
|
482
|
+
provider: zod.z.string(),
|
|
483
|
+
processing: zod.z.enum(["local", "remote"]),
|
|
484
|
+
streaming: zod.z.boolean(),
|
|
485
|
+
supports: zod.z.object({
|
|
486
|
+
rate: zod.z.boolean(),
|
|
487
|
+
pitch: zod.z.boolean(),
|
|
488
|
+
volume: zod.z.boolean(),
|
|
489
|
+
style: zod.z.boolean()
|
|
490
|
+
})
|
|
491
|
+
});
|
|
492
|
+
var TranscribeQuerySchema = zod.z.object({
|
|
493
|
+
language: LanguageSchema.optional(),
|
|
494
|
+
utteranceId: zod.z.string().min(1).max(100).optional()
|
|
495
|
+
});
|
|
496
|
+
var TranscribeResponseSchema = zod.z.object({
|
|
497
|
+
raw: zod.z.string().optional(),
|
|
498
|
+
corrected: zod.z.boolean().optional(),
|
|
499
|
+
ambiguous: zod.z.array(zod.z.string()).optional(),
|
|
500
|
+
text: zod.z.string(),
|
|
501
|
+
silent: zod.z.boolean().optional(),
|
|
502
|
+
language: LanguageSchema.optional(),
|
|
503
|
+
languageConfidence: zod.z.number().min(0).max(1).optional(),
|
|
504
|
+
confidence: zod.z.number().min(0).max(1).optional(),
|
|
505
|
+
providerId: zod.z.string().optional(),
|
|
506
|
+
providerMs: zod.z.number().nonnegative().optional(),
|
|
507
|
+
audioMs: zod.z.number().nonnegative().optional()
|
|
508
|
+
});
|
|
509
|
+
var SynthesizeRequestSchema = zod.z.object({
|
|
510
|
+
text: zod.z.string().trim().min(1).max(1e3),
|
|
511
|
+
language: LanguageSchema,
|
|
512
|
+
voiceId: zod.z.string().max(100).optional(),
|
|
513
|
+
rate: zod.z.number().min(0.25).max(4).optional(),
|
|
514
|
+
pitch: zod.z.number().min(0.25).max(4).optional(),
|
|
515
|
+
volume: zod.z.number().min(0).max(1).optional(),
|
|
516
|
+
style: zod.z.string().max(200).optional(),
|
|
517
|
+
format: zod.z.enum(["mp3", "wav", "opus", "pcm16"]).optional()
|
|
518
|
+
});
|
|
519
|
+
var VoicesResponseSchema = zod.z.object({ voices: zod.z.array(VoiceInfoSchema) });
|
|
409
520
|
var count = zod.z.number().int().nonnegative().max(1e9);
|
|
410
521
|
var slug = zod.z.string().regex(/^[a-z0-9][a-z0-9.-]{0,39}$/);
|
|
411
522
|
var iso = zod.z.iso.datetime();
|
|
@@ -860,6 +971,246 @@ var SentenceChunker = class {
|
|
|
860
971
|
}
|
|
861
972
|
};
|
|
862
973
|
|
|
974
|
+
// src/utils/vocabulary.ts
|
|
975
|
+
var lex = /[\p{L}\p{M}\p{N}_\u200c\u200d]+|[^\s]/gu;
|
|
976
|
+
var fold = (s) => s.normalize("NFC").toLowerCase();
|
|
977
|
+
var words = (s) => Array.from(s.matchAll(lex), (m) => fold(m[0]));
|
|
978
|
+
var latin = /^\p{Script=Latin}{5,}$/u;
|
|
979
|
+
var node = () => ({ next: /* @__PURE__ */ new Map(), entries: [] });
|
|
980
|
+
function deletionKeys(word, edits) {
|
|
981
|
+
const keys = /* @__PURE__ */ new Set([word.slice(0, 8)]);
|
|
982
|
+
let frontier = [...keys];
|
|
983
|
+
for (let edit = 0; edit < edits; edit++) {
|
|
984
|
+
const next = [];
|
|
985
|
+
for (const form of frontier)
|
|
986
|
+
for (let i = 0; i < form.length; i++) {
|
|
987
|
+
const shortened = form.slice(0, i) + form.slice(i + 1);
|
|
988
|
+
if (!keys.has(shortened)) {
|
|
989
|
+
keys.add(shortened);
|
|
990
|
+
next.push(shortened);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
frontier = next;
|
|
994
|
+
}
|
|
995
|
+
return keys;
|
|
996
|
+
}
|
|
997
|
+
function build(v) {
|
|
998
|
+
const root = node();
|
|
999
|
+
const fuzzy = /* @__PURE__ */ new Map();
|
|
1000
|
+
function add(s, entry) {
|
|
1001
|
+
let n = root;
|
|
1002
|
+
for (const token of words(s)) {
|
|
1003
|
+
let child = n.next.get(token);
|
|
1004
|
+
if (!child) {
|
|
1005
|
+
child = node();
|
|
1006
|
+
n.next.set(token, child);
|
|
1007
|
+
}
|
|
1008
|
+
n = child;
|
|
1009
|
+
}
|
|
1010
|
+
n.entries.push(entry);
|
|
1011
|
+
const key = fold(s);
|
|
1012
|
+
if (entry.kind !== "regional" && !entry.term.protected && latin.test(key)) {
|
|
1013
|
+
const set = fuzzy.get(key) ?? /* @__PURE__ */ new Set();
|
|
1014
|
+
set.add(entry.term);
|
|
1015
|
+
fuzzy.set(key, set);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
for (const source of v.terms) {
|
|
1019
|
+
const term = /\p{N}|[@$₹€£]|:\/\//u.test(source.term) ? { ...source, protected: true } : source;
|
|
1020
|
+
add(term.term, { term, kind: "canonical" });
|
|
1021
|
+
for (const a of term.aliases ?? []) add(a, { term, kind: "alias" });
|
|
1022
|
+
for (const [language, forms] of Object.entries(term.regional ?? {}))
|
|
1023
|
+
for (const f of forms) add(f, { term, kind: "regional", language });
|
|
1024
|
+
}
|
|
1025
|
+
for (const term of v.terms)
|
|
1026
|
+
if (term.protected || /\p{N}|[@$₹€£]|:\/\//u.test(term.term)) {
|
|
1027
|
+
for (const name of [
|
|
1028
|
+
term.term,
|
|
1029
|
+
...term.aliases ?? [],
|
|
1030
|
+
...Object.values(term.regional ?? {}).flat()
|
|
1031
|
+
])
|
|
1032
|
+
fuzzy.delete(fold(name));
|
|
1033
|
+
}
|
|
1034
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
1035
|
+
for (const form of fuzzy.keys())
|
|
1036
|
+
for (const key of deletionKeys(form, 2)) {
|
|
1037
|
+
const bucket = buckets.get(key);
|
|
1038
|
+
if (bucket) bucket.push(form);
|
|
1039
|
+
else buckets.set(key, [form]);
|
|
1040
|
+
}
|
|
1041
|
+
return { root, fuzzy, buckets };
|
|
1042
|
+
}
|
|
1043
|
+
var indexes = /* @__PURE__ */ new WeakMap();
|
|
1044
|
+
function indexFor(v) {
|
|
1045
|
+
let i = indexes.get(v);
|
|
1046
|
+
if (!i) {
|
|
1047
|
+
i = build(v);
|
|
1048
|
+
indexes.set(v, i);
|
|
1049
|
+
}
|
|
1050
|
+
return i;
|
|
1051
|
+
}
|
|
1052
|
+
function distance(a, b, limit) {
|
|
1053
|
+
if (Math.abs(a.length - b.length) > limit) return limit + 1;
|
|
1054
|
+
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
1055
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1056
|
+
const row = [i];
|
|
1057
|
+
let best = i;
|
|
1058
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1059
|
+
const cost = Math.min(
|
|
1060
|
+
(prev[j] ?? 0) + 1,
|
|
1061
|
+
(row[j - 1] ?? 0) + 1,
|
|
1062
|
+
(prev[j - 1] ?? 0) + Number(a[i - 1] !== b[j - 1])
|
|
1063
|
+
);
|
|
1064
|
+
row.push(cost);
|
|
1065
|
+
best = Math.min(best, cost);
|
|
1066
|
+
}
|
|
1067
|
+
if (best > limit) return limit + 1;
|
|
1068
|
+
prev = row;
|
|
1069
|
+
}
|
|
1070
|
+
return prev[b.length] ?? limit + 1;
|
|
1071
|
+
}
|
|
1072
|
+
function nearest(word, index) {
|
|
1073
|
+
let best = word.length < 9 ? 1 : 2;
|
|
1074
|
+
const hits = /* @__PURE__ */ new Set();
|
|
1075
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
1076
|
+
for (const key of deletionKeys(word, best))
|
|
1077
|
+
for (const form of index.buckets.get(key) ?? []) candidates.add(form);
|
|
1078
|
+
for (const form of candidates) {
|
|
1079
|
+
const terms = index.fuzzy.get(form) ?? [];
|
|
1080
|
+
const d = distance(word, form, best);
|
|
1081
|
+
if (d > best) continue;
|
|
1082
|
+
if (d < best) {
|
|
1083
|
+
best = d;
|
|
1084
|
+
hits.clear();
|
|
1085
|
+
}
|
|
1086
|
+
for (const t of terms) hits.add(t.term);
|
|
1087
|
+
}
|
|
1088
|
+
const result = [...hits].sort();
|
|
1089
|
+
return result;
|
|
1090
|
+
}
|
|
1091
|
+
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;
|
|
1092
|
+
function correctWithVocabulary(text, vocab, options = {}) {
|
|
1093
|
+
const index = indexFor(vocab), tokens = Array.from(text.matchAll(lex));
|
|
1094
|
+
const changes = [], ambiguous = [];
|
|
1095
|
+
const blocked = new Uint8Array(tokens.length);
|
|
1096
|
+
let pos = 0;
|
|
1097
|
+
const spans = Array.from(text.matchAll(protectedPattern));
|
|
1098
|
+
for (const m of text.matchAll(/\S+/gu)) {
|
|
1099
|
+
if (/\p{N}/u.test(m[0])) spans.push(m);
|
|
1100
|
+
else if (/^(?:[\p{L}\p{N}-]+\.)+[\p{L}]{2,}(?:[/?#]\S*)?$/iu.test(m[0])) spans.push(m);
|
|
1101
|
+
else if (m[0].includes("@") && /^[^@]+@[^@]+\.[^@]+$/u.test(m[0])) spans.push(m);
|
|
1102
|
+
}
|
|
1103
|
+
spans.sort((a, b) => a.index - b.index);
|
|
1104
|
+
for (const m of spans) {
|
|
1105
|
+
while (pos < tokens.length && (tokens[pos]?.index ?? 0) + (tokens[pos]?.[0].length ?? 0) <= m.index)
|
|
1106
|
+
pos++;
|
|
1107
|
+
while (pos < tokens.length && (tokens[pos]?.index ?? Infinity) < m.index + m[0].length)
|
|
1108
|
+
blocked[pos++] = 1;
|
|
1109
|
+
}
|
|
1110
|
+
const keys = tokens.map((m) => fold(m[0]));
|
|
1111
|
+
function matches(i) {
|
|
1112
|
+
const list = [];
|
|
1113
|
+
let n = index.root;
|
|
1114
|
+
for (let j = i; j < keys.length; j++) {
|
|
1115
|
+
n = n.next.get(keys[j] ?? "");
|
|
1116
|
+
if (!n) break;
|
|
1117
|
+
if (n.entries.length) list.push({ end: j + 1, entries: n.entries });
|
|
1118
|
+
}
|
|
1119
|
+
return list;
|
|
1120
|
+
}
|
|
1121
|
+
for (let i = 0; i < keys.length; i++) {
|
|
1122
|
+
if (/\p{N}/u.test(keys[i] ?? "")) blocked[i] = 1;
|
|
1123
|
+
for (const m of matches(i))
|
|
1124
|
+
if (m.entries.some((e) => e.term.protected)) blocked.fill(1, i, m.end);
|
|
1125
|
+
}
|
|
1126
|
+
let result = "", cursor = 0;
|
|
1127
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
1128
|
+
const first = tokens[i];
|
|
1129
|
+
if (!first || blocked[i]) continue;
|
|
1130
|
+
let end = i + 1, kind = "fuzzy", names = [];
|
|
1131
|
+
let exact = false;
|
|
1132
|
+
const matchesHere = matches(i).reverse().filter((m) => !blocked.subarray(i, m.end).includes(1));
|
|
1133
|
+
for (const regional of [false, true]) {
|
|
1134
|
+
if (regional && options.regionalToCanonical === false) break;
|
|
1135
|
+
for (const match of matchesHere) {
|
|
1136
|
+
const forms = match.entries.filter((e) => e.kind === "regional" === regional);
|
|
1137
|
+
if (!forms.length) continue;
|
|
1138
|
+
end = match.end;
|
|
1139
|
+
exact = true;
|
|
1140
|
+
kind = regional ? "regional" : "alias";
|
|
1141
|
+
names = [...new Set(forms.map((e) => e.term.term))].sort();
|
|
1142
|
+
if (names.length === 1 && forms.some((e) => e.kind === "canonical")) names = [];
|
|
1143
|
+
break;
|
|
1144
|
+
}
|
|
1145
|
+
if (exact) break;
|
|
1146
|
+
}
|
|
1147
|
+
if (!exact && options.fuzzy !== false && latin.test(keys[i] ?? ""))
|
|
1148
|
+
names = nearest(keys[i] ?? "", index);
|
|
1149
|
+
const last = tokens[end - 1] ?? first;
|
|
1150
|
+
const finish = last.index + last[0].length;
|
|
1151
|
+
const span = text.slice(first.index, finish);
|
|
1152
|
+
if (names.length > 1) ambiguous.push({ span, candidates: names });
|
|
1153
|
+
else if (names[0] && names[0] !== span) {
|
|
1154
|
+
result += text.slice(cursor, first.index) + names[0];
|
|
1155
|
+
cursor = finish;
|
|
1156
|
+
changes.push({ from: span, to: names[0], term: names[0], kind });
|
|
1157
|
+
}
|
|
1158
|
+
i = end - 1;
|
|
1159
|
+
}
|
|
1160
|
+
return { raw: text, text: result + text.slice(cursor), changes, ambiguous };
|
|
1161
|
+
}
|
|
1162
|
+
function ranked(v) {
|
|
1163
|
+
return [...v.terms].sort((a, b) => (b.weight ?? 1) - (a.weight ?? 1));
|
|
1164
|
+
}
|
|
1165
|
+
function vocabularyHints(v, max = 50) {
|
|
1166
|
+
return [...new Set(ranked(v).map((t) => t.term))].slice(0, Math.max(0, max));
|
|
1167
|
+
}
|
|
1168
|
+
function sttPromptFromVocabulary(v, options = {}) {
|
|
1169
|
+
let result = "";
|
|
1170
|
+
for (const t of ranked(v)) {
|
|
1171
|
+
const forms = [
|
|
1172
|
+
t.term,
|
|
1173
|
+
...t.pronunciations ?? [],
|
|
1174
|
+
...t.regional?.[baseLanguage(options.language ?? "")] ?? []
|
|
1175
|
+
];
|
|
1176
|
+
for (const form of forms) {
|
|
1177
|
+
const next = [result, form].filter(Boolean).join(", ");
|
|
1178
|
+
if (next.length <= (options.maxChars ?? 224)) result = next;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return result;
|
|
1182
|
+
}
|
|
1183
|
+
function autoVocabulary(input) {
|
|
1184
|
+
return {
|
|
1185
|
+
terms: [...input.routes ?? []].map((r) => ({ term: r.title, weight: 0 })).concat((input.tools ?? []).map((t) => ({ term: t.title ?? t.name, weight: 0 })))
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
function freeze(v) {
|
|
1189
|
+
if (v && typeof v === "object") {
|
|
1190
|
+
for (const child of Object.values(v)) freeze(child);
|
|
1191
|
+
Object.freeze(v);
|
|
1192
|
+
}
|
|
1193
|
+
return v;
|
|
1194
|
+
}
|
|
1195
|
+
function defineVocabulary(v) {
|
|
1196
|
+
const term = zod.z.string().trim().min(1), forms = zod.z.array(term).optional();
|
|
1197
|
+
const parsed = zod.z.object({
|
|
1198
|
+
terms: zod.z.array(
|
|
1199
|
+
zod.z.object({
|
|
1200
|
+
term,
|
|
1201
|
+
aliases: forms,
|
|
1202
|
+
pronunciations: forms,
|
|
1203
|
+
regional: zod.z.record(zod.z.string(), zod.z.array(term)).optional(),
|
|
1204
|
+
protected: zod.z.boolean().optional(),
|
|
1205
|
+
weight: zod.z.number().finite().optional()
|
|
1206
|
+
})
|
|
1207
|
+
)
|
|
1208
|
+
}).parse(v);
|
|
1209
|
+
const frozen = freeze(parsed);
|
|
1210
|
+
indexFor(frozen);
|
|
1211
|
+
return frozen;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
863
1214
|
exports.AssistantDeltaEventSchema = AssistantDeltaEventSchema;
|
|
864
1215
|
exports.AssistantMessageEventSchema = AssistantMessageEventSchema;
|
|
865
1216
|
exports.ClientConfigSchema = ClientConfigSchema;
|
|
@@ -902,6 +1253,7 @@ exports.SessionListResponseSchema = SessionListResponseSchema;
|
|
|
902
1253
|
exports.SessionSummarySchema = SessionSummarySchema;
|
|
903
1254
|
exports.SpeeqError = SpeeqError;
|
|
904
1255
|
exports.SseParser = SseParser;
|
|
1256
|
+
exports.SynthesizeRequestSchema = SynthesizeRequestSchema;
|
|
905
1257
|
exports.TELEMETRY_SCHEMA_VERSION = TELEMETRY_SCHEMA_VERSION;
|
|
906
1258
|
exports.TelemetryBatchSchema = TelemetryBatchSchema;
|
|
907
1259
|
exports.TelemetryEventSchema = TelemetryEventSchema;
|
|
@@ -909,6 +1261,8 @@ exports.TelemetryFeaturesSchema = TelemetryFeaturesSchema;
|
|
|
909
1261
|
exports.ToolFinishedEventSchema = ToolFinishedEventSchema;
|
|
910
1262
|
exports.ToolKindSchema = ToolKindSchema;
|
|
911
1263
|
exports.ToolStartedEventSchema = ToolStartedEventSchema;
|
|
1264
|
+
exports.TranscribeQuerySchema = TranscribeQuerySchema;
|
|
1265
|
+
exports.TranscribeResponseSchema = TranscribeResponseSchema;
|
|
912
1266
|
exports.TurnEndReasonSchema = TurnEndReasonSchema;
|
|
913
1267
|
exports.TurnFinishedEventSchema = TurnFinishedEventSchema;
|
|
914
1268
|
exports.TurnRequestSchema = TurnRequestSchema;
|
|
@@ -916,13 +1270,21 @@ exports.TurnStartedEventSchema = TurnStartedEventSchema;
|
|
|
916
1270
|
exports.TypedEmitter = TypedEmitter;
|
|
917
1271
|
exports.UsageRollupEventSchema = UsageRollupEventSchema;
|
|
918
1272
|
exports.UsageSchema = UsageSchema;
|
|
1273
|
+
exports.VoiceInfoSchema = VoiceInfoSchema;
|
|
1274
|
+
exports.VoicesResponseSchema = VoicesResponseSchema;
|
|
919
1275
|
exports.applyEventToSummary = applyEventToSummary;
|
|
1276
|
+
exports.autoVocabulary = autoVocabulary;
|
|
1277
|
+
exports.baseLanguage = baseLanguage;
|
|
920
1278
|
exports.combineSignals = combineSignals;
|
|
1279
|
+
exports.correctWithVocabulary = correctWithVocabulary;
|
|
921
1280
|
exports.createId = createId;
|
|
922
1281
|
exports.decodeCursor = decodeCursor;
|
|
1282
|
+
exports.defineVocabulary = defineVocabulary;
|
|
1283
|
+
exports.detectScripts = detectScripts;
|
|
923
1284
|
exports.emptySummary = emptySummary;
|
|
924
1285
|
exports.encodeCursor = encodeCursor;
|
|
925
1286
|
exports.encodeSse = encodeSse;
|
|
1287
|
+
exports.guessLanguageFromScript = guessLanguageFromScript;
|
|
926
1288
|
exports.isAbortError = isAbortError;
|
|
927
1289
|
exports.isAfterCursor = isAfterCursor;
|
|
928
1290
|
exports.isErrorCode = isErrorCode;
|
|
@@ -936,8 +1298,11 @@ exports.redactText = redactText;
|
|
|
936
1298
|
exports.safeJsonParse = safeJsonParse;
|
|
937
1299
|
exports.safeJsonStringify = safeJsonStringify;
|
|
938
1300
|
exports.sleep = sleep;
|
|
1301
|
+
exports.sttPromptFromVocabulary = sttPromptFromVocabulary;
|
|
1302
|
+
exports.toIso639_1 = toIso639_1;
|
|
939
1303
|
exports.toPublicError = toPublicError;
|
|
940
1304
|
exports.toSpeeqError = toSpeeqError;
|
|
941
1305
|
exports.truncate = truncate;
|
|
1306
|
+
exports.vocabularyHints = vocabularyHints;
|
|
942
1307
|
//# sourceMappingURL=index.cjs.map
|
|
943
1308
|
//# sourceMappingURL=index.cjs.map
|