@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/tts-engine.js CHANGED
@@ -1,453 +1 @@
1
- // Local text-to-speech — Kokoro (StyleTTS2-family) via the same in-process ONNX
2
- // engine, model root and download plumbing as NER and STT. Phase 4 of
3
- // docs/voice-pipeline.md: "voice out".
4
- //
5
- // Why this drives the model directly instead of using `kokoro-js`: that package
6
- // depends on @huggingface/transformers ^3.5.1 and the gateway pins ^4.2.0, so
7
- // adding it would nest a SECOND transformers install — a second ONNX runtime in a
8
- // binary whose build script (scripts/build.mjs) exists specifically to control
9
- // which runtime ships. transformers 4.2 has StyleTextToSpeech2Model built in, so
10
- // the model loads on the pinned version and the only thing kokoro-js was really
11
- // providing — grapheme→phoneme — comes from `phonemizer` (zero dependencies, a
12
- // pure-JS espeak-ng, so it survives Bun --compile).
13
- //
14
- // Privacy: synthesis is entirely local. Nothing is sent anywhere, which is why the
15
- // route speaks RESTORED text rather than redacted text — see the /tts handler.
16
- //
17
- // This module owns ONE concern: text in, PCM out. Streaming, routing and redaction
18
- // live at the server/route layer, because a pipeline stage never imports another
19
- // stage.
20
-
21
- import { join } from 'node:path';
22
- import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';
23
- import { ensureLib, modelRoot } from './ner-engine.js';
24
- import { runtimeDtype, runtimeName, DTYPE_SUFFIX } from './model-runtime.js';
25
- import {
26
- DEFAULT_TTS_MODEL, DEFAULT_TTS_VOICE, STYLE_DIM, MAX_PHONEME_TOKENS,
27
- ttsModelDtype, isKnownTtsModel, isValidVoiceId, voiceLang, ttsModelEngine, ttsModel,
28
- } from './tts-models.js';
29
- import { bundleOnDisk as pocketBundleOnDisk } from './pocket-tts-engine.js';
30
-
31
- // Kokoro's rate. Kept as a named export because it is the default and several
32
- // callers want a number before anything is loaded — but it is NOT universal: a
33
- // VITS/MMS model outputs 16 kHz, and writing its samples into a 24 kHz WAV header
34
- // plays it back fast and chipmunked. Use sampleRate() once a model is active.
35
- export const SAMPLE_RATE = 24000;
36
-
37
- let _state = 'off'; // 'off' | 'loading' | 'downloading' | 'ready' | 'error'
38
- let _model = null;
39
- let _net = null; // StyleTextToSpeech2Model
40
- let _tok = null; // phoneme tokenizer
41
- let _dtype = null;
42
- let _err = null;
43
- let _progress = null;
44
- let _initPromise = null;
45
- let _arch = null; // 'style-tts2' (Kokoro) | 'vits' (MMS) | 'speecht5' (custom voices)
46
- let _vocoder = null; // speecht5 only — mel → waveform
47
- let _pocket = null; // pocket-tts only — its own PocketTTS instance
48
- let _encoder = null; // a PocketTTS kept ONLY to encode voices, never to speak
49
- let _rate = SAMPLE_RATE; // the ACTIVE model's output rate
50
- const _voices = new Map(); // voice id → Float32Array style bank
51
-
52
- // The architectures this engine can actually drive. Anything else is refused at
53
- // load with a message naming what it is, rather than failing later inside a
54
- // forward pass with a shape error nobody can act on.
55
- export const SUPPORTED_ARCH = { style_text_to_speech_2: 'style-tts2', vits: 'vits', speecht5: 'speecht5' };
56
-
57
- // Pocket TTS is not a transformers.js model — it is five raw ONNX graphs with a
58
- // hand-written generation loop, exactly like parakeet on the STT side — so it is
59
- // dispatched by catalog id rather than by a transformers config.model_type.
60
- export const POCKET_ARCH = 'pocket-tts';
61
-
62
- // SpeechT5 is the only architecture here that takes a SPEAKER EMBEDDING, which is
63
- // what makes a custom voice possible at all: Kokoro's voices are fixed style banks
64
- // and VITS is single-speaker, so neither can be pointed at a person. It needs a
65
- // separate vocoder (mel → waveform), hence the extra model id.
66
- export const SPEECHT5_VOCODER = 'Xenova/speecht5_hifigan';
67
- // Both engines that can be pointed at a person. Pocket TTS is the one built for
68
- // it; SpeechT5 is kept because it is small and already downloaded for anyone who
69
- // tried it, but it borrows a voice rather than reproducing one.
70
- export function supportsCustomVoices() { return _arch === 'speecht5' || _arch === POCKET_ARCH; }
71
- export function isPocket() { return _arch === POCKET_ARCH; }
72
- /** The built-in speaker names the loaded Pocket model offers, if any. */
73
- export function builtinVoices() { return _pocket?.builtinVoices?.() || []; }
74
-
75
- /**
76
- * A PocketTTS instance purely for ENCODING a voice, without disturbing whatever
77
- * model is currently speaking. Saving a voice has to derive its conditioning while
78
- * the sample still exists, and that must not silently switch the active engine out
79
- * from under a conversation in progress.
80
- */
81
- export async function pocketForEncoding({ allowDownload = true, log = () => {} } = {}) {
82
- if (_pocket) return _pocket;
83
- const { PocketTTS, bundleOnDisk, DEFAULT_BUNDLE } = await import('./pocket-tts-engine.js');
84
- if (!bundleOnDisk(DEFAULT_BUNDLE) && !allowDownload) return null;
85
- if (_encoder) return _encoder;
86
- const pt = new PocketTTS();
87
- await pt.load(DEFAULT_BUNDLE, { log });
88
- _encoder = pt;
89
- return pt;
90
- }
91
-
92
- export function arch() { return _arch; }
93
- export function sampleRate() { return _rate; }
94
- // Kokoro picks a voice from a style bank; VITS is single-speaker and has none, so
95
- // the UI must not offer a voice list that cannot do anything.
96
- export function supportsVoices() { return _arch === 'style-tts2'; }
97
-
98
- export function state() { return _state; }
99
- export function isReady() { return _state === 'ready' && !!_net; }
100
- export function progress() { return _progress; }
101
-
102
- export function health() {
103
- return { configured: _state !== 'off', ok: isReady(), state: _state, model: _model, dtype: _dtype, runtime: runtimeName(), error: _err, arch: _arch, sampleRate: _rate, voices: supportsVoices(), customVoices: supportsCustomVoices() };
104
- }
105
-
106
- export function modelDir(modelId) {
107
- return join(modelRoot(), ...String(modelId).split('/'));
108
- }
109
-
110
- // Present = the EXACT ONNX file this runtime will load, plus the tokenizer. Both
111
- // non-empty: a truncated download must not read as installed.
112
- export function modelOnDisk(modelId = _model || DEFAULT_TTS_MODEL, dtype = ttsModelDtype(modelId) || runtimeDtype()) {
113
- // Pocket TTS keeps a bundle of five graphs under its own directory, not a single
114
- // transformers-style onnx/ folder. bundleOnDisk is a pure fs predicate — the
115
- // heavy onnxruntime import inside that module is dynamic — so importing it
116
- // statically costs nothing.
117
- if (ttsModelEngine(modelId) === POCKET_ARCH) return pocketBundleOnDisk(ttsModel(modelId)?.bundle);
118
- const dir = modelDir(modelId);
119
- const suffix = DTYPE_SUFFIX[dtype] ?? '';
120
- const need = [join(dir, 'onnx', `model${suffix}.onnx`), join(dir, 'tokenizer.json')];
121
- try {
122
- return need.every((p) => existsSync(p) && statSync(p).size > 0);
123
- } catch { return false; }
124
- }
125
-
126
- // A voice is a separate ~500 KB style bank (voices/<id>.bin), not part of the model
127
- // download, so it is fetched and checked on its own.
128
- export function voiceOnDisk(voice, modelId = _model || DEFAULT_TTS_MODEL) {
129
- if (!isValidVoiceId(voice)) return false;
130
- const p = join(modelDir(modelId), 'voices', `${voice}.bin`);
131
- try { return existsSync(p) && statSync(p).size > 0; } catch { return false; }
132
- }
133
-
134
- export function init(cfg = {}) {
135
- const tts = cfg.tts || {};
136
- if (tts.enabled === false) { _state = 'off'; return; }
137
- _model = tts.model || DEFAULT_TTS_MODEL;
138
- // No autostart, same as STT: the model downloads on FIRST synthesis, never on
139
- // gateway boot — a 90-330 MB fetch must not be a side effect of starting up.
140
- }
141
-
142
- async function loadModel(modelId, { log = () => {}, allowDownload = true, dtype: dtypeOverride = null } = {}) {
143
- // Pocket TTS has its own loader (raw onnxruntime, its own bundle layout), so it
144
- // is routed before any transformers.js machinery is touched.
145
- if (ttsModelEngine(modelId) === POCKET_ARCH) return loadPocket(modelId, { log, allowDownload });
146
-
147
- const prevNet = _net, prevModel = _model;
148
- let lib;
149
- try {
150
- lib = await ensureLib();
151
- } catch (e) {
152
- _state = 'error'; _err = `engine load failed: ${e.message}`;
153
- log(`[tts] transformers.js not available (${e.message}) — read-aloud falls back to browser speech`);
154
- return false;
155
- }
156
-
157
- const chosen = dtypeOverride && dtypeOverride !== 'auto' ? dtypeOverride : null;
158
- const dtype = chosen || ttsModelDtype(modelId) || runtimeDtype();
159
- const haveLocal = modelOnDisk(modelId, dtype);
160
- lib.env.allowRemoteModels = haveLocal ? false : !!allowDownload;
161
- if (!haveLocal && !allowDownload) {
162
- _state = 'error'; _err = 'model not on disk and downloads disabled';
163
- log(`[tts] model ${modelId} not installed and downloads disabled`);
164
- return false;
165
- }
166
-
167
- // ensureLib points remoteHost at the private dl.chatpanel.net mirror, which
168
- // carries the NER and STT models but NOT the TTS ones yet (it 403s on them), so
169
- // every TTS fetch goes to Hugging Face for now — curated and custom alike. Once
170
- // the mirror carries them, narrow this back to `!isKnownTtsModel(modelId)` the
171
- // way stt-engine does, and curated downloads move to the mirror with no other
172
- // change. Voice banks (loadVoice) fetch from HF for the same reason.
173
- const prevHost = lib.env.remoteHost;
174
- const mirrored = false; // ← flip when dl.chatpanel.net mirrors the TTS models
175
- if (!haveLocal && (!mirrored || !isKnownTtsModel(modelId))) {
176
- try { lib.env.remoteHost = 'https://huggingface.co/'; } catch { /* optional */ }
177
- }
178
-
179
- _state = haveLocal ? 'loading' : 'downloading';
180
- if (!haveLocal) { _progress = { model: modelId, file: null, pct: 0 }; log(`[tts] downloading voice model ${modelId} (one-time)…`); }
181
-
182
- try {
183
- // The extra classes ensureLib doesn't return. Module resolution is cached, so
184
- // this is the SAME transformers instance ensureLib already configured (env,
185
- // cacheDir, wasm paths) — importing it here keeps ner-engine free of TTS.
186
- const tf = await import('@huggingface/transformers');
187
-
188
- // Which architecture is this? Read the config BEFORE choosing a class, so an
189
- // unsupported model is refused by name instead of exploding inside a forward
190
- // pass with a tensor-shape error.
191
- let modelType = '';
192
- try {
193
- const conf = await tf.AutoConfig.from_pretrained(modelId);
194
- modelType = String(conf?.model_type || '').toLowerCase();
195
- } catch { /* no config we can read — fall through to the Kokoro default */ }
196
- const kind = SUPPORTED_ARCH[modelType] || (modelType ? null : 'style-tts2');
197
- if (!kind) throw new Error(`unsupported TTS architecture "${modelType}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);
198
-
199
- const onProgress = (p) => {
200
- if (p?.status === 'progress' && p.file) _progress = { model: modelId, file: p.file, pct: Math.round(p.progress || 0) };
201
- };
202
- const Klass = kind === 'vits' ? tf.VitsModel
203
- : kind === 'speecht5' ? tf.SpeechT5ForTextToSpeech
204
- : tf.StyleTextToSpeech2Model;
205
- const [net, tok] = await Promise.all([
206
- Klass.from_pretrained(modelId, { dtype, progress_callback: onProgress }),
207
- tf.AutoTokenizer.from_pretrained(modelId),
208
- ]);
209
- // The vocoder is a second download and a second failure point, so it is loaded
210
- // only for the architecture that needs one.
211
- _vocoder = kind === 'speecht5'
212
- ? await tf.SpeechT5HifiGan.from_pretrained(SPEECHT5_VOCODER, { dtype, progress_callback: onProgress })
213
- : null;
214
- _net = net; _tok = tok; _model = modelId; _dtype = dtype; _arch = kind;
215
- // VITS/MMS emit 16 kHz; Kokoro 24 kHz. Take it from the model's own config
216
- // where it says so, because guessing wrong plays the voice at the wrong pitch.
217
- _rate = Number(net?.config?.sampling_rate) || (kind === 'style-tts2' ? SAMPLE_RATE : 16000);
218
- _state = 'ready'; _err = null; _progress = null;
219
- log(`[tts] ready — model ${modelId} @ ${dtype} (${kind}, ${_rate} Hz, ${runtimeName()}, offline) — local speech active`);
220
- return true;
221
- } catch (e) {
222
- // A failed SWITCH keeps the previous working model, same as ner/stt.
223
- _net = prevNet; _model = prevModel;
224
- _state = prevNet ? 'ready' : 'error';
225
- _err = e.message; _progress = null;
226
- log(`[tts] model load failed (${e.message})`);
227
- return false;
228
- } finally {
229
- try { lib.env.remoteHost = prevHost; } catch { /* optional */ }
230
- }
231
- }
232
-
233
- async function loadPocket(modelId, { log = () => {}, allowDownload = true } = {}) {
234
- const prevArch = _arch, prevPocket = _pocket, prevModel = _model;
235
- const { PocketTTS, bundleOnDisk, DEFAULT_BUNDLE, SAMPLE_RATE: PR } = await import('./pocket-tts-engine.js');
236
- const bundle = ttsModel(modelId)?.bundle || DEFAULT_BUNDLE;
237
- if (!bundleOnDisk(bundle) && !allowDownload) {
238
- _state = 'error'; _err = 'model not on disk and downloads disabled';
239
- return false;
240
- }
241
- _state = bundleOnDisk(bundle) ? 'loading' : 'downloading';
242
- if (_state === 'downloading') _progress = { model: modelId, file: null, pct: 0 };
243
- try {
244
- const pt = new PocketTTS();
245
- await pt.load(bundle, {
246
- log,
247
- onProgress: ({ file, pct }) => { _progress = { model: modelId, file, pct }; },
248
- });
249
- _pocket = pt; _net = pt; _tok = null; _vocoder = null;
250
- _model = modelId; _arch = POCKET_ARCH; _dtype = 'int8'; _rate = PR;
251
- _state = 'ready'; _err = null; _progress = null;
252
- return true;
253
- } catch (e) {
254
- // A failed switch keeps whatever was working, same as every other engine here.
255
- _pocket = prevPocket; _arch = prevArch; _model = prevModel;
256
- _state = prevPocket || _net ? 'ready' : 'error';
257
- _err = e.message; _progress = null;
258
- log(`[pocket-tts] load failed (${e.message})`);
259
- return false;
260
- }
261
- }
262
-
263
- export async function setModel(modelId, { onLog = () => {}, allowDownload = true, dtype = 'auto' } = {}) {
264
- const want = dtype && dtype !== 'auto' ? dtype : (ttsModelDtype(modelId) || runtimeDtype());
265
- if (modelId === _model && isReady() && _dtype === want) return true;
266
- _initPromise = loadModel(modelId, { log: onLog, allowDownload, dtype });
267
- return _initPromise;
268
- }
269
-
270
- export async function ready({ onLog = () => {}, allowDownload = true, model = null, dtype = 'auto' } = {}) {
271
- if (isReady()) return true;
272
- if (_initPromise) return _initPromise;
273
- return setModel(model || _model || DEFAULT_TTS_MODEL, { onLog, allowDownload, dtype });
274
- }
275
-
276
- // ── voices ───────────────────────────────────────────────────────────────────────
277
- // voices/<id>.bin is a flat Float32 bank of MAX+1 style vectors — one per possible
278
- // token count — so the row is selected by the length of THIS utterance.
279
- async function loadVoice(voice, { allowDownload = true, log = () => {} } = {}) {
280
- if (!isValidVoiceId(voice)) throw new Error(`invalid voice id: ${voice}`);
281
- const cached = _voices.get(voice);
282
- if (cached) return cached;
283
- const dir = join(modelDir(_model || DEFAULT_TTS_MODEL), 'voices');
284
- const dest = join(dir, `${voice}.bin`);
285
- if (!(existsSync(dest) && statSync(dest).size > 0)) {
286
- if (!allowDownload) throw new Error(`voice ${voice} not on disk and downloads disabled`);
287
- mkdirSync(dir, { recursive: true });
288
- const url = `https://huggingface.co/${_model || DEFAULT_TTS_MODEL}/resolve/main/voices/${voice}.bin`;
289
- const res = await fetch(url, { redirect: 'follow' });
290
- if (!res.ok) throw new Error(`fetch voice ${voice} → HTTP ${res.status}`);
291
- // .part then rename, so an interrupted fetch never looks complete.
292
- const tmp = `${dest}.part`;
293
- writeFileSync(tmp, Buffer.from(await res.arrayBuffer()));
294
- renameSync(tmp, dest);
295
- log(`[tts] fetched voice ${voice}`);
296
- }
297
- const buf = readFileSync(dest);
298
- const bank = new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4));
299
- _voices.set(voice, bank);
300
- return bank;
301
- }
302
-
303
- // ── text → speech ────────────────────────────────────────────────────────────────
304
- // Kokoro accepts at most MAX_PHONEME_TOKENS per forward pass and SILENTLY drops
305
- // whatever does not fit — the failure is "it stopped reading halfway", with no
306
- // error. So every returned part must be bounded, not merely usually bounded.
307
- //
308
- // Boundaries are tried in descending order of how natural the pause sounds:
309
- // sentence → clause → word → (last resort) a hard slice. Falling through to the
310
- // next one only happens when the previous left a part still over the limit, so
311
- // ordinary prose splits where a listener expects a breath.
312
- export function splitSentences(text, maxChars = 300) {
313
- const bound = (s, seps) => {
314
- if (s.length <= maxChars) return [s];
315
- if (!seps.length) {
316
- // A single unbroken run longer than the window (a URL, a base64 blob).
317
- // Slicing it is ugly to listen to, but losing its tail is worse.
318
- const out = [];
319
- for (let i = 0; i < s.length; i += maxChars) out.push(s.slice(i, i + maxChars).trim());
320
- return out.filter(Boolean);
321
- }
322
- const [sep, ...rest] = seps;
323
- const out = [];
324
- let buf = '';
325
- for (const piece of s.split(sep)) {
326
- const p = piece.trim();
327
- if (!p) continue;
328
- const cand = buf ? `${buf} ${p}` : p;
329
- if (cand.length > maxChars && buf) { out.push(...bound(buf, rest)); buf = p; }
330
- else buf = cand;
331
- }
332
- if (buf) out.push(...bound(buf, rest));
333
- return out;
334
- };
335
-
336
- const parts = [];
337
- for (const raw of String(text).split(/(?<=[.!?])\s+|\n{2,}/)) {
338
- const s = raw.trim();
339
- if (s) parts.push(...bound(s, [/(?<=[,;:])\s+/, /\s+/]));
340
- }
341
- return parts;
342
- }
343
-
344
- /**
345
- * Synthesize ONE chunk. Returns 24 kHz mono Float32 PCM.
346
- * @param {string} text @param {{voice?: string, speed?: number}} [opts]
347
- */
348
- export async function synthChunk(text, { voice = DEFAULT_TTS_VOICE, speed = 1, speakerEmbedding = null } = {}) {
349
- if (!isReady()) throw new Error('tts model not ready');
350
- const tf = await import('@huggingface/transformers');
351
-
352
- // VITS/MMS: single-speaker, tokenizes GRAPHEMES directly — no phonemizer, no
353
- // style bank, no speed input. One language per model, which is the trade for
354
- // ~40 MB and a thousand of them.
355
- if (_arch === 'vits') {
356
- const inputs = _tok(String(text));
357
- const out = await _net(inputs);
358
- return out.waveform.data;
359
- }
360
-
361
- // Pocket TTS runs its own generation loop and chunking, so a whole utterance is
362
- // handed over at once rather than being pre-split here.
363
- if (_arch === POCKET_ARCH) {
364
- // Either a cloned voice (an embedding) or one of its built-in speakers (a name).
365
- const v = speakerEmbedding?.data?.length ? speakerEmbedding : voice;
366
- if (!v) throw new Error('this model needs a voice — pick a built-in one or record your own');
367
- return _pocket.synth(String(text), { voice: v });
368
- }
369
-
370
- // SpeechT5: conditioned by a 512-d speaker embedding, which is the whole point —
371
- // it is the one architecture here that can be pointed at a person's voice.
372
- // Without an embedding there is no voice to speak in, so this refuses rather
373
- // than inventing one.
374
- if (_arch === 'speecht5') {
375
- if (!speakerEmbedding || speakerEmbedding.length !== 512) {
376
- throw new Error('this model needs a saved voice — record one in Settings → Text-to-speech');
377
- }
378
- const { input_ids } = _tok(String(text));
379
- const emb = new tf.Tensor('float32', Float32Array.from(speakerEmbedding), [1, 512]);
380
- const { waveform } = await _net.generate_speech(input_ids, emb, { vocoder: _vocoder });
381
- return waveform.data;
382
- }
383
-
384
- const { phonemize } = await import('phonemizer');
385
-
386
- // G2P follows the VOICE, not the request — an American voice reading British
387
- // phonemes is audibly wrong.
388
- const phonemes = (await phonemize(String(text), voiceLang(voice))).join(' ');
389
- const { input_ids } = _tok(phonemes, { truncation: true });
390
-
391
- const bank = await loadVoice(voice);
392
- // One style row per token count; clamp so a long chunk still picks a valid row.
393
- const n = Math.min(Math.max(input_ids.dims.at(-1) - 2, 0), Math.floor(bank.length / STYLE_DIM) - 1);
394
- const style = bank.slice(n * STYLE_DIM, n * STYLE_DIM + STYLE_DIM);
395
-
396
- const out = await _net({
397
- input_ids,
398
- style: new tf.Tensor('float32', style, [1, STYLE_DIM]),
399
- speed: new tf.Tensor('float32', [speed], [1]),
400
- });
401
- return out.waveform.data;
402
- }
403
-
404
- /** Synthesize arbitrary-length text, chunk by chunk. `onChunk` sees each as it lands. */
405
- export async function synth(text, { voice = DEFAULT_TTS_VOICE, speed = 1, speakerEmbedding = null, onChunk = null } = {}) {
406
- // Pocket TTS splits internally against its own token ceiling, so splitting again
407
- // here would cut sentences twice and reset its state mid-thought.
408
- if (_arch === POCKET_ARCH) return synthChunk(text, { voice, speed, speakerEmbedding });
409
- const chunks = splitSentences(text);
410
- const out = [];
411
- for (const c of chunks) {
412
- const pcm = await synthChunk(c, { voice, speed, speakerEmbedding });
413
- out.push(pcm);
414
- onChunk?.(pcm);
415
- }
416
- if (out.length === 1) return out[0];
417
- const total = out.reduce((n, a) => n + a.length, 0);
418
- const merged = new Float32Array(total);
419
- let at = 0;
420
- for (const a of out) { merged.set(a, at); at += a.length; }
421
- return merged;
422
- }
423
-
424
- // ── WAV ──────────────────────────────────────────────────────────────────────────
425
- // 16-bit PCM WAV: what every <audio> element and every OS player accepts without a
426
- // codec. Float32 → int16 with clamping (a value outside [-1,1] wraps and clicks).
427
- export function toWav(pcm, sampleRate = SAMPLE_RATE) {
428
- const buf = Buffer.alloc(44 + pcm.length * 2);
429
- buf.write('RIFF', 0);
430
- buf.writeUInt32LE(36 + pcm.length * 2, 4);
431
- buf.write('WAVE', 8);
432
- buf.write('fmt ', 12);
433
- buf.writeUInt32LE(16, 16); // PCM chunk size
434
- buf.writeUInt16LE(1, 20); // format = PCM
435
- buf.writeUInt16LE(1, 22); // channels = mono
436
- buf.writeUInt32LE(sampleRate, 24);
437
- buf.writeUInt32LE(sampleRate * 2, 28); // byte rate
438
- buf.writeUInt16LE(2, 32); // block align
439
- buf.writeUInt16LE(16, 34); // bits per sample
440
- buf.write('data', 36);
441
- buf.writeUInt32LE(pcm.length * 2, 40);
442
- for (let i = 0; i < pcm.length; i++) {
443
- const s = Math.max(-1, Math.min(1, pcm[i]));
444
- buf.writeInt16LE(Math.round(s * 32767), 44 + i * 2);
445
- }
446
- return buf;
447
- }
448
-
449
- export function _reset() {
450
- _state = 'off'; _model = null; _net = null; _tok = null; _dtype = null;
451
- _err = null; _progress = null; _initPromise = null; _arch = null; _rate = SAMPLE_RATE; _vocoder = null; _pocket = null; _encoder = null;
452
- _voices.clear();
453
- }
1
+ import{join as k}from"node:path";import{existsSync as O,mkdirSync as Q,readFileSync as Z,writeFileSync as I,renameSync as tt,statSync as V}from"node:fs";import{ensureLib as et,modelRoot as nt}from"./ner-engine.js";import{runtimeDtype as R,runtimeName as K,DTYPE_SUFFIX as rt}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as b,DEFAULT_TTS_VOICE as j,STYLE_DIM as L,ttsModelDtype as H,isKnownTtsModel as ot,isValidVoiceId as X,voiceLang as st,ttsModelEngine as W,ttsModel as Y}from"./tts-models.js";import{bundleOnDisk as it}from"./pocket-tts-engine.js";const A=24e3;let p="off",d=null,m=null,x=null,$=null,T=null,y=null,P=null,h=null,D=null,E=null,U=null,M=A;const z=new Map,lt={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},S="pocket-tts",at="Xenova/speecht5_hifigan";function ct(){return h==="speecht5"||h===S}function kt(){return h===S}function bt(){return E?.builtinVoices?.()||[]}async function xt({allowDownload:t=!0,log:n=()=>{}}={}){if(E)return E;const{PocketTTS:e,bundleOnDisk:r,DEFAULT_BUNDLE:o}=await import("./pocket-tts-engine.js");if(!r(o)&&!t)return null;if(U)return U;const s=new e;return await s.load(o,{log:n}),U=s,s}function Mt(){return h}function Lt(){return M}function ut(){return h==="style-tts2"}function $t(){return p}function F(){return p==="ready"&&!!m}function Pt(){return y}function At(){return{configured:p!=="off",ok:F(),state:p,model:d,dtype:$,runtime:K(),error:T,arch:h,sampleRate:M,voices:ut(),customVoices:ct()}}function B(t){return k(nt(),...String(t).split("/"))}function ft(t=d||b,n=H(t)||R()){if(W(t)===S)return it(Y(t)?.bundle);const e=B(t),r=rt[n]??"",o=[k(e,"onnx",`model${r}.onnx`),k(e,"tokenizer.json")];try{return o.every(s=>O(s)&&V(s).size>0)}catch{return!1}}function Dt(t,n=d||b){if(!X(t))return!1;const e=k(B(n),"voices",`${t}.bin`);try{return O(e)&&V(e).size>0}catch{return!1}}function Ut(t={}){const n=t.tts||{};if(n.enabled===!1){p="off";return}d=n.model||b}async function pt(t,{log:n=()=>{},allowDownload:e=!0,dtype:r=null}={}){if(W(t)===S)return dt(t,{log:n,allowDownload:e});const o=m,s=d;let u;try{u=await et()}catch(l){return p="error",T=`engine load failed: ${l.message}`,n(`[tts] transformers.js not available (${l.message}) — read-aloud falls back to browser speech`),!1}const f=(r&&r!=="auto"?r:null)||H(t)||R(),i=ft(t,f);if(u.env.allowRemoteModels=i?!1:!!e,!i&&!e)return p="error",T="model not on disk and downloads disabled",n(`[tts] model ${t} not installed and downloads disabled`),!1;const c=u.env.remoteHost;if(!i&&(!!1||!ot(t)))try{u.env.remoteHost="https://huggingface.co/"}catch{}p=i?"loading":"downloading",i||(y={model:t,file:null,pct:0},n(`[tts] downloading voice model ${t} (one-time)…`));try{const l=await import("@huggingface/transformers");let g="";try{const v=await l.AutoConfig.from_pretrained(t);g=String(v?.model_type||"").toLowerCase()}catch{}const _=lt[g]||(g?null:"style-tts2");if(!_)throw new Error(`unsupported TTS architecture "${g}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);const C=v=>{v?.status==="progress"&&v.file&&(y={model:t,file:v.file,pct:Math.round(v.progress||0)})},q=_==="vits"?l.VitsModel:_==="speecht5"?l.SpeechT5ForTextToSpeech:l.StyleTextToSpeech2Model,[N,J]=await Promise.all([q.from_pretrained(t,{dtype:f,progress_callback:C}),l.AutoTokenizer.from_pretrained(t)]);return D=_==="speecht5"?await l.SpeechT5HifiGan.from_pretrained(at,{dtype:f,progress_callback:C}):null,m=N,x=J,d=t,$=f,h=_,M=Number(N?.config?.sampling_rate)||(_==="style-tts2"?A:16e3),p="ready",T=null,y=null,n(`[tts] ready — model ${t} @ ${f} (${_}, ${M} Hz, ${K()}, offline) — local speech active`),!0}catch(l){return m=o,d=s,p=o?"ready":"error",T=l.message,y=null,n(`[tts] model load failed (${l.message})`),!1}finally{try{u.env.remoteHost=c}catch{}}}async function dt(t,{log:n=()=>{},allowDownload:e=!0}={}){const r=h,o=E,s=d,{PocketTTS:u,bundleOnDisk:w,DEFAULT_BUNDLE:f,SAMPLE_RATE:i}=await import("./pocket-tts-engine.js"),c=Y(t)?.bundle||f;if(!w(c)&&!e)return p="error",T="model not on disk and downloads disabled",!1;p=w(c)?"loading":"downloading",p==="downloading"&&(y={model:t,file:null,pct:0});try{const a=new u;return await a.load(c,{log:n,onProgress:({file:l,pct:g})=>{y={model:t,file:l,pct:g}}}),E=a,m=a,x=null,D=null,d=t,h=S,$="int8",M=i,p="ready",T=null,y=null,!0}catch(a){return E=o,h=r,d=s,p=o||m?"ready":"error",T=a.message,y=null,n(`[pocket-tts] load failed (${a.message})`),!1}}async function ht(t,{onLog:n=()=>{},allowDownload:e=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:H(t)||R();return t===d&&F()&&$===o?!0:(P=pt(t,{log:n,allowDownload:e,dtype:r}),P)}async function Ft({onLog:t=()=>{},allowDownload:n=!0,model:e=null,dtype:r="auto"}={}){return F()?!0:P||ht(e||d||b,{onLog:t,allowDownload:n,dtype:r})}async function wt(t,{allowDownload:n=!0,log:e=()=>{}}={}){if(!X(t))throw new Error(`invalid voice id: ${t}`);const r=z.get(t);if(r)return r;const o=k(B(d||b),"voices"),s=k(o,`${t}.bin`);if(!(O(s)&&V(s).size>0)){if(!n)throw new Error(`voice ${t} not on disk and downloads disabled`);Q(o,{recursive:!0});const f=`https://huggingface.co/${d||b}/resolve/main/voices/${t}.bin`,i=await fetch(f,{redirect:"follow"});if(!i.ok)throw new Error(`fetch voice ${t} → HTTP ${i.status}`);const c=`${s}.part`;I(c,Buffer.from(await i.arrayBuffer())),tt(c,s),e(`[tts] fetched voice ${t}`)}const u=Z(s),w=new Float32Array(u.buffer,u.byteOffset,Math.floor(u.byteLength/4));return z.set(t,w),w}function mt(t,n=300){const e=(o,s)=>{if(o.length<=n)return[o];if(!s.length){const c=[];for(let a=0;a<o.length;a+=n)c.push(o.slice(a,a+n).trim());return c.filter(Boolean)}const[u,...w]=s,f=[];let i="";for(const c of o.split(u)){const a=c.trim();if(!a)continue;const l=i?`${i} ${a}`:a;l.length>n&&i?(f.push(...e(i,w)),i=a):i=l}return i&&f.push(...e(i,w)),f},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const s=o.trim();s&&r.push(...e(s,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function G(t,{voice:n=j,speed:e=1,speakerEmbedding:r=null}={}){if(!F())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(h==="vits"){const l=x(String(t));return(await m(l)).waveform.data}if(h===S){const l=r?.data?.length?r:n;if(!l)throw new Error("this model needs a voice — pick a built-in one or record your own");return E.synth(String(t),{voice:l})}if(h==="speecht5"){if(!r||r.length!==512)throw new Error("this model needs a saved voice — record one in Settings → Text-to-speech");const{input_ids:l}=x(String(t)),g=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:_}=await m.generate_speech(l,g,{vocoder:D});return _.data}const{phonemize:s}=await import("phonemizer"),u=(await s(String(t),st(n))).join(" "),{input_ids:w}=x(u,{truncation:!0}),f=await wt(n),i=Math.min(Math.max(w.dims.at(-1)-2,0),Math.floor(f.length/L)-1),c=f.slice(i*L,i*L+L);return(await m({input_ids:w,style:new o.Tensor("float32",c,[1,L]),speed:new o.Tensor("float32",[e],[1])})).waveform.data}async function Ot(t,{voice:n=j,speed:e=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(h===S)return G(t,{voice:n,speed:e,speakerEmbedding:r});const s=mt(t),u=[];for(const c of s){const a=await G(c,{voice:n,speed:e,speakerEmbedding:r});u.push(a),o?.(a)}if(u.length===1)return u[0];const w=u.reduce((c,a)=>c+a.length,0),f=new Float32Array(w);let i=0;for(const c of u)f.set(c,i),i+=c.length;return f}function Vt(t,n=A){const e=Buffer.alloc(44+t.length*2);e.write("RIFF",0),e.writeUInt32LE(36+t.length*2,4),e.write("WAVE",8),e.write("fmt ",12),e.writeUInt32LE(16,16),e.writeUInt16LE(1,20),e.writeUInt16LE(1,22),e.writeUInt32LE(n,24),e.writeUInt32LE(n*2,28),e.writeUInt16LE(2,32),e.writeUInt16LE(16,34),e.write("data",36),e.writeUInt32LE(t.length*2,40);for(let r=0;r<t.length;r++){const o=Math.max(-1,Math.min(1,t[r]));e.writeInt16LE(Math.round(o*32767),44+r*2)}return e}function Rt(){p="off",d=null,m=null,x=null,$=null,T=null,y=null,P=null,h=null,M=A,D=null,E=null,U=null,z.clear()}export{S as POCKET_ARCH,A as SAMPLE_RATE,at as SPEECHT5_VOCODER,lt as SUPPORTED_ARCH,Rt as _reset,Mt as arch,bt as builtinVoices,At as health,Ut as init,kt as isPocket,F as isReady,B as modelDir,ft as modelOnDisk,xt as pocketForEncoding,Pt as progress,Ft as ready,Lt as sampleRate,ht as setModel,mt as splitSentences,$t as state,ct as supportsCustomVoices,ut as supportsVoices,Ot as synth,G as synthChunk,Vt as toWav,Dt as voiceOnDisk};