@chatpanel/gateway 0.6.110 → 0.7.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 (80) 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 +1 -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/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2296
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
package/src/tts-models.js CHANGED
@@ -1,254 +1 @@
1
- // Catalog of text-to-speech models the gateway can run — Phase 4 of the voice
2
- // pipeline (docs/voice-pipeline.md), the "voice out" counterpart to stt-models.js.
3
- // Same engine family (ONNX via transformers.js), same model root, same download
4
- // plumbing, same picker shape — so the Gateway tab renders it like the STT list.
5
- //
6
- // Why Kokoro and not the piper-class voices the design doc originally named: piper
7
- // phonemizes through `piper-phonemize`, a NATIVE espeak-ng binding, and the
8
- // standalone binary is a Bun --compile artifact that cannot carry native addons
9
- // (it is why scripts/build.mjs stubs onnxruntime-node and sharp). Kokoro's G2P is
10
- // the pure-JS `phonemizer` package — zero dependencies — so it is the one that
11
- // actually runs on BOTH delivery channels. It is also Apache-2.0, 82M params, and
12
- // ships fp32 + quantized ONNX exports, which is exactly the dual-runtime split
13
- // model-runtime.js already encodes.
14
- //
15
- // Adding a model: it must expose `onnx/model{suffix}.onnx` and a tokenizer, and be
16
- // driveable by a transformers.js class (Kokoro = StyleTextToSpeech2Model). Verify
17
- // it loads on BOTH runtimes (native q8 + WASM fp32) before listing it.
18
-
19
- // Pocket TTS is the default where it can run: it is the fastest engine here
20
- // (7-9x realtime against Kokoro's 2.1x) and the only one that can speak as the
21
- // user. It needs the native onnxruntime, though, which the standalone binary does
22
- // not carry — so the binary falls back to Kokoro rather than offering a model it
23
- // cannot load. See src/ort.js for why.
24
- export const DEFAULT_TTS_MODEL_NATIVE = 'kyutai/pocket-tts';
25
- export const DEFAULT_TTS_MODEL_WASM = 'onnx-community/Kokoro-82M-v1.0-ONNX';
26
- export const DEFAULT_TTS_MODEL = DEFAULT_TTS_MODEL_WASM; // safe default; resolveDefaultModel() picks properly
27
- export const DEFAULT_TTS_VOICE = 'af_heart';
28
-
29
- // The eight speakers shipped in voices.bin. Names only — the data is a ~52 MB
30
- // optional download, and cloning works without it.
31
- export const POCKET_VOICES = ['alba', 'azelma', 'cosette', 'eponine', 'fantine', 'javert', 'jean', 'marius'];
32
- export const DEFAULT_POCKET_VOICE = 'alba';
33
-
34
- export function isPocketVoice(v) {
35
- return POCKET_VOICES.includes(String(v || ''));
36
- }
37
-
38
- /** The model to use when nothing is configured, given what this runtime can load. */
39
- export function resolveDefaultModel(rawOrtAvailable = true) {
40
- return rawOrtAvailable ? DEFAULT_TTS_MODEL_NATIVE : DEFAULT_TTS_MODEL_WASM;
41
- }
42
-
43
- // Style-vector width in a voices/*.bin file, and the max token window a single
44
- // forward pass accepts. Both are properties of the Kokoro export, and the engine
45
- // needs them to slice the voice and to chunk long text.
46
- export const STYLE_DIM = 256;
47
- export const MAX_PHONEME_TOKENS = 510;
48
-
49
- // Upper bound on one /tts request. Long text is CHUNKED rather than rejected, so
50
- // this is not a model limit — it is a fairness limit: synthesis is single-engine
51
- // and roughly realtime, so an unbounded body would hold it for minutes.
52
- export const MAX_TTS_CHARS = 5000;
53
-
54
- export const TTS_MODEL_CATALOG = [
55
- {
56
- id: 'onnx-community/Kokoro-82M-v1.0-ONNX',
57
- label: 'Kokoro 82M (v1.0)',
58
- lang: 'English (US/UK)',
59
- tier: 'balanced',
60
- arch: 'style-tts2',
61
- approxMB: 330, // fp32 on WASM; ~90 on native q8
62
- ramMB: 600,
63
- sampleRate: 24000,
64
- voices: true,
65
- note: 'Apache-2.0, 82M params. Natural voices at ~5× realtime on CPU. The default.',
66
- },
67
- {
68
- id: 'onnx-community/Kokoro-82M-v1.1-zh-ONNX',
69
- label: 'Kokoro 82M (v1.1, Chinese)',
70
- lang: 'Chinese + English',
71
- tier: 'balanced',
72
- arch: 'style-tts2',
73
- approxMB: 330,
74
- ramMB: 600,
75
- sampleRate: 24000,
76
- voices: true,
77
- note: 'The Mandarin-tuned Kokoro. Same engine and voice mechanism as v1.0.',
78
- },
79
- {
80
- // The one model here BUILT for cloning. Its Mimi encoder turns a sample into a
81
- // conditioning the model generates from directly, rather than borrowing a
82
- // voice print from a space it was not trained on — which is why it reproduces
83
- // a speaker where SpeechT5 merely produces a consistent stranger. Also the
84
- // fastest: measured 8-9x realtime at int8, against Kokoro's 2.1x.
85
- id: 'kyutai/pocket-tts',
86
- label: 'Pocket TTS — clone your voice',
87
- lang: 'English',
88
- tier: 'accurate',
89
- arch: 'pocket-tts',
90
- bundle: 'english_2026-04',
91
- approxMB: 146,
92
- ramMB: 700,
93
- sampleRate: 24000,
94
- voices: true, // eight built-in speakers (optional 52 MB voices.bin)
95
- customVoices: true, // …and it can speak as YOU
96
- recommended: true,
97
- // Raw onnxruntime, which the standalone binary cannot provide.
98
- requiresNative: true,
99
- note: 'Kyutai Pocket TTS (MIT code, CC-BY-4.0 weights). Eight built-in voices (downloaded with the model), and it can clone yours. Fastest model here. ~200 MB. Needs the npm gateway.',
100
- },
101
- {
102
- id: 'Xenova/speecht5_tts',
103
- label: 'SpeechT5 — your own voice',
104
- lang: 'English',
105
- tier: 'custom',
106
- arch: 'speecht5',
107
- // PINNED to fp32, and not as a preference. At the runtime default (q8 on
108
- // native) this model renders about half of all speaker embeddings as
109
- // near-silence — measured: 91-92% of samples under the noise floor, where the
110
- // same embeddings at fp32 produce clean speech at ~47% silence, which is just
111
- // the pauses between words. The quantization is destroying the speaker
112
- // conditioning, and the failure looks exactly like "voice cloning does not
113
- // work" rather than "the precision is wrong".
114
- dtype: 'fp32',
115
- approxMB: 190, // plus the ~50 MB HiFi-GAN vocoder it needs
116
- ramMB: 500,
117
- sampleRate: 16000,
118
- voices: false, // no built-in voices…
119
- customVoices: true, // …but it is the ONE model here that can use yours
120
- note: 'Speaks using a voice you record — but it will NOT sound like you. It borrows pitch and timbre in a general way and produces a consistent voice of its own. Kokoro sounds better if you do not need a personal voice.',
121
- },
122
- {
123
- // One MMS entry so the second architecture is DISCOVERABLE from the list rather
124
- // than only findable by search. The rest of the family (~1000 languages) is
125
- // exactly what the search box is for — listing them all here would be a menu,
126
- // not a catalog.
127
- id: 'Xenova/mms-tts-hin',
128
- label: 'MMS TTS — Hindi',
129
- lang: 'Hindi (हिन्दी)',
130
- tier: 'light',
131
- arch: 'vits',
132
- approxMB: 40,
133
- ramMB: 200,
134
- sampleRate: 16000,
135
- voices: false,
136
- note: 'Tiny single-speaker VITS. Meta\u2019s MMS covers ~1000 languages — search "mms-tts" for yours.',
137
- },
138
- ];
139
-
140
- // Voice prefix → the language phonemizer must use for G2P. First letter = language,
141
- // second = gender (f/m). Only the English families are listed: the other Kokoro
142
- // voices (es/fr/hi/it/ja/pt/zh) need misaki-class G2P, which has no dependency-free
143
- // JS port — shipping them against an English phonemizer would produce confident
144
- // gibberish, which is worse than not offering them.
145
- const VOICE_LANG = { a: 'en-us', b: 'en-gb' };
146
-
147
- // `grade` is Kokoro's own published quality rating for the voice. Ordered best-first
148
- // so the picker's default ordering is already the useful one.
149
- export const TTS_VOICES = [
150
- { id: 'af_heart', label: 'Heart (US, female)', lang: 'en-us', gender: 'female', grade: 'A' },
151
- { id: 'af_bella', label: 'Bella (US, female)', lang: 'en-us', gender: 'female', grade: 'A-' },
152
- { id: 'bf_emma', label: 'Emma (UK, female)', lang: 'en-gb', gender: 'female', grade: 'B-' },
153
- { id: 'af_nicole', label: 'Nicole (US, female)', lang: 'en-us', gender: 'female', grade: 'B-', note: 'Recorded close-mic — best on headphones.' },
154
- { id: 'af_aoede', label: 'Aoede (US, female)', lang: 'en-us', gender: 'female', grade: 'C+' },
155
- { id: 'af_kore', label: 'Kore (US, female)', lang: 'en-us', gender: 'female', grade: 'C+' },
156
- { id: 'af_sarah', label: 'Sarah (US, female)', lang: 'en-us', gender: 'female', grade: 'C+' },
157
- { id: 'am_michael', label: 'Michael (US, male)', lang: 'en-us', gender: 'male', grade: 'C+' },
158
- { id: 'am_fenrir', label: 'Fenrir (US, male)', lang: 'en-us', gender: 'male', grade: 'C+' },
159
- { id: 'am_puck', label: 'Puck (US, male)', lang: 'en-us', gender: 'male', grade: 'C+' },
160
- { id: 'af_nova', label: 'Nova (US, female)', lang: 'en-us', gender: 'female', grade: 'C' },
161
- { id: 'af_alloy', label: 'Alloy (US, female)', lang: 'en-us', gender: 'female', grade: 'C' },
162
- { id: 'bf_isabella', label: 'Isabella (UK, female)', lang: 'en-gb', gender: 'female', grade: 'C' },
163
- { id: 'bm_george', label: 'George (UK, male)', lang: 'en-gb', gender: 'male', grade: 'C' },
164
- { id: 'bm_fable', label: 'Fable (UK, male)', lang: 'en-gb', gender: 'male', grade: 'C' },
165
- ];
166
-
167
- // Which engine drives a model — the same dispatch seam stt-models.js has for
168
- // 'whisper' (transformers.js pipeline) vs 'parakeet-tdt' (raw onnxruntime, its own
169
- // decode loop). 'style-tts2' = Kokoro through transformers.js.
170
- //
171
- // The seam exists because the obvious second engine is already on the table:
172
- // Kyutai's Pocket TTS (MIT code, CC-BY-4.0 weights, ~100M params, streams a first
173
- // chunk in ~200 ms, six languages, and — unlike Kokoro — CLONES a voice from a
174
- // sample). It is not listed here because it is not implemented: its ONNX form is a
175
- // five-graph bundle (text_conditioner + flow_lm_main + flow_lm_flow + mimi
176
- // encoder/decoder) needing a hand-written flow-matching decode loop, from a
177
- // THIRD-PARTY re-export of a gated checkpoint. That is a parakeet-engine-sized
178
- // piece of work, not a catalog entry — so the seam is here and the engine is not.
179
- export function ttsModelEngine(id) {
180
- return ttsModel(id)?.arch || 'style-tts2';
181
- }
182
-
183
- // The bundle a pocket-tts catalog entry uses (its language pack).
184
- export function ttsModelBundle(id) {
185
- return ttsModel(id)?.bundle || null;
186
- }
187
-
188
- // Does this catalog entry have selectable voices? Kokoro picks one from a style
189
- // bank; VITS/MMS is single-speaker. Unknown (a searched model) resolves at load.
190
- export function ttsModelHasVoices(id) {
191
- const m = ttsModel(id);
192
- return m ? m.voices !== false : true;
193
- }
194
-
195
- // Can it speak in a voice the user recorded? Only SpeechT5 takes a speaker
196
- // embedding — the other two are conditioned on something fixed.
197
- export function ttsModelHasCustomVoices(id) {
198
- return ttsModel(id)?.customVoices === true;
199
- }
200
-
201
- /** Does this model need the native onnxruntime (i.e. not usable in the binary)? */
202
- export function ttsModelRequiresNative(id) {
203
- return ttsModel(id)?.requiresNative === true;
204
- }
205
-
206
- export function ttsModel(id) {
207
- return TTS_MODEL_CATALOG.find((m) => m.id === id) || null;
208
- }
209
- export function isKnownTtsModel(id) {
210
- return TTS_MODEL_CATALOG.some((m) => m.id === id);
211
- }
212
- export function ttsModelDtype(id) {
213
- return ttsModel(id)?.dtype || null;
214
- }
215
- export function ttsVoice(id) {
216
- return TTS_VOICES.find((v) => v.id === id) || null;
217
- }
218
- export function isKnownVoice(id) {
219
- return TTS_VOICES.some((v) => v.id === id);
220
- }
221
-
222
- // A voice id becomes a FILENAME (voices/<id>.bin) and a phonemizer language lookup,
223
- // so it is validated by shape as well as by catalog membership — belt and braces
224
- // against a traversal reaching the fetch/join even if the catalog check is ever
225
- // refactored away. Kokoro ids are strictly `<lang><gender>_<name>`.
226
- export function isValidVoiceId(id) {
227
- return /^[a-z]{2}_[a-z0-9]+$/.test(String(id || ''));
228
- }
229
-
230
- // The phonemizer language for a voice — an American voice reading British phonemes
231
- // (or vice versa) is audibly wrong, so G2P follows the voice, not the request.
232
- export function voiceLang(id) {
233
- return VOICE_LANG[String(id || '')[0]] || 'en-us';
234
- }
235
-
236
- // Same strict `org/name` shape as isValidCustomSttId — no traversal.
237
- export function isValidCustomTtsId(id) {
238
- const s = String(id || '');
239
- return /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(s) && !s.includes('..');
240
- }
241
-
242
- // Selectable precisions. Same ids as the STT picker (they are transformers.js
243
- // dtypes, not a whisper concept) but the notes are about synthesis speed.
244
- export const TTS_DTYPES = [
245
- { id: 'auto', label: 'Auto (recommended)', note: 'q8 on the native gateway, fp32 on the WASM binary.' },
246
- { id: 'q8', label: 'q8 — fast, balanced', note: 'Int8. Best speed/quality trade-off (native default).' },
247
- { id: 'q4', label: 'q4 — smallest & fastest', note: '4-bit. Least memory; audibly rougher.' },
248
- { id: 'fp16', label: 'fp16 — more accurate', note: 'Half precision. Larger, a bit slower.' },
249
- { id: 'fp32', label: 'fp32 — best quality (slow)', note: 'Full precision. The only one that loads on the WASM binary.' },
250
- ];
251
-
252
- export function isValidTtsDtype(d) {
253
- return TTS_DTYPES.some((x) => x.id === d);
254
- }
1
+ const r="kyutai/pocket-tts",n="onnx-community/Kokoro-82M-v1.0-ONNX",c=n,u="af_heart",i=["alba","azelma","cosette","eponine","fantine","javert","jean","marius"],m="alba";function g(e){return i.includes(String(e||""))}function p(e=!0){return e?r:n}const f=256,b=510,h=5e3,o=[{id:"onnx-community/Kokoro-82M-v1.0-ONNX",label:"Kokoro 82M (v1.0)",lang:"English (US/UK)",tier:"balanced",arch:"style-tts2",approxMB:330,ramMB:600,sampleRate:24e3,voices:!0,note:"Apache-2.0, 82M params. Natural voices at ~5× realtime on CPU. The default."},{id:"onnx-community/Kokoro-82M-v1.1-zh-ONNX",label:"Kokoro 82M (v1.1, Chinese)",lang:"Chinese + English",tier:"balanced",arch:"style-tts2",approxMB:330,ramMB:600,sampleRate:24e3,voices:!0,note:"The Mandarin-tuned Kokoro. Same engine and voice mechanism as v1.0."},{id:"kyutai/pocket-tts",label:"Pocket TTS — clone your voice",lang:"English",tier:"accurate",arch:"pocket-tts",bundle:"english_2026-04",approxMB:146,ramMB:700,sampleRate:24e3,voices:!0,customVoices:!0,recommended:!0,requiresNative:!0,note:"Kyutai Pocket TTS (MIT code, CC-BY-4.0 weights). Eight built-in voices (downloaded with the model), and it can clone yours. Fastest model here. ~200 MB. Needs the npm gateway."},{id:"Xenova/speecht5_tts",label:"SpeechT5 — your own voice",lang:"English",tier:"custom",arch:"speecht5",dtype:"fp32",approxMB:190,ramMB:500,sampleRate:16e3,voices:!1,customVoices:!0,note:"Speaks using a voice you record — but it will NOT sound like you. It borrows pitch and timbre in a general way and produces a consistent voice of its own. Kokoro sounds better if you do not need a personal voice."},{id:"Xenova/mms-tts-hin",label:"MMS TTS — Hindi",lang:"Hindi (हिन्दी)",tier:"light",arch:"vits",approxMB:40,ramMB:200,sampleRate:16e3,voices:!1,note:'Tiny single-speaker VITS. Meta’s MMS covers ~1000 languages — search "mms-tts" for yours.'}],s={a:"en-us",b:"en-gb"},l=[{id:"af_heart",label:"Heart (US, female)",lang:"en-us",gender:"female",grade:"A"},{id:"af_bella",label:"Bella (US, female)",lang:"en-us",gender:"female",grade:"A-"},{id:"bf_emma",label:"Emma (UK, female)",lang:"en-gb",gender:"female",grade:"B-"},{id:"af_nicole",label:"Nicole (US, female)",lang:"en-us",gender:"female",grade:"B-",note:"Recorded close-mic — best on headphones."},{id:"af_aoede",label:"Aoede (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"af_kore",label:"Kore (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"af_sarah",label:"Sarah (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"am_michael",label:"Michael (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"am_fenrir",label:"Fenrir (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"am_puck",label:"Puck (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"af_nova",label:"Nova (US, female)",lang:"en-us",gender:"female",grade:"C"},{id:"af_alloy",label:"Alloy (US, female)",lang:"en-us",gender:"female",grade:"C"},{id:"bf_isabella",label:"Isabella (UK, female)",lang:"en-gb",gender:"female",grade:"C"},{id:"bm_george",label:"George (UK, male)",lang:"en-gb",gender:"male",grade:"C"},{id:"bm_fable",label:"Fable (UK, male)",lang:"en-gb",gender:"male",grade:"C"}];function M(e){return t(e)?.arch||"style-tts2"}function T(e){return t(e)?.bundle||null}function S(e){const a=t(e);return a?a.voices!==!1:!0}function _(e){return t(e)?.customVoices===!0}function x(e){return t(e)?.requiresNative===!0}function t(e){return o.find(a=>a.id===e)||null}function v(e){return o.some(a=>a.id===e)}function y(e){return t(e)?.dtype||null}function E(e){return l.find(a=>a.id===e)||null}function C(e){return l.some(a=>a.id===e)}function U(e){return/^[a-z]{2}_[a-z0-9]+$/.test(String(e||""))}function A(e){return s[String(e||"")[0]]||"en-us"}function k(e){const a=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(a)&&!a.includes("..")}const d=[{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; audibly rougher."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — best quality (slow)",note:"Full precision. The only one that loads on the WASM binary."}];function K(e){return d.some(a=>a.id===e)}export{m as DEFAULT_POCKET_VOICE,c as DEFAULT_TTS_MODEL,r as DEFAULT_TTS_MODEL_NATIVE,n as DEFAULT_TTS_MODEL_WASM,u as DEFAULT_TTS_VOICE,b as MAX_PHONEME_TOKENS,h as MAX_TTS_CHARS,i as POCKET_VOICES,f as STYLE_DIM,d as TTS_DTYPES,o as TTS_MODEL_CATALOG,l as TTS_VOICES,v as isKnownTtsModel,C as isKnownVoice,g as isPocketVoice,k as isValidCustomTtsId,K as isValidTtsDtype,U as isValidVoiceId,p as resolveDefaultModel,t as ttsModel,T as ttsModelBundle,y as ttsModelDtype,M as ttsModelEngine,_ as ttsModelHasCustomVoices,S as ttsModelHasVoices,x as ttsModelRequiresNative,E as ttsVoice,A as voiceLang};
package/src/tts-remote.js CHANGED
@@ -1,109 +1 @@
1
- // Remote text-to-speech destinations — ElevenLabs, OpenAI, or anything that speaks
2
- // the OpenAI /audio/speech shape (Groq, a local server, an OpenAI-compatible proxy).
3
- //
4
- // TWO RULES, and they are the whole reason this is a separate module from
5
- // tts-engine.js rather than a branch inside it.
6
- //
7
- // 1. NO KEY LIVES HERE. config.js says it outright — "the gateway forwards the
8
- // CLIENT's own auth header upstream (it stores no provider keys)" — and a TTS
9
- // destination is not the place to break that. The caller sends its own
10
- // Authorization (or xi-api-key) and we pass it through. Config holds the ROUTE.
11
- //
12
- // 2. THE PRIVACY DECISION INVERTS. Local synthesis speaks restored text because the
13
- // words never leave the machine; there is nothing to protect them from. The
14
- // moment the destination is remote, the text IS leaving, to a vendor, and every
15
- // other egress in this gateway is redacted first. So remote synthesis redacts by
16
- // default.
17
- //
18
- // That trade is real and cannot be papered over: audio cannot be un-redacted the
19
- // way a text completion can, so a redacted remote voice literally says
20
- // "PERSON_1". The honest options are (a) placeholders spoken aloud, or (b) real
21
- // PII sent to a vendor — and the user picks, per destination, with `redact`. The
22
- // default is the safe one and the choice is logged via onEgress, so sending real
23
- // names to ElevenLabs is something someone DID, not something that happened.
24
-
25
- import { secureFetch } from './secure-fetch.js';
26
- import { redactSegments, segment } from './redact.js';
27
-
28
- export const TTS_PROVIDERS = ['local', 'openai', 'elevenlabs'];
29
-
30
- export function isValidTtsProvider(p) {
31
- return TTS_PROVIDERS.includes(String(p || ''));
32
- }
33
-
34
- /** The configured destination, or null when synthesis is local (the default). */
35
- export function ttsDestination(cfg = {}) {
36
- const t = cfg.tts || {};
37
- const kind = t.provider || 'local';
38
- if (kind === 'local' || !isValidTtsProvider(kind)) return null;
39
- const r = t.remote || {};
40
- return {
41
- kind,
42
- baseUrl: String(r.baseUrl || (kind === 'elevenlabs' ? 'https://api.elevenlabs.io/v1' : 'https://api.openai.com/v1')).replace(/\/+$/, ''),
43
- model: r.model || (kind === 'elevenlabs' ? 'eleven_multilingual_v2' : 'tts-1'),
44
- voice: r.voice || (kind === 'elevenlabs' ? '21m00Tcm4TlvDq8ikWAM' : 'alloy'),
45
- // Undefined means "not set", which must read as ON — an absent flag is never
46
- // permission to send someone's name to a vendor.
47
- redact: r.redact !== false,
48
- };
49
- }
50
-
51
- // A remote voice id lands in a URL PATH for ElevenLabs, so it is shape-checked
52
- // rather than trusted: no slashes, no traversal, no query smuggling.
53
- export function isValidRemoteVoice(v) {
54
- return /^[A-Za-z0-9_-]{1,64}$/.test(String(v || ''));
55
- }
56
-
57
- /**
58
- * Synthesize remotely. Returns { audio: Buffer, contentType, redacted } — `redacted`
59
- * is the count of values replaced, so the caller can report what actually left.
60
- *
61
- * @param {{dest: any, text: string, voice?: string, speed?: number, auth?: string,
62
- * redaction?: any, isPro?: boolean, onEgress?: Function, fetchImpl?: Function}} opts
63
- */
64
- export async function synthesizeRemote({ dest, text, voice, speed = 1, auth, redaction, isPro = true, onEgress = null, fetchImpl = null } = {}) {
65
- if (!dest) throw new Error('no remote TTS destination configured');
66
- const pick = voice || dest.voice;
67
- if (!isValidRemoteVoice(pick)) throw new Error(`invalid remote voice id: ${pick}`);
68
-
69
- // Redact BEFORE anything is built, so there is no path where the raw string
70
- // reaches a request body by accident.
71
- let out = String(text);
72
- let redacted = 0;
73
- if (dest.redact && redaction) {
74
- const box = { text: out };
75
- const r = await redactSegments([segment(() => box.text, (v) => { box.text = v; })], redaction, { isPro, onEgress });
76
- out = box.text;
77
- redacted = r?.count || 0;
78
- }
79
-
80
- const fetcher = fetchImpl || secureFetch;
81
- const headers = { 'Content-Type': 'application/json' };
82
- let url, body;
83
- if (dest.kind === 'elevenlabs') {
84
- url = `${dest.baseUrl}/text-to-speech/${encodeURIComponent(pick)}`;
85
- body = { text: out, model_id: dest.model };
86
- // ElevenLabs uses its own header. Accept either form from the caller so a
87
- // generic OpenAI client can drive it too.
88
- const key = stripBearer(auth);
89
- if (key) headers['xi-api-key'] = key;
90
- } else {
91
- url = `${dest.baseUrl}/audio/speech`;
92
- body = { model: dest.model, input: out, voice: pick, response_format: 'wav', speed };
93
- if (auth) headers.Authorization = auth.startsWith('Bearer ') ? auth : `Bearer ${auth}`;
94
- }
95
-
96
- const res = await fetcher(url, { method: 'POST', headers, body: JSON.stringify(body) });
97
- if (!res.ok) {
98
- let detail = `HTTP ${res.status}`;
99
- try { detail = (await res.text()).slice(0, 300) || detail; } catch { /* no body */ }
100
- throw new Error(`remote tts failed: ${detail}`);
101
- }
102
- const audio = Buffer.from(await res.arrayBuffer());
103
- return { audio, contentType: res.headers.get('content-type') || 'audio/mpeg', redacted };
104
- }
105
-
106
- function stripBearer(a) {
107
- const s = String(a || '').trim();
108
- return s.toLowerCase().startsWith('bearer ') ? s.slice(7).trim() : s;
109
- }
1
+ import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as w,segment as T}from"./redact.js";const S=["local","openai","elevenlabs"];function $(e){return S.includes(String(e||""))}function E(e={}){const o=e.tts||{},r=o.provider||"local";if(r==="local"||!$(r))return null;const i=o.remote||{};return{kind:r,baseUrl:String(i.baseUrl||(r==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:i.model||(r==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:i.voice||(r==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:i.redact!==!1}}function k(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}async function P({dest:e,text:o,voice:r,speed:i=1,auth:n,redaction:d,isPro:f=!0,onEgress:v=null,fetchImpl:b=null}={}){if(!e)throw new Error("no remote TTS destination configured");const l=r||e.voice;if(!k(l))throw new Error(`invalid remote voice id: ${l}`);let s=String(o),u=0;if(e.redact&&d){const t={text:s},h=await w([T(()=>t.text,y=>{t.text=y})],d,{isPro:f,onEgress:v});s=t.text,u=h?.count||0}const x=b||g,c={"Content-Type":"application/json"};let m,p;if(e.kind==="elevenlabs"){m=`${e.baseUrl}/text-to-speech/${encodeURIComponent(l)}`,p={text:s,model_id:e.model};const t=_(n);t&&(c["xi-api-key"]=t)}else m=`${e.baseUrl}/audio/speech`,p={model:e.model,input:s,voice:l,response_format:"wav",speed:i},n&&(c.Authorization=n.startsWith("Bearer ")?n:`Bearer ${n}`);const a=await x(m,{method:"POST",headers:c,body:JSON.stringify(p)});if(!a.ok){let t=`HTTP ${a.status}`;try{t=(await a.text()).slice(0,300)||t}catch{}throw new Error(`remote tts failed: ${t}`)}return{audio:Buffer.from(await a.arrayBuffer()),contentType:a.headers.get("content-type")||"audio/mpeg",redacted:u}}function _(e){const o=String(e||"").trim();return o.toLowerCase().startsWith("bearer ")?o.slice(7).trim():o}export{S as TTS_PROVIDERS,k as isValidRemoteVoice,$ as isValidTtsProvider,P as synthesizeRemote,E as ttsDestination};
@@ -1,78 +1 @@
1
- // Which voice a /tts request actually speaks in — decided in ONE place, with every
2
- // dependency injected so the table below can be tested without loading a model.
3
- //
4
- // The rule that shapes this: a saved clone is a CHOICE, never a default. Someone's
5
- // own voice print must not start speaking because the config was empty, named a
6
- // voice from another model, or pointed at a voice since deleted. A model with
7
- // built-in speakers (Pocket) falls back to one of those; only SpeechT5, which has
8
- // no built-ins, has nothing to fall back to but a recording.
9
- //
10
- // A voice named EXPLICITLY in the request never falls back — it succeeds or fails
11
- // loudly, so a caller that asked for a specific voice can trust what it got.
12
- //
13
- // Returns either { ok: true, voice, customId, speakerEmbedding }
14
- // or { ok: false, status, type, message }.
15
-
16
- export function resolveTtsVoice({
17
- requested = null, // body.voice, or null when the caller left it to the config
18
- configured, // the voice the request would use absent an override
19
- engine, // { isPocket(), supportsCustomVoices(), supportsVoices(), arch() }
20
- voices, // { parseCustomVoice, getVoice, listVoices, getPocketVoice }
21
- isPocketVoice,
22
- isKnownVoice,
23
- isValidVoiceId,
24
- defaultVoice, // Kokoro's default
25
- defaultPocketVoice, // Pocket's built-in default
26
- }) {
27
- const voice = requested || configured;
28
- const pocket = engine.isPocket();
29
- let customId = voices.parseCustomVoice(voice);
30
-
31
- // A Pocket built-in speaker is a NAME, not an embedding, so it is recognised
32
- // before the custom-voice path — which would otherwise demand a recording for a
33
- // model that ships eight voices of its own.
34
- if (pocket && isPocketVoice(voice)) return { ok: true, voice, customId: null, speakerEmbedding: null };
35
-
36
- if (engine.supportsCustomVoices()) {
37
- let rec = customId ? voices.getVoice(customId) : null;
38
- if (!rec && !requested) {
39
- // Nothing valid was configured and nothing was asked for.
40
- if (pocket) return { ok: true, voice: defaultPocketVoice, customId: null, speakerEmbedding: null };
41
- const saved = voices.listVoices();
42
- if (saved.length) { customId = saved[0].id; rec = voices.getVoice(customId); }
43
- }
44
- if (!rec) {
45
- return customId
46
- ? { ok: false, status: 404, type: 'bad_voice', message: 'no such saved voice' }
47
- : { ok: false, status: 400, type: 'bad_voice', message: 'this model speaks in a voice you record — add one in Settings → Text-to-speech' };
48
- }
49
- // Which print to hand over depends on the engine: Pocket TTS takes its Mimi
50
- // conditioning, SpeechT5 the 512-d x-vector. A voice saved before the pocket
51
- // bundle existed has only the latter.
52
- let speakerEmbedding;
53
- if (pocket) {
54
- speakerEmbedding = voices.getPocketVoice(customId);
55
- if (!speakerEmbedding) {
56
- return { ok: false, status: 409, type: 'voice_kind_missing', message: 'this voice was saved without a Pocket TTS conditioning — record it again with Pocket TTS selected' };
57
- }
58
- } else {
59
- speakerEmbedding = rec.vec;
60
- }
61
- return { ok: true, voice: `custom:${customId}`, customId, speakerEmbedding };
62
- }
63
-
64
- if (customId) {
65
- // Explicitly asked for a recorded voice this model cannot use — say so.
66
- // Inherited from config, though, it is just a stale setting, and refusing to
67
- // speak at all is a worse answer than speaking in the default voice.
68
- if (requested) {
69
- return { ok: false, status: 409, type: 'voice_unsupported', message: `the active model (${engine.arch()}) cannot use a recorded voice — switch to SpeechT5` };
70
- }
71
- return { ok: true, voice: defaultVoice, customId: null, speakerEmbedding: null };
72
- }
73
- if (pocket && !isPocketVoice(voice)) return { ok: true, voice: defaultPocketVoice, customId: null, speakerEmbedding: null };
74
- if (engine.supportsVoices() && !pocket && !(isKnownVoice(voice) && isValidVoiceId(voice))) {
75
- return { ok: false, status: 400, type: 'bad_voice', message: 'unknown or invalid voice' };
76
- }
77
- return { ok: true, voice, customId: null, speakerEmbedding: null };
78
- }
1
+ function v({requested:c=null,configured:d,engine:i,voices:s,isPocketVoice:r,isKnownVoice:k,isValidVoiceId:m,defaultVoice:p,defaultPocketVoice:a}){const t=c||d,o=i.isPocket();let e=s.parseCustomVoice(t);if(o&&r(t))return{ok:!0,voice:t,customId:null,speakerEmbedding:null};if(i.supportsCustomVoices()){let u=e?s.getVoice(e):null;if(!u&&!c){if(o)return{ok:!0,voice:a,customId:null,speakerEmbedding:null};const l=s.listVoices();l.length&&(e=l[0].id,u=s.getVoice(e))}if(!u)return e?{ok:!1,status:404,type:"bad_voice",message:"no such saved voice"}:{ok:!1,status:400,type:"bad_voice",message:"this model speaks in a voice you record — add one in Settings → Text-to-speech"};let n;if(o){if(n=s.getPocketVoice(e),!n)return{ok:!1,status:409,type:"voice_kind_missing",message:"this voice was saved without a Pocket TTS conditioning — record it again with Pocket TTS selected"}}else n=u.vec;return{ok:!0,voice:`custom:${e}`,customId:e,speakerEmbedding:n}}return e?c?{ok:!1,status:409,type:"voice_unsupported",message:`the active model (${i.arch()}) cannot use a recorded voice — switch to SpeechT5`}:{ok:!0,voice:p,customId:null,speakerEmbedding:null}:o&&!r(t)?{ok:!0,voice:a,customId:null,speakerEmbedding:null}:i.supportsVoices()&&!o&&!(k(t)&&m(t))?{ok:!1,status:400,type:"bad_voice",message:"unknown or invalid voice"}:{ok:!0,voice:t,customId:null,speakerEmbedding:null}}export{v as resolveTtsVoice};