@chatpanel/gateway 0.6.110 → 0.8.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.
Files changed (81) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +2 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/policy.js +2 -0
  47. package/src/prefs-store.js +1 -149
  48. package/src/project-store.js +1 -139
  49. package/src/project.js +1 -171
  50. package/src/recruit.js +3 -424
  51. package/src/recruiting.js +1 -93
  52. package/src/redact.js +2 -123
  53. package/src/responses.js +2 -80
  54. package/src/router.js +1 -292
  55. package/src/rrf.js +1 -93
  56. package/src/scorecard-store.js +1 -92
  57. package/src/scorecard.js +1 -336
  58. package/src/search-index.js +2 -134
  59. package/src/secure-fetch.js +1 -58
  60. package/src/sentencepiece.js +1 -184
  61. package/src/server.js +10 -2296
  62. package/src/service.js +11 -189
  63. package/src/shape.js +5 -121
  64. package/src/sqlite-store.js +3 -212
  65. package/src/stream.js +5 -182
  66. package/src/structured.js +4 -902
  67. package/src/stt-engine.js +1 -486
  68. package/src/stt-models.js +1 -144
  69. package/src/subject-kinds.js +1 -6
  70. package/src/subject-name.js +1 -97
  71. package/src/team-board.js +6 -338
  72. package/src/team-record.js +1 -226
  73. package/src/team-store.js +1 -261
  74. package/src/team.js +1 -303
  75. package/src/toolrelay.js +3 -122
  76. package/src/tts-engine.js +1 -453
  77. package/src/tts-models.js +1 -254
  78. package/src/tts-remote.js +1 -109
  79. package/src/tts-voice-resolve.js +1 -78
  80. package/src/tts-voices.js +1 -192
  81. package/src/update.js +1 -305
package/src/stt-engine.js CHANGED
@@ -1,486 +1 @@
1
- // In-process speech-to-text — whisper via transformers.js, zero native deps.
2
- //
3
- // Same design as ner-engine.js (and deliberately the same file shape): an ONNX
4
- // model run IN-PROCESS, downloaded once on first use into ~/.chatpanel/models,
5
- // fully offline afterwards — audio NEVER leaves the machine. This is what makes
6
- // dictation private: the extension streams mic PCM over loopback, we transcribe
7
- // locally, and only text goes back.
8
- //
9
- // Two layers:
10
- // engine — load/switch the whisper pipeline (mirrors ner-engine verbatim)
11
- // sessions — rolling-buffer streaming decode: interim results every ~1.2s,
12
- // finals on trailing silence or when a segment grows too long.
13
- // Whisper isn't natively streaming, so we re-decode the open
14
- // segment and commit it when the speaker pauses.
15
- //
16
- // Fail-open by design: if the model can't load, sessions emit one error event
17
- // and dictation falls back to the browser engine client-side.
18
-
19
- import { join } from 'node:path';
20
- import { existsSync, readdirSync } from 'node:fs';
21
- import { randomUUID } from 'node:crypto';
22
- import { ensureLib, modelRoot } from './ner-engine.js';
23
- import { runtimeDtype, runtimeName, DTYPE_SUFFIX } from './model-runtime.js';
24
- import { verifyModelWeights } from './model-integrity.js';
25
- import { DEFAULT_STT_MODEL, isEnglishOnly, sttModelDtype, isKnownSttModel, sttModelEngine } from './stt-models.js';
26
- import * as parakeet from './parakeet-engine.js';
27
- import * as diarize from './diarize-engine.js';
28
-
29
- export const SAMPLE_RATE = 16000; // fixed wire contract: 16 kHz mono Float32 PCM
30
-
31
- // runtimeDtype / runtimeName moved to model-runtime.js — the WASM binary's fp32-only
32
- // constraint is a property of the runtime, and tts-engine needs the same answer.
33
- // Re-exported here so this module's public API is unchanged for existing callers.
34
- export { runtimeDtype, runtimeName };
35
-
36
- let _state = 'off'; // 'off' | 'loading' | 'downloading' | 'ready' | 'error'
37
- let _model = null; // active model id
38
- let _pipe = null; // the loaded automatic-speech-recognition pipeline
39
- let _err = null; // last error message (for /health)
40
- let _initPromise = null; // single-flight init
41
- let _progress = null; // { model, file, pct } while downloading, else null
42
- let _dtype = null; // the quantization actually loaded (fp32 on WASM, q8 native)
43
-
44
- export function modelOnDisk(modelId = _model || DEFAULT_STT_MODEL, dtype = sttModelDtype(modelId) || runtimeDtype()) {
45
- // Transducer models (parakeet) have a different file layout + engine — delegate.
46
- if (sttModelEngine(modelId) === 'parakeet-tdt') return parakeet.parakeetOnDisk(modelId, parakeet.parakeetDtype(dtype));
47
- const dir = join(modelRoot(), ...modelId.split('/'), 'onnx');
48
- if (!existsSync(dir)) return false;
49
- const suffix = DTYPE_SUFFIX[dtype] ?? '';
50
- try {
51
- const files = readdirSync(dir);
52
- return files.includes(`encoder_model${suffix}.onnx`)
53
- && files.some((f) => f === `decoder_model_merged${suffix}.onnx` || f === `decoder_model${suffix}.onnx`);
54
- } catch { return false; }
55
- }
56
-
57
- export function state() { return _state; }
58
- export function isReady() { return _state === 'ready' && !!_pipe; }
59
- export function progress() { return _progress; }
60
-
61
- export function health() {
62
- return { configured: _state !== 'off', ok: isReady(), state: _state, model: _model, dtype: _dtype, runtime: runtimeName(), error: _err };
63
- }
64
-
65
- // (Re)load a model into _pipe. Same contract as ner-engine.loadModel: fail-open,
66
- // and a failed SWITCH keeps the previous working pipeline.
67
- /** @param {string} modelId @param {{ log?: (m: string) => void, allowDownload?: boolean, dtype?: string }} [opts] */
68
- async function loadModel(modelId, { log = () => {}, allowDownload = true, dtype: dtypeOverride = null } = {}) {
69
- // Transducer models aren't whisper pipelines — hand off to the parakeet engine.
70
- if (sttModelEngine(modelId) === 'parakeet-tdt') return loadParakeet(modelId, { log, allowDownload, dtype: dtypeOverride });
71
-
72
- const prevPipe = _pipe;
73
- const prevModel = _model;
74
- let lib;
75
- try {
76
- lib = await ensureLib();
77
- } catch (e) {
78
- _state = 'error'; _err = `engine load failed: ${e.message}`;
79
- log(`[stt] transformers.js not available (${e.message}) — dictation falls back to the browser engine`);
80
- return false;
81
- }
82
-
83
- // Resolve the precision up front so the on-disk check targets the RIGHT files —
84
- // else switching precision (e.g. q8→fp16) would see the q8 files as "present" and
85
- // try to load fp16 offline, which fails.
86
- const chosen = dtypeOverride && dtypeOverride !== 'auto' ? dtypeOverride : null;
87
- const dtype = chosen || sttModelDtype(modelId) || runtimeDtype();
88
-
89
- const haveLocal = modelOnDisk(modelId, dtype);
90
- lib.env.allowRemoteModels = haveLocal ? false : !!allowDownload;
91
- if (!haveLocal && !allowDownload) {
92
- _state = 'error'; _err = 'model not on disk and downloads disabled';
93
- log(`[stt] model ${modelId} not installed and downloads disabled`);
94
- return false;
95
- }
96
-
97
- // Curated catalog models come from the private dl.chatpanel.net mirror (ensureLib
98
- // already set that as remoteHost). A CUSTOM ("Advanced") id isn't mirrored, so
99
- // fetch it from Hugging Face directly — only for this load, then restore.
100
- const prevHost = lib.env.remoteHost;
101
- const isCustom = !isKnownSttModel(modelId);
102
- if (!haveLocal && isCustom) { try { lib.env.remoteHost = 'https://huggingface.co/'; } catch { /* optional */ } }
103
-
104
- _state = haveLocal ? 'loading' : 'downloading';
105
- if (!haveLocal) { _progress = { model: modelId, file: null, pct: 0 }; log(`[stt] downloading model ${modelId} (one-time${isCustom ? ', from Hugging Face' : ''})…`); }
106
-
107
- try {
108
- const progress_callback = (p) => {
109
- if (!p) return;
110
- const pct = typeof p.progress === 'number' ? Math.round(p.progress) : (_progress?.pct ?? 0);
111
- if (p.status === 'progress' || p.status === 'download' || p.status === 'initiate') {
112
- _progress = { model: modelId, file: p.file || _progress?.file || null, pct };
113
- } else if (p.status === 'done' && p.file) {
114
- log(`[stt] fetched ${p.file}`);
115
- }
116
- };
117
- let pipe;
118
- try {
119
- pipe = await lib.pipeline('automatic-speech-recognition', modelId, { dtype, progress_callback });
120
- } catch (e) {
121
- // The dl.chatpanel.net mirror only proxies an allowlist; a catalog model
122
- // missing from it (or any mirror hiccup) 403s. Fall back to Hugging Face so
123
- // a download is never blocked by a mirror gap. (Custom ids already use HF.)
124
- if (haveLocal || isCustom || !allowDownload) throw e;
125
- log(`[stt] mirror fetch failed (${String(e.message).slice(0, 80)}) — retrying from Hugging Face…`);
126
- lib.env.remoteHost = 'https://huggingface.co/';
127
- lib.env.allowRemoteModels = true;
128
- pipe = await lib.pipeline('automatic-speech-recognition', modelId, { dtype, progress_callback });
129
- }
130
- // H3: verify freshly-downloaded weights (fail-closed on a real mismatch;
131
- // warn-and-allow when unlisted). Post-load — see model-integrity.js note.
132
- if (!haveLocal) {
133
- try {
134
- verifyModelWeights(modelId, { modelsDir: modelRoot(), log });
135
- } catch (e) {
136
- try { await pipe.dispose?.(); } catch { /* ignore */ }
137
- throw e;
138
- }
139
- }
140
- _pipe = pipe; _model = modelId; _state = 'ready'; _err = null; _progress = null; _dtype = dtype;
141
- if (prevPipe && prevPipe !== pipe) { try { await prevPipe.dispose?.(); } catch { /* ignore */ } }
142
- log(`[stt] ready — model ${modelId} @ ${dtype} (in-process, offline) — local dictation active`);
143
- return true;
144
- } catch (e) {
145
- _err = e.message; _progress = null;
146
- if (prevPipe) { _pipe = prevPipe; _model = prevModel; _state = 'ready'; }
147
- else { _state = 'error'; }
148
- log(`[stt] model load failed (${e.message})${prevPipe ? ' — keeping previous model' : ''}`);
149
- return false;
150
- } finally {
151
- try { lib.env.remoteHost = prevHost; } catch { /* optional */ } // restore the mirror for NER + catalog loads
152
- }
153
- }
154
-
155
- // Load a Parakeet TDT (transducer) model via parakeet-engine.js (raw onnxruntime), and
156
- // expose it to the session layer as a whisper-shaped `_pipe(audio) → { text }` adapter,
157
- // so decodeSession/streaming/redaction/diarization all work unchanged. Fail-open and
158
- // keep-previous-on-switch-failure, exactly like the whisper path above.
159
- /** @param {string} modelId @param {{ log?: (m: string) => void, allowDownload?: boolean, dtype?: string|null }} [opts] */
160
- async function loadParakeet(modelId, { log = () => {}, allowDownload = true, dtype: dtypeOverride = null } = {}) {
161
- const prevPipe = _pipe;
162
- const prevModel = _model;
163
- const dtype = parakeet.parakeetDtype(dtypeOverride && dtypeOverride !== 'auto' ? dtypeOverride : PARAKEET_RUNTIME_DTYPE());
164
- const haveLocal = parakeet.parakeetOnDisk(modelId, dtype);
165
- if (!haveLocal && !allowDownload) {
166
- _state = 'error'; _err = 'model not on disk and downloads disabled';
167
- log(`[stt] model ${modelId} not installed and downloads disabled`);
168
- return false;
169
- }
170
- _state = haveLocal ? 'loading' : 'downloading';
171
- if (!haveLocal) { _progress = { model: modelId, file: null, pct: 0 }; log(`[stt] downloading model ${modelId} (one-time, from Hugging Face)…`); }
172
- try {
173
- const rec = await parakeet.loadRecognizer({
174
- modelId, dtype, allowDownload, log,
175
- onProgress: (p) => { _progress = { model: modelId, file: p.file || null, pct: typeof p.pct === 'number' ? p.pct : (_progress?.pct ?? 0) }; },
176
- });
177
- // whisper-shaped adapter: ignores the whisper `{ language, task }` opts (parakeet
178
- // auto-detects language) and returns { text }. `__parakeet` flags the language-ID
179
- // short-circuit; `dispose` frees the ORT sessions on switch.
180
- const adapter = async (audio) => ({ text: await rec.transcribe(audio) });
181
- adapter.__parakeet = true;
182
- adapter.dispose = () => rec.dispose();
183
- _pipe = adapter; _model = modelId; _state = 'ready'; _err = null; _progress = null; _dtype = dtype;
184
- if (prevPipe && prevPipe !== adapter) { try { await prevPipe.dispose?.(); } catch { /* ignore */ } }
185
- log(`[stt] ready — model ${modelId} @ ${dtype} (parakeet-tdt, in-process, offline) — local dictation active`);
186
- return true;
187
- } catch (e) {
188
- _err = e.message; _progress = null;
189
- if (prevPipe) { _pipe = prevPipe; _model = prevModel; _state = 'ready'; }
190
- else { _state = 'error'; }
191
- log(`[stt] model load failed (${e.message})${prevPipe ? ' — keeping previous model' : ''}`);
192
- return false;
193
- }
194
- }
195
-
196
- // Parakeet only ships int8 + fp32 exports (no whisper-style q8). int8 loads and runs on
197
- // BOTH runtimes; only force fp32 if a caller explicitly asks. Independent of the whisper
198
- // runtimeDtype (which returns q8/fp32).
199
- function PARAKEET_RUNTIME_DTYPE() { return parakeet.PARAKEET_DEFAULT_DTYPE; }
200
-
201
- // Load the configured model once, on FIRST USE (never at gateway startup — the
202
- // download is deferred until someone actually dictates). Single-flight.
203
- export function init(cfg = {}) {
204
- if (_initPromise) return _initPromise;
205
- const log = typeof cfg.onLog === 'function' ? cfg.onLog : () => {};
206
- _model = cfg.model || DEFAULT_STT_MODEL;
207
- _state = 'loading';
208
- _initPromise = loadModel(_model, { log, allowDownload: cfg.allowDownload !== false, dtype: cfg.dtype });
209
- return _initPromise;
210
- }
211
-
212
- export async function setModel(modelId, opts = {}) {
213
- const log = typeof opts.onLog === 'function' ? opts.onLog : () => {};
214
- if (!modelId) return false;
215
- // Re-load if the model OR the requested precision changed. Parakeet has its own
216
- // dtype domain (int8/fp32), independent of whisper's q8/fp32 runtimeDtype.
217
- const wantDtype = sttModelEngine(modelId) === 'parakeet-tdt'
218
- ? parakeet.parakeetDtype(opts.dtype && opts.dtype !== 'auto' ? opts.dtype : parakeet.PARAKEET_DEFAULT_DTYPE)
219
- : (opts.dtype && opts.dtype !== 'auto' ? opts.dtype : (sttModelDtype(modelId) || runtimeDtype()));
220
- if (modelId === _model && isReady() && _dtype === wantDtype) return true;
221
- return loadModel(modelId, { log, allowDownload: opts.allowDownload !== false, dtype: opts.dtype });
222
- }
223
-
224
- // ── Streaming sessions ──────────────────────────────────────────────────────────
225
-
226
- const MAX_SESSIONS = 4;
227
- const IDLE_MS = 60_000; // no audio for a minute → session expires
228
- const DECODE_GAP_MS = 1200; // min spacing between decodes of one session
229
- const MAX_SEGMENT_S = 12; // force-finalize an open segment past this
230
- const SILENCE_FINAL_MS = 700; // trailing quiet that commits a segment
231
- const SILENCE_RMS = 0.008; // "quiet" threshold on Float32 PCM
232
- const MAX_BUFFER_S = 30; // hard cap on the open segment (whisper ctx)
233
-
234
- const _sessions = new Map();
235
- let _decodeChain = Promise.resolve(); // whisper is effectively single-threaded —
236
- // serialize decodes across ALL sessions
237
-
238
- export function sessionCount() { return _sessions.size; }
239
-
240
- /** @param {{ lang?: string, redact?: boolean, diarize?: boolean, speakerLabel?: string }} [opts] */
241
- // How long a pause commits a segment. The default suits dictation into a text box,
242
- // where a final just appends and a short pause costs nothing. In a VOICE
243
- // conversation every final is SENT as a question, so a 700ms pause mid-thought
244
- // ("I want to… um… go to Google") sends half a sentence. Callers may ask for more.
245
- const END_SILENCE_MIN_MS = 300;
246
- const END_SILENCE_MAX_MS = 3000;
247
- export function clampEndSilence(ms) {
248
- const n = Number(ms);
249
- if (!Number.isFinite(n)) return SILENCE_FINAL_MS;
250
- return Math.min(END_SILENCE_MAX_MS, Math.max(END_SILENCE_MIN_MS, Math.round(n)));
251
- }
252
-
253
- export function createSession({ lang, redact = false, diarize: diarizeOpt = false, speakerLabel = null, endSilenceMs = SILENCE_FINAL_MS } = {}) {
254
- if (_sessions.size >= MAX_SESSIONS) {
255
- const e = /** @type {Error & { code?: string }} */ (new Error('too many concurrent dictation sessions'));
256
- e.code = 'too_many_sessions'; throw e;
257
- }
258
- const s = {
259
- id: randomUUID(),
260
- endSilenceMs: clampEndSilence(endSilenceMs),
261
- lang: typeof lang === 'string' && lang ? lang.slice(0, 12) : null,
262
- langTried: false, // language auto-detect runs once per session (multilingual models)
263
- // Opaque to this engine: the server applies the redaction hop to finals when
264
- // set. Pipeline stages stay independent — STT never imports NER.
265
- redact: !!redact,
266
- // Diarization is opt-in. A per-session Diarizer clusters final segments into
267
- // speakers; `speakerLabel` pins every final to one label (the mic channel =
268
- // "You" in a meeting), so clustering only ever splits the other channels.
269
- diarize: !!diarizeOpt,
270
- speakerLabel: typeof speakerLabel === 'string' && speakerLabel ? speakerLabel.slice(0, 40) : null,
271
- diarizer: diarizeOpt ? new diarize.Diarizer() : null,
272
- chunks: [], // Float32Array pieces of the OPEN (unfinalized) segment
273
- samples: 0,
274
- listeners: new Set(), // (event) => void — the SSE writers
275
- lastDecodeAt: 0,
276
- decodeTimer: null,
277
- lastInterim: '',
278
- closed: false,
279
- idleTimer: null,
280
- };
281
- _sessions.set(s.id, s);
282
- touch(s);
283
- return { id: s.id };
284
- }
285
-
286
- export function getSession(id) { return _sessions.get(String(id || '')) || null; }
287
-
288
- export function subscribe(id, fn) {
289
- const s = getSession(id);
290
- if (!s) return null;
291
- s.listeners.add(fn);
292
- return () => s.listeners.delete(fn);
293
- }
294
-
295
- function emit(s, ev) {
296
- for (const fn of s.listeners) { try { fn(ev); } catch { /* listener's problem */ } }
297
- }
298
-
299
- function touch(s) {
300
- if (s.idleTimer) clearTimeout(s.idleTimer);
301
- s.idleTimer = setTimeout(() => endSession(s.id).catch(() => {}), IDLE_MS);
302
- s.idleTimer.unref?.();
303
- }
304
-
305
- // Accept a chunk of 16 kHz mono Float32 PCM and schedule a decode.
306
- export function pushAudio(id, float32) {
307
- const s = getSession(id);
308
- if (!s || s.closed) {
309
- const e = /** @type {Error & { code?: string }} */ (new Error('no such session'));
310
- e.code = 'no_session'; throw e;
311
- }
312
- if (!(float32 instanceof Float32Array) || !float32.length) return;
313
- s.chunks.push(float32);
314
- s.samples += float32.length;
315
- touch(s);
316
- scheduleDecode(s);
317
- }
318
-
319
- // HTTP bodies arrive as Buffers whose byteOffset may not be 4-aligned — copy.
320
- export function toFloat32(buf) {
321
- const bytes = buf.length - (buf.length % 4);
322
- const out = new Float32Array(bytes / 4);
323
- for (let i = 0; i < out.length; i++) out[i] = buf.readFloatLE(i * 4);
324
- return out;
325
- }
326
-
327
- function scheduleDecode(s) {
328
- if (s.closed || s.decodeTimer) return;
329
- const wait = Math.max(0, s.lastDecodeAt + DECODE_GAP_MS - Date.now());
330
- s.decodeTimer = setTimeout(() => {
331
- s.decodeTimer = null;
332
- _decodeChain = _decodeChain.then(() => decodeSession(s).catch(() => {}));
333
- }, wait);
334
- s.decodeTimer.unref?.();
335
- }
336
-
337
- function concatBuffer(s) {
338
- const out = new Float32Array(s.samples);
339
- let o = 0;
340
- for (const c of s.chunks) { out.set(c, o); o += c.length; }
341
- return out;
342
- }
343
-
344
- function rms(audio, from = 0, to = audio.length) {
345
- let sum = 0;
346
- const n = Math.max(1, to - from);
347
- for (let i = from; i < to; i++) sum += audio[i] * audio[i];
348
- return Math.sqrt(sum / n);
349
- }
350
-
351
- // Trim leading/trailing near-silence so a speaker embedding is computed on VOICE,
352
- // not room tone — otherwise the silence dominates and distinct speakers' vectors
353
- // converge (they'd all cluster as one). Window-scan at 20 ms granularity.
354
- function voicedRegion(audio) {
355
- const w = Math.round(0.02 * SAMPLE_RATE);
356
- let start = 0, end = audio.length;
357
- for (let i = 0; i + w <= audio.length; i += w) { if (rms(audio, i, i + w) >= SILENCE_RMS) { start = i; break; } }
358
- for (let i = audio.length - w; i >= 0; i -= w) { if (rms(audio, i, i + w) >= SILENCE_RMS) { end = i + w; break; } }
359
- return end > start ? audio.subarray(start, end) : audio;
360
- }
361
-
362
- // Whisper's native language-ID, which transformers.js doesn't implement (its
363
- // pipeline just defaults to English): one decoder step from <|startoftranscript|>,
364
- // argmax over the 99 language tokens. Run ONCE per session on the first voiced
365
- // segment, then pinned — so "speak any language, it just works" without a setting.
366
- async function detectLanguage(audio) {
367
- try {
368
- const lib = await ensureLib();
369
- const gc = _pipe?.model?.generation_config;
370
- if (!gc?.lang_to_id || !gc.decoder_start_token_id || !lib.Tensor) return null; // english-only model (or exotic export)
371
- const clip = audio.length > SAMPLE_RATE * 8 ? audio.subarray(0, SAMPLE_RATE * 8) : audio;
372
- const feats = await _pipe.processor(clip);
373
- const decoder_input_ids = new lib.Tensor('int64', new BigInt64Array([BigInt(gc.decoder_start_token_id)]), [1, 1]);
374
- const out = await _pipe.model({ ...feats, decoder_input_ids });
375
- let best = null, bestVal = -Infinity;
376
- for (const [tok, id] of Object.entries(gc.lang_to_id)) {
377
- const v = Number(out.logits.data[id]);
378
- if (v > bestVal) { bestVal = v; best = tok; }
379
- }
380
- return best ? best.slice(2, -2) : null; // '<|fr|>' → 'fr'
381
- } catch { return null; } // fail-open: whisper's English default still transcribes
382
- }
383
-
384
- async function decodeSession(s, { flush = false } = {}) {
385
- if (s.closed && !flush) return;
386
- if (!isReady() || !s.samples) return;
387
- s.lastDecodeAt = Date.now();
388
-
389
- const audio = concatBuffer(s);
390
- const tail = Math.round(((s.endSilenceMs || SILENCE_FINAL_MS) / 1000) * SAMPLE_RATE);
391
- const trailingQuiet = audio.length > tail && rms(audio, audio.length - tail) < SILENCE_RMS;
392
-
393
- // Nothing but room tone? Don't decode (whisper hallucinates on silence) and
394
- // don't let the buffer grow unbounded — keep only the last second.
395
- if (rms(audio) < SILENCE_RMS) {
396
- if (audio.length > SAMPLE_RATE * 5) {
397
- s.chunks = [audio.subarray(audio.length - SAMPLE_RATE)];
398
- s.samples = SAMPLE_RATE;
399
- }
400
- return;
401
- }
402
-
403
- // Auto-detect the spoken language on the session's first voiced audio (≥1s),
404
- // then pin it. An explicit client `lang` wins; `.en` models skip all of this.
405
- if (!s.lang && !s.langTried && !isEnglishOnly(_model) && !_pipe?.__parakeet && audio.length >= SAMPLE_RATE) {
406
- s.langTried = true;
407
- const detected = await detectLanguage(audio);
408
- if (detected) { s.lang = detected; emit(s, { type: 'language', lang: detected }); }
409
- }
410
-
411
- let text = '';
412
- try {
413
- const opts = isEnglishOnly(_model) ? {} : { language: s.lang || undefined, task: 'transcribe' };
414
- const out = await _pipe(audio, opts);
415
- text = String(out?.text || '').trim();
416
- } catch (e) {
417
- emit(s, { type: 'error', code: 'decode_failed', message: e.message, fatal: false });
418
- return;
419
- }
420
- if (!text) return;
421
-
422
- const tooLong = audio.length >= MAX_SEGMENT_S * SAMPLE_RATE;
423
- const overflow = audio.length >= MAX_BUFFER_S * SAMPLE_RATE;
424
- if (flush || trailingQuiet || tooLong || overflow) {
425
- // WHY THIS SEGMENT WAS COMMITTED — and it is not always because the speaker finished.
426
- //
427
- // Four situations produced an identical `final`, and a client could not tell them apart:
428
- // the session ending and a trailing pause are the end of a TURN; the length and buffer
429
- // caps are this engine cutting a segment it cannot hold any longer, mid-sentence, while
430
- // the speaker is still going. In dictation the difference does not matter — either way
431
- // the text is appended. In a voice CONVERSATION every final is SENT, so a long sentence
432
- // was cut at twelve seconds and half of it asked as a question:
433
- // "…you should just continuously listen to it and then" → sent, answered, lost.
434
- // Both fields are ADDITIVE: an older client ignores them and behaves exactly as before.
435
- const reason = flush ? 'flush' : trailingQuiet ? 'silence' : overflow ? 'overflow' : 'length';
436
- const endOfTurn = reason === 'flush' || reason === 'silence';
437
- // Commit: the open segment becomes a final; the buffer restarts empty.
438
- s.chunks = []; s.samples = 0; s.lastInterim = '';
439
- // Diarize this committed segment (opt-in): embed its audio, cluster → speaker.
440
- // A pinned label (mic = "You") skips clustering. Best-effort; never blocks text.
441
- let speaker = null;
442
- if (s.diarizer) {
443
- try {
444
- const vec = s.speakerLabel ? null : await diarize.embed(voicedRegion(audio));
445
- speaker = s.diarizer.assign(vec, { pinnedLabel: s.speakerLabel });
446
- } catch { /* diarization is additive — a failure never drops the transcript */ }
447
- }
448
- emit(s, { type: 'final', text, reason, endOfTurn, ...(speaker ? { speaker } : {}) });
449
- } else if (text !== s.lastInterim) {
450
- s.lastInterim = text;
451
- emit(s, { type: 'interim', text });
452
- }
453
- // More audio may have arrived while decoding — the next push reschedules.
454
- }
455
-
456
- // Stop a session: flush any remaining speech as a last final, notify, clean up.
457
- export async function endSession(id) {
458
- const s = getSession(id);
459
- if (!s || s.closed) return false;
460
- s.closed = true;
461
- if (s.idleTimer) clearTimeout(s.idleTimer);
462
- if (s.decodeTimer) { clearTimeout(s.decodeTimer); s.decodeTimer = null; }
463
- try {
464
- await (_decodeChain = _decodeChain.then(() => decodeSession(s, { flush: true }).catch(() => {})));
465
- } finally {
466
- emit(s, { type: 'end' });
467
- s.listeners.clear();
468
- _sessions.delete(s.id);
469
- }
470
- return true;
471
- }
472
-
473
- // Test hook: reset module state.
474
- export function _reset() {
475
- for (const s of _sessions.values()) {
476
- if (s.idleTimer) clearTimeout(s.idleTimer);
477
- if (s.decodeTimer) clearTimeout(s.decodeTimer);
478
- }
479
- _sessions.clear();
480
- _state = 'off'; _model = null; _pipe = null; _err = null; _initPromise = null; _progress = null;
481
- }
482
-
483
- // Test hook: inject a fake pipeline (so session logic is testable without a model).
484
- export function _setPipeForTest(pipe, model = 'test/fake') {
485
- _pipe = pipe; _model = model; _state = pipe ? 'ready' : 'off';
486
- }
1
+ import{join as O}from"node:path";import{existsSync as G,readdirSync as q}from"node:fs";import{randomUUID as Q}from"node:crypto";import{ensureLib as R,modelRoot as z}from"./ner-engine.js";import{runtimeDtype as x,runtimeName as C,DTYPE_SUFFIX as V}from"./model-runtime.js";import{verifyModelWeights as W}from"./model-integrity.js";import{DEFAULT_STT_MODEL as H,isEnglishOnly as U,sttModelDtype as v,isKnownSttModel as J,sttModelEngine as $}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as X from"./diarize-engine.js";const h=16e3;let c="off",f=null,d=null,y=null,M=null,m=null,D=null;function Z(e=f||H,t=v(e)||x()){if($(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=O(z(),...e.split("/"),"onnx");if(!G(n))return!1;const r=V[t]??"";try{const o=q(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(s=>s===`decoder_model_merged${r}.onnx`||s===`decoder_model${r}.onnx`)}catch{return!1}}function Ee(){return c}function F(){return c==="ready"&&!!d}function ke(){return m}function Me(){return{configured:c!=="off",ok:F(),state:c,model:f,dtype:D,runtime:C(),error:y}}async function B(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if($(e)==="parakeet-tdt")return I(e,{log:t,allowDownload:n,dtype:r});const o=d,s=f;let a;try{a=await R()}catch(w){return c="error",y=`engine load failed: ${w.message}`,t(`[stt] transformers.js not available (${w.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||v(e)||x(),l=Z(e,i);if(a.env.allowRemoteModels=l?!1:!!n,!l&&!n)return c="error",y="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=a.env.remoteHost,_=!J(e);if(!l&&_)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=l?"loading":"downloading",l||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${_?", from Hugging Face":""})…`));try{const w=u=>{if(!u)return;const j=typeof u.progress=="number"?Math.round(u.progress):m?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?m={model:e,file:u.file||m?.file||null,pct:j}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let k;try{k=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:w})}catch(u){if(l||_||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,k=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:w})}if(!l)try{W(e,{modelsDir:z(),log:t})}catch(u){try{await k.dispose?.()}catch{}throw u}if(d=k,f=e,c="ready",y=null,m=null,D=i,o&&o!==k)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(w){return y=w.message,m=null,o?(d=o,f=s,c="ready"):c="error",t(`[stt] model load failed (${w.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=p}catch{}}}async function I(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=d,s=f,a=T.parakeetDtype(r&&r!=="auto"?r:ee()),g=T.parakeetOnDisk(e,a);if(!g&&!n)return c="error",y="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=g?"loading":"downloading",g||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:a,allowDownload:n,log:t,onProgress:p=>{m={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:m?.pct??0}}}),l=async p=>({text:await i.transcribe(p)});if(l.__parakeet=!0,l.dispose=()=>i.dispose(),d=l,f=e,c="ready",y=null,m=null,D=a,o&&o!==l)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return y=i.message,m=null,o?(d=o,f=s,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function ee(){return T.PARAKEET_DEFAULT_DTYPE}function Se(e={}){if(M)return M;const t=typeof e.onLog=="function"?e.onLog:()=>{};return f=e.model||H,c="loading",M=B(f,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype}),M}async function xe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=$(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:v(e)||x();return e===f&&F()&&D===r?!0:B(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})}const te=4,ne=6e4,re=1200,oe=12,P=700,b=.008,ie=30,E=new Map;let A=Promise.resolve();function De(){return E.size}const se=300,ae=3e3;function le(e){const t=Number(e);return Number.isFinite(t)?Math.min(ae,Math.max(se,Math.round(t))):P}function be({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=P}={}){if(E.size>=te){const a=new Error("too many concurrent dictation sessions");throw a.code="too_many_sessions",a}const s={id:Q(),endSilenceMs:le(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new X.Diarizer:null,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return E.set(s.id,s),K(s),{id:s.id}}function N(e){return E.get(String(e||""))||null}function Ae(e,t){const n=N(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function S(e,t){for(const n of e.listeners)try{n(t)}catch{}}function K(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>pe(e.id).catch(()=>{}),ne),e.idleTimer.unref?.()}function Le(e,t){const n=N(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,K(n),ce(n))}function ve(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function ce(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+re-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,A=A.then(()=>Y(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ue(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function L(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let s=t;s<n;s++)r+=e[s]*e[s];return Math.sqrt(r/o)}function fe(e){const t=Math.round(.02*h);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(L(e,o,o+t)>=b){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(L(e,o,o+t)>=b){r=o+t;break}return r>n?e.subarray(n,r):e}async function de(e){try{const t=await R(),n=d?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await d.processor(r),s=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await d.model({...o,decoder_input_ids:s});let g=null,i=-1/0;for(const[l,p]of Object.entries(n.lang_to_id)){const _=Number(a.logits.data[p]);_>i&&(i=_,g=l)}return g?g.slice(2,-2):null}catch{return null}}async function Y(e,{flush:t=!1}={}){if(e.closed&&!t||!F()||!e.samples)return;e.lastDecodeAt=Date.now();const n=ue(e),r=Math.round((e.endSilenceMs||P)/1e3*h),o=n.length>r&&L(n,n.length-r)<b;if(L(n)<b){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.lang&&!e.langTried&&!U(f)&&!d?.__parakeet&&n.length>=h){e.langTried=!0;const i=await de(n);i&&(e.lang=i,S(e,{type:"language",lang:i}))}let s="";try{const i=U(f)?{}:{language:e.lang||void 0,task:"transcribe"},l=await d(n,i);s=String(l?.text||"").trim()}catch(i){S(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!s)return;const a=n.length>=oe*h,g=n.length>=ie*h;if(t||o||a||g){const i=t?"flush":o?"silence":g?"overflow":"length",l=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";let p=null;if(e.diarizer)try{const _=e.speakerLabel?null:await X.embed(fe(n));p=e.diarizer.assign(_,{pinnedLabel:e.speakerLabel})}catch{}S(e,{type:"final",text:s,reason:i,endOfTurn:l,...p?{speaker:p}:{}})}else s!==e.lastInterim&&(e.lastInterim=s,S(e,{type:"interim",text:s}))}async function pe(e){const t=N(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(A=A.then(()=>Y(t,{flush:!0}).catch(()=>{})))}finally{S(t,{type:"end"}),t.listeners.clear(),E.delete(t.id)}return!0}function $e(){for(const e of E.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);E.clear(),c="off",f=null,d=null,y=null,M=null,m=null}function Fe(e,t="test/fake"){d=e,f=t,c=e?"ready":"off"}export{h as SAMPLE_RATE,$e as _reset,Fe as _setPipeForTest,le as clampEndSilence,be as createSession,pe as endSession,N as getSession,Me as health,Se as init,F as isReady,Z as modelOnDisk,ke as progress,Le as pushAudio,x as runtimeDtype,C as runtimeName,De as sessionCount,xe as setModel,Ee as state,Ae as subscribe,ve as toFloat32};
package/src/stt-models.js CHANGED
@@ -1,144 +1 @@
1
- // Catalog of speech-to-text (whisper) models the gateway can run, surfaced in the
2
- // extension's Gateway settings and dictation UI so users pick by their machine's
3
- // resources. All are ONNX (transformers.js) automatic-speech-recognition models —
4
- // same engine, download plumbing, and model root as the NER catalog (models.js).
5
- //
6
- // `tier` groups them for the picker (light / balanced / accurate / max). `ramMB`
7
- // is a rough working-set hint. `approxMB` is the DOWNLOAD size for the dtype the
8
- // current runtime will actually fetch — it differs by runtime (the WASM binary
9
- // downloads fp32; the native npm build downloads q8), so it's a range, and the
10
- // gateway reports the exact bytes as they stream.
11
- //
12
- // Adding a model: any onnx-community/* (or Xenova/*) whisper export works. Verify
13
- // it loads on BOTH runtimes (native q8 + WASM fp32) before listing it — the WASM
14
- // runtime can't load block-quantized (q8/int8) or fp16 exports (see stt-engine
15
- // runtimeDtype). `.en` models are English-only and reject language/task options.
16
-
17
- // THE SHIP DEFAULT. Parakeet rather than Whisper: several times faster at similar or
18
- // better accuracy, and multilingual, so dictation is good out of the box instead of good
19
- // after someone finds the model picker.
20
- //
21
- // Two costs, stated because they are real. It is a ~690 MB one-time download against
22
- // whisper-base's ~300 MB, so first dictation takes longer to become available. And
23
- // parakeet-engine.js fetches from Hugging Face directly rather than ChatPanel's CDN, so a
24
- // clean install's first dictation depends on huggingface.co — mirroring it on
25
- // dl.chatpanel.net removes that dependency and is a release chore, not a code change.
26
- //
27
- // `whisper-base` remains the small, mirrored fallback for anyone who wants dictation
28
- // working in seconds on a slow link.
29
- export const DEFAULT_STT_MODEL = 'istupakov/parakeet-tdt-0.6b-v3-onnx';
30
-
31
- export const STT_MODEL_CATALOG = [
32
- {
33
- id: 'onnx-community/whisper-tiny.en',
34
- label: 'Tiny (English)',
35
- lang: 'English',
36
- tier: 'light',
37
- approxMB: 150, // fp32 on WASM; ~40 on native q8
38
- ramMB: 400,
39
- note: 'Fastest, lightest. English only — great for quick dictation on any machine.',
40
- },
41
- {
42
- id: 'onnx-community/whisper-base',
43
- label: 'Base (multilingual)',
44
- lang: '99 languages (auto-detected)',
45
- tier: 'balanced',
46
- approxMB: 300, // fp32 on WASM; ~80 on native q8
47
- ramMB: 700,
48
- note: 'Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed.',
49
- },
50
- {
51
- id: 'onnx-community/whisper-small',
52
- label: 'Small (multilingual)',
53
- lang: '99 languages (auto-detected)',
54
- tier: 'accurate',
55
- approxMB: 950, // fp32 on WASM; ~250 on native q8
56
- ramMB: 1600,
57
- note: 'Noticeably more accurate; needs a faster CPU to keep up in real time.',
58
- },
59
- {
60
- id: 'onnx-community/whisper-large-v3-turbo',
61
- label: 'Large v3 Turbo (multilingual)',
62
- lang: '99 languages (auto-detected)',
63
- tier: 'max',
64
- approxMB: 1600, // native q8 recommended; heavy on WASM
65
- ramMB: 3200,
66
- note: 'Best accuracy. For powerful machines; use the native (npm) gateway for speed.',
67
- },
68
- {
69
- // NOT a whisper/seq2seq model — a NeMo TDT transducer. It doesn't run through the
70
- // transformers.js ASR pipeline; the STT engine routes `engine: 'parakeet-tdt'`
71
- // models to parakeet-engine.js (raw onnxruntime + a greedy TDT decode). Multilingual
72
- // (25 European languages, auto-detected) and ~35× realtime at int8 on the native
73
- // (npm) gateway — the fast local-dictation path. WASM runs it but slower.
74
- id: 'istupakov/parakeet-tdt-0.6b-v3-onnx',
75
- label: 'Parakeet TDT 0.6B v3 (multilingual, fast)',
76
- lang: '25 European languages (auto-detected)',
77
- tier: 'accurate',
78
- engine: 'parakeet-tdt',
79
- recommended: true, // and the DEFAULT — faster + more accurate than Whisper.
80
- approxMB: 690, // int8: encoder 652 + decoder_joint 18 + preprocessor
81
- ramMB: 1600,
82
- note: 'Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway.',
83
- },
84
- ];
85
-
86
- // The model we steer users to. It is now also DEFAULT_STT_MODEL — the two were split
87
- // while the default stayed small for a fast first run, and shipping the best model by
88
- // default is the call that closed that gap. Kept as its own export because the settings UI
89
- // marks a recommendation, and the two could diverge again (a heavier model that is worth
90
- // recommending but too big to default to).
91
- export const RECOMMENDED_STT_MODEL = 'istupakov/parakeet-tdt-0.6b-v3-onnx';
92
-
93
- // STT engine backing a model. Default 'whisper' = the transformers.js ASR pipeline;
94
- // 'parakeet-tdt' = the raw-onnxruntime transducer engine (parakeet-engine.js).
95
- export function sttModelEngine(id) {
96
- return sttModel(id)?.engine || 'whisper';
97
- }
98
-
99
- export function isKnownSttModel(id) {
100
- return STT_MODEL_CATALOG.some((m) => m.id === id);
101
- }
102
-
103
- export function sttModel(id) {
104
- return STT_MODEL_CATALOG.find((m) => m.id === id) || null;
105
- }
106
-
107
- // English-only exports reject `language`/`task` generation options.
108
- export function isEnglishOnly(id) {
109
- return /\.en$/.test(String(id || ''));
110
- }
111
-
112
- // A model may pin an explicit dtype (overriding the runtime default). None do by
113
- // default — the engine's runtimeDtype() picks q8 (native) / fp32 (WASM) — but
114
- // this is the seam for a model that needs a specific quantization.
115
- export function sttModelDtype(id) {
116
- return sttModel(id)?.dtype || null;
117
- }
118
-
119
- // Accept a user-supplied / registry-picked STT model id. STRICT `org/name` shape,
120
- // no path traversal. We DON'T require "whisper" in the id — the extension's model
121
- // registry only surfaces transformers.js automatic-speech-recognition models
122
- // (whisper, moonshine, …), all of which load via the ASR pipeline; the engine
123
- // fails open if a pick turns out incompatible. Curated ids use the private
124
- // dl.chatpanel.net mirror; custom ids fetch from Hugging Face directly.
125
- export function isValidCustomSttId(id) {
126
- const s = String(id || '');
127
- return /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(s) && !s.includes('..');
128
- }
129
-
130
- // Selectable quantizations (precision). 'auto' = let the runtime decide (q8 on
131
- // native, fp32 on WASM). Each is a transformers.js dtype; a model must actually
132
- // ship that ONNX variant (the load fails open otherwise). Ordered fastest→best.
133
- export const STT_DTYPES = [
134
- { id: 'auto', label: 'Auto (recommended)', note: 'q8 on the native gateway, fp32 on the WASM binary.' },
135
- { id: 'q8', label: 'q8 — fast, balanced', note: 'Int8. Best speed/quality trade-off (native default).' },
136
- { id: 'q4', label: 'q4 — smallest & fastest', note: '4-bit. Least memory; slightly lower accuracy.' },
137
- { id: 'int8', label: 'int8', note: 'Alternative int8 export.' },
138
- { id: 'fp16', label: 'fp16 — more accurate', note: 'Half precision. Larger, a bit slower.' },
139
- { id: 'fp32', label: 'fp32 — most accurate (slow)', note: 'Full precision. Largest + slowest; the only one that loads on the WASM binary.' },
140
- ];
141
-
142
- export function isValidDtype(d) {
143
- return STT_DTYPES.some((x) => x.id === d);
144
- }
1
+ const i="istupakov/parakeet-tdt-0.6b-v3-onnx",a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."}],l="istupakov/parakeet-tdt-0.6b-v3-onnx";function r(e){return n(e)?.engine||"whisper"}function s(e){return a.some(t=>t.id===e)}function n(e){return a.find(t=>t.id===e)||null}function u(e){return/\.en$/.test(String(e||""))}function c(e){return n(e)?.dtype||null}function d(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const o=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function p(e){return o.some(t=>t.id===e)}export{i as DEFAULT_STT_MODEL,l as RECOMMENDED_STT_MODEL,o as STT_DTYPES,a as STT_MODEL_CATALOG,u as isEnglishOnly,s as isKnownSttModel,d as isValidCustomSttId,p as isValidDtype,n as sttModel,c as sttModelDtype,r as sttModelEngine};