wicked-crew 0.18.13 → 0.18.15

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 (113) hide show
  1. package/README.md +1 -1
  2. package/dist/api/chat-jobs.d.ts.map +1 -1
  3. package/dist/api/chat-jobs.js +20 -14
  4. package/dist/api/chat-jobs.js.map +1 -1
  5. package/dist/api/chat-proposals.d.ts.map +1 -1
  6. package/dist/api/chat-proposals.js +4 -2
  7. package/dist/api/chat-proposals.js.map +1 -1
  8. package/dist/api/mcp.d.ts +1 -0
  9. package/dist/api/mcp.d.ts.map +1 -1
  10. package/dist/api/mcp.js +16 -0
  11. package/dist/api/mcp.js.map +1 -1
  12. package/dist/api/routes.d.ts +2 -0
  13. package/dist/api/routes.d.ts.map +1 -1
  14. package/dist/api/routes.js +2 -1
  15. package/dist/api/routes.js.map +1 -1
  16. package/dist/apps/exec/sources.d.ts.map +1 -1
  17. package/dist/apps/exec/sources.js +7 -1
  18. package/dist/apps/exec/sources.js.map +1 -1
  19. package/dist/apps-server/server/lib/bundle/server.mjs +1854 -1840
  20. package/dist/cli/index.js +2 -2
  21. package/dist/cli/index.js.map +1 -1
  22. package/dist/cli/service.d.ts.map +1 -1
  23. package/dist/cli/service.js +50 -9
  24. package/dist/cli/service.js.map +1 -1
  25. package/dist/interactive/bridge-pool.d.ts +8 -2
  26. package/dist/interactive/bridge-pool.d.ts.map +1 -1
  27. package/dist/interactive/bridge-pool.js +7 -1
  28. package/dist/interactive/bridge-pool.js.map +1 -1
  29. package/dist/learn/scheduler.d.ts +1 -1
  30. package/dist/learn/scheduler.d.ts.map +1 -1
  31. package/dist/learn/scheduler.js +1 -10
  32. package/dist/learn/scheduler.js.map +1 -1
  33. package/dist/mcp/env.d.ts +30 -0
  34. package/dist/mcp/env.d.ts.map +1 -0
  35. package/dist/mcp/env.js +102 -0
  36. package/dist/mcp/env.js.map +1 -0
  37. package/dist/mcp/probe.d.ts +2 -0
  38. package/dist/mcp/probe.d.ts.map +1 -1
  39. package/dist/mcp/probe.js +1 -0
  40. package/dist/mcp/probe.js.map +1 -1
  41. package/dist/mcp/registry-store.d.ts +2 -0
  42. package/dist/mcp/registry-store.d.ts.map +1 -1
  43. package/dist/mcp/registry-store.js.map +1 -1
  44. package/dist/mcp/registry.d.ts.map +1 -1
  45. package/dist/mcp/registry.js +8 -2
  46. package/dist/mcp/registry.js.map +1 -1
  47. package/dist/mcp-inspect/routes.d.ts.map +1 -1
  48. package/dist/mcp-inspect/routes.js +2 -1
  49. package/dist/mcp-inspect/routes.js.map +1 -1
  50. package/dist/schedules/scheduler.d.ts +3 -3
  51. package/dist/schedules/scheduler.d.ts.map +1 -1
  52. package/dist/schedules/scheduler.js +4 -7
  53. package/dist/schedules/scheduler.js.map +1 -1
  54. package/dist/studio/assets/{KnowledgeGraph-BgXDoH6k.js → KnowledgeGraph-BsnkAeft.js} +1 -1
  55. package/dist/studio/assets/{index-CrcZTJjG.css → index-DsUknIuZ.css} +1 -1
  56. package/dist/studio/assets/{index-rMZ47jUD.js → index-KfQJ9Jw0.js} +292 -292
  57. package/dist/studio/editors/wicked-apps/editor.json +1 -1
  58. package/dist/studio/editors/wicked-apps/index.html +1 -1
  59. package/dist/studio/editors/wicked-deck/editor.json +1 -1
  60. package/dist/studio/editors/wicked-deck/index.html +1 -1
  61. package/dist/studio/editors/wicked-doc/editor.json +1 -1
  62. package/dist/studio/editors/wicked-doc/index.html +1 -1
  63. package/dist/studio/editors/wicked-insights/editor.json +1 -1
  64. package/dist/studio/editors/wicked-insights/index.html +1 -1
  65. package/dist/studio/editors/wicked-page/editor.json +1 -1
  66. package/dist/studio/editors/wicked-page/index.html +1 -1
  67. package/dist/studio/editors/wicked-video/editor.json +1 -1
  68. package/dist/studio/editors/wicked-video/index.html +1 -1
  69. package/dist/studio/index.html +2 -2
  70. package/dist/studio/testid-inventory.json +1 -1
  71. package/dist/voice/routes.d.ts +16 -0
  72. package/dist/voice/routes.d.ts.map +1 -1
  73. package/dist/voice/routes.js +54 -0
  74. package/dist/voice/routes.js.map +1 -1
  75. package/dist/voice/service.d.ts +1 -1
  76. package/dist/voice/service.d.ts.map +1 -1
  77. package/dist/voice/service.js.map +1 -1
  78. package/dist/voice/tts-manifest.d.ts +37 -0
  79. package/dist/voice/tts-manifest.d.ts.map +1 -0
  80. package/dist/voice/tts-manifest.js +40 -0
  81. package/dist/voice/tts-manifest.js.map +1 -0
  82. package/dist/voice/tts.d.ts +214 -0
  83. package/dist/voice/tts.d.ts.map +1 -0
  84. package/dist/voice/tts.js +821 -0
  85. package/dist/voice/tts.js.map +1 -0
  86. package/dist/workflow-catalog/catalog-data-v2.d.ts.map +1 -1
  87. package/dist/workflow-catalog/catalog-data-v2.js +2 -0
  88. package/dist/workflow-catalog/catalog-data-v2.js.map +1 -1
  89. package/endpoint-manifest.json +64 -1
  90. package/package.json +5 -4
  91. package/voice-locks/darwin-arm64-cp310.txt +107 -0
  92. package/voice-locks/darwin-arm64-cp311.txt +118 -0
  93. package/voice-locks/darwin-arm64-cp312.txt +112 -0
  94. package/voice-locks/darwin-arm64-cp313.txt +112 -0
  95. package/voice-locks/darwin-arm64-cp314.txt +112 -0
  96. package/voice-locks/darwin-arm64-cp39.txt +102 -0
  97. package/voice-locks/darwin-x64-cp310.txt +107 -0
  98. package/voice-locks/darwin-x64-cp311.txt +124 -0
  99. package/voice-locks/darwin-x64-cp312.txt +118 -0
  100. package/voice-locks/darwin-x64-cp313.txt +118 -0
  101. package/voice-locks/darwin-x64-cp39.txt +102 -0
  102. package/voice-locks/linux-arm64-cp310.txt +107 -0
  103. package/voice-locks/linux-arm64-cp311.txt +118 -0
  104. package/voice-locks/linux-arm64-cp312.txt +112 -0
  105. package/voice-locks/linux-arm64-cp313.txt +112 -0
  106. package/voice-locks/linux-arm64-cp314.txt +112 -0
  107. package/voice-locks/linux-arm64-cp39.txt +102 -0
  108. package/voice-locks/linux-x64-cp310.txt +107 -0
  109. package/voice-locks/linux-x64-cp311.txt +118 -0
  110. package/voice-locks/linux-x64-cp312.txt +112 -0
  111. package/voice-locks/linux-x64-cp313.txt +112 -0
  112. package/voice-locks/linux-x64-cp314.txt +112 -0
  113. package/voice-locks/linux-x64-cp39.txt +102 -0
@@ -0,0 +1,821 @@
1
+ /**
2
+ * TEXT TO SPEECH on THIS machine (DES studio#1140, slice 1): a consented, checksummed install of the piper engine
3
+ * and two licence-cleared voices, beside the whisper model in the voice cache dir (`WICKED_CREW_VOICE_DIR`, outside
4
+ * the state home), and a local synthesis that sends nothing off the machine. The text is never logged or audited.
5
+ *
6
+ * - Engine: a venv built with the machine's Python, then `pip install --require-hashes --no-deps -r <lock>` from
7
+ * PyPI only, from the lock committed for this (OS, arch, CPython minor) in `voice-locks/`. The venv is built in a
8
+ * temp dir and renamed into place; any failure removes it. Native Windows and CPython outside 3.9 to 3.14 are
9
+ * unsupported, and said so.
10
+ * - Voices: only the manifest's (tts-manifest.ts); each file is fetched to a `.part`, held to its sha256 and size,
11
+ * and a mismatch keeps nothing.
12
+ * - Synthesis: `<venv>/bin/python -I -m piper -m <onnx> -c <json> -f <temp.wav>`, argv only, the text as ONE line on
13
+ * stdin (piper parses argv with parse_known_args, so text there could be read as an option).
14
+ * - Every Python launch runs isolated (`-I`: no current directory or user site on sys.path, PYTHON* ignored) with the
15
+ * voice dir as its cwd, never the daemon's. A child runs in its own process group; a timeout or cancel kills the
16
+ * group and the call settles only when the child has closed. A child's stderr never reaches an error body.
17
+ */
18
+ import { spawn as nodeSpawn } from 'node:child_process';
19
+ import { createHash, randomBytes } from 'node:crypto';
20
+ import { createWriteStream, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
21
+ import { platform as osPlatform, release as osRelease } from 'node:os';
22
+ import { basename, dirname, join, resolve } from 'node:path';
23
+ import { Readable, Transform } from 'node:stream';
24
+ import { StringDecoder } from 'node:string_decoder';
25
+ import { pipeline } from 'node:stream/promises';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { childEnvWithBootEstateDb } from '../core/governance-store.js';
28
+ import { TTS_ENGINE, TTS_VOICES, TTS_VOICES_SOURCE, ttsVoiceUrl } from './tts-manifest.js';
29
+ import { VoiceError } from './service.js';
30
+ /** CPython minors a lock exists for. */
31
+ export const TTS_PYTHON_MINORS = [9, 10, 11, 12, 13, 14];
32
+ /** At most this many characters of text are spoken. */
33
+ export const TTS_MAX_TEXT_CHARS = 2000;
34
+ /** One synthesis that runs longer than this is killed. */
35
+ export const TTS_TIMEOUT_MS = 30_000;
36
+ /** Piper's stdout and stderr are each kept to this much. */
37
+ export const TTS_OUTPUT_CAP_BYTES = 64 * 1024;
38
+ /** The output file is watched while piper writes and the process killed past this. */
39
+ export const TTS_MAX_WAV_BYTES = 16 * 1024 * 1024;
40
+ /** A sample's checksum sidecar holds one sha256 hex line (64-65 bytes); anything larger is a cache miss, never read. */
41
+ export const TTS_SIDECAR_MAX_BYTES = 128;
42
+ /** The one fixed sentence of a voice sample. */
43
+ export const TTS_SAMPLE_TEXT = 'Hello, this is how I sound when I read to you.';
44
+ /** The engine install (venv + pip) is given this long. */
45
+ export const TTS_INSTALL_TIMEOUT_MS = 10 * 60_000;
46
+ /** One voice file download is given this long in all, and may go this long without a byte. */
47
+ export const TTS_DOWNLOAD_TIMEOUT_MS = 20 * 60_000;
48
+ export const TTS_DOWNLOAD_IDLE_MS = 30_000;
49
+ /** A voice download follows at most this many redirects, each of them https. */
50
+ export const TTS_MAX_REDIRECTS = 5;
51
+ /** The Python probe result is kept this long. */
52
+ export const TTS_PROBE_TTL_MS = 60_000;
53
+ /** The error text of a failed synthesis: fixed, because the child's stderr can echo the spoken text. */
54
+ const SYNTH_FAILED = 'The speech engine could not read that aloud.';
55
+ /**
56
+ * The platform baseline the locks were resolved for (`scripts/generate-voice-locks.mjs` TARGETS: macosx_14_0 and the
57
+ * manylinux_2_28 tag). Older machines are refused in status; Linux on musl has no wheels and is unsupported.
58
+ */
59
+ export const TTS_MIN_PLATFORM = { darwin: { macos: 14, darwinMajor: 23 }, linux: { glibc: [2, 28] } };
60
+ const LOCKS_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'voice-locks');
61
+ const SUPPORTED_OS = new Set(['darwin', 'linux']);
62
+ const SUPPORTED_ARCH = new Set(['arm64', 'x64']);
63
+ /** Targets inside the table above that still have no lock: onnxruntime ships no wheel for them. */
64
+ const NO_WHEEL = new Set(['darwin-x64-cp314']);
65
+ /** The lock file for an (OS, arch, CPython minor) as Node reports them; null for an unsupported combination. */
66
+ export function lockPath(os, arch, minor, locksDir = LOCKS_DIR) {
67
+ if (!SUPPORTED_OS.has(os) || !SUPPORTED_ARCH.has(arch))
68
+ return null;
69
+ if (!TTS_PYTHON_MINORS.includes(minor))
70
+ return null;
71
+ if (NO_WHEEL.has(`${os}-${arch}-cp3${minor}`))
72
+ return null;
73
+ return join(locksDir, `${os}-${arch}-cp3${minor}.txt`);
74
+ }
75
+ /**
76
+ * The text as piper reads it: control characters and line breaks gone (a break becomes a space, so words never
77
+ * fuse), runs of space collapsed, piper's `[[ ... ]]` phoneme markup neutralized so it is never interpreted (a
78
+ * space goes between every pair of adjacent brackets, so no run of any length keeps a `[[` or `]]`), at most
79
+ * {@link TTS_MAX_TEXT_CHARS} characters.
80
+ */
81
+ export function normalizeSpeakText(text) {
82
+ const flat = text
83
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ')
84
+ .replace(/ {2,}/g, ' ')
85
+ .trim()
86
+ .replace(/\[(?=\[)/g, '[ ')
87
+ .replace(/\](?=\])/g, '] ');
88
+ return flat.slice(0, TTS_MAX_TEXT_CHARS).trim();
89
+ }
90
+ /** A WAV piper wrote: RIFF/WAVE, a PCM `fmt ` chunk and a `data` chunk of non-zero duration; null when sound. */
91
+ export function ttsWavProblem(buf) {
92
+ if (buf.length < 12 || buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE')
93
+ return 'not a RIFF/WAVE file';
94
+ if (buf.readUInt32LE(4) + 8 !== buf.length)
95
+ return 'the RIFF size does not match the length of the file';
96
+ let at = 12;
97
+ let fmt = null;
98
+ let data = 0;
99
+ let dataBeforeFmt = false;
100
+ while (at + 8 <= buf.length) {
101
+ const id = buf.toString('ascii', at, at + 4);
102
+ const size = buf.readUInt32LE(at + 4);
103
+ const body = at + 8;
104
+ if (body + size > buf.length)
105
+ return `the ${id.trim() || 'unnamed'} chunk runs past the end of the file`;
106
+ if (id === 'fmt ') {
107
+ if (size < 16)
108
+ return 'the fmt chunk is too short';
109
+ if (fmt !== null)
110
+ return 'more than one fmt chunk';
111
+ if (buf.readUInt16LE(body) !== 1)
112
+ return 'not PCM audio';
113
+ const channels = buf.readUInt16LE(body + 2);
114
+ const rate = buf.readUInt32LE(body + 4);
115
+ const byteRate = buf.readUInt32LE(body + 8);
116
+ const blockAlign = buf.readUInt16LE(body + 12);
117
+ const bits = buf.readUInt16LE(body + 14);
118
+ if (channels < 1)
119
+ return 'no channels';
120
+ if (rate <= 0)
121
+ return 'a zero sample rate';
122
+ if (![8, 16, 24, 32].includes(bits))
123
+ return `${bits}-bit samples are not PCM audio`;
124
+ if (blockAlign !== (channels * bits) / 8)
125
+ return 'the block alignment does not match the channels and bit depth';
126
+ if (byteRate !== rate * blockAlign)
127
+ return 'the byte rate does not match the sample rate and block alignment';
128
+ fmt = { blockAlign };
129
+ }
130
+ else if (id === 'data') {
131
+ if (fmt === null)
132
+ dataBeforeFmt = true;
133
+ data += size;
134
+ if (fmt !== null && size % fmt.blockAlign !== 0)
135
+ return 'the data chunk is not a whole number of blocks';
136
+ }
137
+ at = body + size + (size % 2);
138
+ }
139
+ if (fmt === null)
140
+ return 'no usable fmt chunk';
141
+ if (dataBeforeFmt)
142
+ return 'the data chunk comes before the fmt chunk';
143
+ if (data === 0)
144
+ return 'no audio in the data chunk';
145
+ return null;
146
+ }
147
+ /**
148
+ * What `<cmd>` is as a CPython 3 interpreter; null when it does not run or is not CPython 3. Run isolated (`-I`) with
149
+ * `cwd` (the voice dir), so no file of the daemon's working directory is ever imported.
150
+ */
151
+ export async function probePython(cmd, cwd, options = {}) {
152
+ try {
153
+ const env = {};
154
+ for (const [k, v] of Object.entries(childEnvWithBootEstateDb(process.env)))
155
+ if (v !== undefined && !k.startsWith('PYTHON'))
156
+ env[k] = v;
157
+ const r = await runChild(cmd, ['-I', '-c', 'import sys,platform;print(platform.python_implementation(), sys.version_info[0], sys.version_info[1], sys.version.split()[0], platform.machine(), sys.executable)'], { env, timeoutMs: options.timeoutMs ?? 5000, ...(options.signal === undefined ? {} : { signal: options.signal }) }, options.spawn ?? nodeSpawn, cwd);
158
+ if (r.code !== 0)
159
+ return null;
160
+ const m = /^CPython (\d+) (\d+) (\S+) (\S+) (.+)$/m.exec(r.stdout);
161
+ if (m === null || m[1] !== '3')
162
+ return null;
163
+ return { path: m[5].trim() === '' ? cmd : m[5].trim(), version: m[3], minor: Number(m[2]), machine: m[4] };
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ }
169
+ /** Node's names (arm64, x64) for what `platform.machine()` reports; null for any other processor. */
170
+ export function archOfMachine(machine) {
171
+ const m = machine.toLowerCase();
172
+ if (m === 'arm64' || m === 'aarch64')
173
+ return 'arm64';
174
+ if (m === 'x86_64' || m === 'amd64')
175
+ return 'x64';
176
+ return null;
177
+ }
178
+ /** The glibc this Node runs on ("2.35"), null on musl or when it cannot be told. */
179
+ function glibcRuntime() {
180
+ try {
181
+ const rep = process.report;
182
+ const was = rep.excludeNetwork;
183
+ rep.excludeNetwork = true;
184
+ const header = rep.getReport().header;
185
+ rep.excludeNetwork = was;
186
+ return header?.glibcVersionRuntime ?? null;
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ /** The one-line remedy when this machine has no usable Python. */
193
+ export function pythonHint(plat) {
194
+ if (plat === 'darwin')
195
+ return 'Install Python 3.12 from python.org or with Homebrew (brew install python@3.12).';
196
+ return 'Install Python 3 with its venv module: on Debian or Ubuntu, sudo apt install python3 python3-venv.';
197
+ }
198
+ export class TtsService {
199
+ env;
200
+ plat;
201
+ fetchImpl;
202
+ spawnImpl;
203
+ exists;
204
+ probe;
205
+ release;
206
+ glibc;
207
+ now;
208
+ locksDir;
209
+ timeoutMs;
210
+ installTimeoutMs;
211
+ downloadMs;
212
+ idleMs;
213
+ maxWav;
214
+ voices;
215
+ installState = null;
216
+ inflight = null;
217
+ gen = 0;
218
+ busy = false;
219
+ waiting = [];
220
+ /** The last Python probe: kept for a minute, dropped on install and on remove. */
221
+ picked = null;
222
+ picking = null;
223
+ probeRound = 0;
224
+ probes = new Set();
225
+ dir;
226
+ /** Syntheses in flight: removal cancels them and waits for each to finish its cleanup. */
227
+ /** Bumped by every removal: a synthesis that queued before it never starts after it. */
228
+ epoch = 0;
229
+ removing = 0;
230
+ synths = new Set();
231
+ constructor(deps) {
232
+ this.dir = resolve(deps.dir);
233
+ this.env = { ...(deps.env ?? process.env) };
234
+ const python = this.env['WICKED_CREW_PYTHON'];
235
+ if (python !== undefined && /[\\/]/.test(python))
236
+ this.env['WICKED_CREW_PYTHON'] = resolve(python);
237
+ this.plat = deps.platform ?? osPlatform();
238
+ this.fetchImpl = deps.fetch ?? fetch;
239
+ this.spawnImpl = deps.spawn ?? nodeSpawn;
240
+ this.exists = deps.exists ?? existsSync;
241
+ this.probe = deps.probe ?? ((cmd, cwd, signal) => probePython(cmd, cwd, { ...(signal === undefined ? {} : { signal }), spawn: this.spawnImpl }));
242
+ this.release = deps.osRelease ?? osRelease;
243
+ this.glibc = deps.glibc ?? glibcRuntime;
244
+ this.now = deps.now ?? Date.now;
245
+ this.locksDir = deps.locksDir ?? LOCKS_DIR;
246
+ this.timeoutMs = deps.timeoutMs ?? TTS_TIMEOUT_MS;
247
+ this.installTimeoutMs = deps.installTimeoutMs ?? TTS_INSTALL_TIMEOUT_MS;
248
+ this.downloadMs = deps.downloadTimeoutMs ?? TTS_DOWNLOAD_TIMEOUT_MS;
249
+ this.idleMs = deps.downloadIdleMs ?? TTS_DOWNLOAD_IDLE_MS;
250
+ this.maxWav = deps.maxWavBytes ?? TTS_MAX_WAV_BYTES;
251
+ this.voices = deps.voices ?? TTS_VOICES;
252
+ }
253
+ root() { return join(this.dir, 'tts'); }
254
+ enginePath() { return join(this.root(), 'engine'); }
255
+ enginePython(root = this.enginePath()) { return join(root, 'bin', 'python'); }
256
+ voiceDir(id) { return join(this.root(), 'voices', id); }
257
+ samplePath(id) { return join(this.root(), 'sample', `${id}-${TTS_ENGINE.version}.wav`); }
258
+ /** Resolves when the install in flight (if any) has finished, whatever its outcome. */
259
+ installDone() { return this.inflight?.done ?? Promise.resolve(); }
260
+ /**
261
+ * The Python this machine will use: `WICKED_CREW_PYTHON`, else the first of python3, python3.14 ... python3.9 with a
262
+ * lock. Probed asynchronously and kept for a minute (`fresh` re-probes: install, remove).
263
+ */
264
+ async pickPython(fresh = false) {
265
+ if (this.removing > 0)
266
+ return { python: null, lock: null, problem: 'The speech engine is being removed.' };
267
+ if (!fresh && this.picked !== null && this.now() - this.picked.at < TTS_PROBE_TTL_MS)
268
+ return this.picked.value;
269
+ if (!fresh && this.picking !== null)
270
+ return this.picking;
271
+ const round = ++this.probeRound;
272
+ this.picked = null;
273
+ const entry = { abort: new AbortController(), done: Promise.resolve(undefined) };
274
+ const run = this.probeAll(entry.abort.signal).then((value) => {
275
+ if (round === this.probeRound)
276
+ this.picked = { at: this.now(), value };
277
+ return value;
278
+ }).finally(() => { this.probes.delete(entry); if (this.picking === run)
279
+ this.picking = null; });
280
+ entry.done = run;
281
+ this.probes.add(entry);
282
+ this.picking = run;
283
+ return run;
284
+ }
285
+ async probeAll(signal) {
286
+ const set = this.env['WICKED_CREW_PYTHON'];
287
+ const wanted = set !== undefined && set.trim() !== '' ? set : null;
288
+ const names = wanted !== null ? [wanted] : ['python3', ...[...TTS_PYTHON_MINORS].reverse().map((n) => `python3.${n}`)];
289
+ let skipped = null;
290
+ let badArch = null;
291
+ for (const name of names) {
292
+ if (signal.aborted)
293
+ break;
294
+ const info = await this.probe(name, this.dir, signal);
295
+ if (signal.aborted)
296
+ break;
297
+ if (info === null)
298
+ continue;
299
+ // The lock follows the processor the Python itself runs on (Rosetta: an x86_64 Python on an arm64 Mac).
300
+ const arch = info.machine === undefined ? null : archOfMachine(info.machine);
301
+ if (info.machine !== undefined && arch === null) {
302
+ badArch ??= info.machine;
303
+ continue;
304
+ }
305
+ const lock = arch === null ? null : lockPath(this.plat, arch, info.minor, this.locksDir);
306
+ if (lock !== null && this.exists(lock))
307
+ return { python: info, lock, problem: null };
308
+ skipped ??= info;
309
+ }
310
+ if (badArch !== null && skipped === null) {
311
+ return { python: null, lock: null, problem: `The ${badArch} processor is not supported for text to speech (arm64 and x86_64 only).` };
312
+ }
313
+ if (skipped !== null) {
314
+ const arch = skipped.machine === undefined ? null : archOfMachine(skipped.machine);
315
+ if (arch !== null && lockPath(this.plat, arch, skipped.minor, this.locksDir) === null && TTS_PYTHON_MINORS.includes(skipped.minor)) {
316
+ return { python: null, lock: null, problem: `Python ${skipped.version} at ${skipped.path} is not supported on this machine: the speech engine has no build for it on an Intel Mac. Use Python 3.9 to 3.13 (WICKED_CREW_PYTHON names one).` };
317
+ }
318
+ return { python: null, lock: null, problem: `Python ${skipped.version} at ${skipped.path} is not supported: voice needs CPython 3.9 to 3.14. ${pythonHint(this.plat)}` };
319
+ }
320
+ const why = wanted !== null ? `WICKED_CREW_PYTHON (${wanted}) is not a working CPython 3.` : 'No Python 3 was found on this machine.';
321
+ return { python: null, lock: null, problem: `${why} ${pythonHint(this.plat)}` };
322
+ }
323
+ /** The OS is one with a lock, and new enough for the wheels the locks were resolved for. */
324
+ platformProblem() {
325
+ if (!SUPPORTED_OS.has(this.plat)) {
326
+ return this.plat === 'win32'
327
+ ? 'Native Windows is not supported for text to speech; use WSL2 (Linux).'
328
+ : `${this.plat} is not supported for text to speech (macOS and Linux only).`;
329
+ }
330
+ if (this.plat === 'darwin') {
331
+ const major = Number.parseInt(this.release(), 10);
332
+ if (Number.isFinite(major) && major < TTS_MIN_PLATFORM.darwin.darwinMajor) {
333
+ return `This Mac is older than macOS ${TTS_MIN_PLATFORM.darwin.macos}, which the speech engine needs. Update macOS to use text to speech.`;
334
+ }
335
+ }
336
+ else {
337
+ const glibc = this.glibc();
338
+ const need = TTS_MIN_PLATFORM.linux.glibc;
339
+ if (glibc === null)
340
+ return 'This Linux uses musl, not glibc; the speech engine has no build for it (use a glibc distribution such as Debian or Ubuntu).';
341
+ const [maj, min] = glibc.split('.').map((n) => Number.parseInt(n, 10));
342
+ if (Number.isFinite(maj) && Number.isFinite(min) && (maj < need[0] || (maj === need[0] && min < need[1]))) {
343
+ return `This Linux has glibc ${glibc}; the speech engine needs glibc ${need[0]}.${need[1]} or newer (Debian 10, Ubuntu 20.04 or later).`;
344
+ }
345
+ }
346
+ return null;
347
+ }
348
+ engineInstalled() { return this.exists(this.enginePython()); }
349
+ voiceInstalled(v) {
350
+ return this.exists(join(this.voiceDir(v.id), basename(v.model.path))) && this.exists(join(this.voiceDir(v.id), basename(v.config.path)));
351
+ }
352
+ async status() {
353
+ const platformProblem = this.platformProblem();
354
+ const picked = platformProblem === null ? await this.pickPython() : { python: null, lock: null, problem: null };
355
+ const problem = platformProblem ?? picked.problem;
356
+ const engine = this.engineInstalled();
357
+ const voices = {};
358
+ for (const v of this.voices) {
359
+ voices[v.id] = { installed: this.voiceInstalled(v), name: v.name, accent: v.accent, licence: v.licence, bytes: v.model.bytes + v.config.bytes, source: TTS_VOICES_SOURCE };
360
+ }
361
+ return {
362
+ supported: { ok: problem === null, reason: problem },
363
+ python: { found: picked.python !== null, path: picked.python?.path ?? null, version: picked.python?.version ?? null },
364
+ engine: { found: engine, version: engine ? TTS_ENGINE.version : null },
365
+ voices,
366
+ install: this.installState === null ? null : { ...this.installState },
367
+ };
368
+ }
369
+ voiceById(id) {
370
+ const v = this.voices.find((x) => x.id === id);
371
+ if (v === undefined)
372
+ throw new VoiceError(400, 'voice_unknown', `"${id.slice(0, 80)}" is not a voice this install offers.`);
373
+ return v;
374
+ }
375
+ /**
376
+ * Install the engine if missing, then the named voices. Resolves at once; `status().install` reports it. Only
377
+ * manifest voices are accepted (400 `voice_unknown`); an unsupported machine is 409 `voice_tts_unsupported`.
378
+ */
379
+ async startInstall(ids) {
380
+ const wanted = ids.map((id) => this.voiceById(id));
381
+ if (this.removing > 0)
382
+ throw new VoiceError(409, 'voice_tts_missing', 'The speech engine is being removed.');
383
+ if (this.inflight !== null)
384
+ throw new VoiceError(409, 'voice_install_running', 'The speech install is already running.');
385
+ const before = this.epoch;
386
+ const problem = this.platformProblem() ?? (await this.pickPython(true)).problem;
387
+ // DELETE fences on its own epoch: an install also bumps gen.
388
+ if (this.removing > 0 || this.epoch !== before)
389
+ throw new VoiceError(409, 'voice_tts_missing', 'The speech engine is being removed.');
390
+ if (this.inflight !== null)
391
+ throw new VoiceError(409, 'voice_install_running', 'The speech install is already running.');
392
+ if (problem !== null)
393
+ throw new VoiceError(409, 'voice_tts_unsupported', problem);
394
+ if (this.engineInstalled() && wanted.every((v) => this.voiceInstalled(v)))
395
+ return { started: false };
396
+ const gen = ++this.gen;
397
+ const abort = new AbortController();
398
+ this.installState = { state: 'running', step: 'engine', error: null };
399
+ const done = this.install(wanted, gen, abort.signal).then(() => { if (this.gen === gen)
400
+ this.installState = null; }, (e) => {
401
+ if (this.gen !== gen)
402
+ return;
403
+ this.installState = { state: 'failed', step: this.installState?.step ?? 'engine', error: e instanceof Error ? e.message : String(e) };
404
+ }).finally(() => { if (this.inflight?.gen === gen)
405
+ this.inflight = null; });
406
+ this.inflight = { gen, abort, done };
407
+ return { started: true };
408
+ }
409
+ step(gen, step) {
410
+ if (this.gen === gen && this.installState !== null)
411
+ this.installState.step = step;
412
+ }
413
+ async install(wanted, gen, signal) {
414
+ mkdirSync(this.root(), { recursive: true });
415
+ if (!this.engineInstalled())
416
+ await this.installEngine(gen, signal);
417
+ for (const v of wanted) {
418
+ if (this.voiceInstalled(v))
419
+ continue;
420
+ this.step(gen, `voice:${v.id}`);
421
+ await this.installVoice(v, gen, signal);
422
+ }
423
+ }
424
+ /** Env for a child: no pip or Python variable of the person's reaches it; pip reads no config file. */
425
+ childEnv(extra = {}) {
426
+ const out = {};
427
+ for (const [k, val] of Object.entries(this.env)) {
428
+ if (val === undefined || k.startsWith('PIP_') || k.startsWith('PYTHON'))
429
+ continue;
430
+ out[k] = val;
431
+ }
432
+ return { ...out, ...extra };
433
+ }
434
+ async installEngine(gen, signal) {
435
+ const picked = await this.pickPython(true);
436
+ if (picked.python === null || picked.lock === null)
437
+ throw new Error(picked.problem ?? 'No usable Python.');
438
+ const tmp = join(this.root(), `engine.tmp-${randomBytes(4).toString('hex')}`);
439
+ try {
440
+ const venv = await this.run(picked.python.path, ['-I', '-m', 'venv', tmp], { env: this.childEnv(), timeoutMs: this.installTimeoutMs, signal });
441
+ if (venv.code !== 0)
442
+ throw new Error(`Creating the Python environment failed. ${pythonHint(this.plat)}`);
443
+ const pip = await this.run(this.enginePython(tmp), [
444
+ '-I', '-m', 'pip', 'install', '--isolated', '--index-url', TTS_ENGINE.index, '--only-binary=:all:', '--require-hashes', '--no-deps', '-r', picked.lock,
445
+ ], { env: this.childEnv({ PIP_CONFIG_FILE: '/dev/null', PIP_DISABLE_PIP_VERSION_CHECK: '1' }), timeoutMs: this.installTimeoutMs, signal });
446
+ if (pip.code !== 0)
447
+ throw new Error(`Installing ${TTS_ENGINE.name} ${TTS_ENGINE.version} failed: pip refused the hash-locked install. Check the connection to pypi.org and try again.`);
448
+ if (this.gen !== gen || signal.aborted)
449
+ throw new Error('The install was cancelled.');
450
+ rmSync(this.enginePath(), { recursive: true, force: true });
451
+ renameSync(tmp, this.enginePath());
452
+ }
453
+ catch (e) {
454
+ rmSync(tmp, { recursive: true, force: true });
455
+ throw e;
456
+ }
457
+ }
458
+ async installVoice(v, gen, signal) {
459
+ const tmp = join(this.root(), 'voices', `.${v.id}.tmp-${randomBytes(4).toString('hex')}`);
460
+ mkdirSync(tmp, { recursive: true });
461
+ try {
462
+ for (const file of [v.model, v.config])
463
+ await this.fetchVoiceFile(file, join(tmp, basename(file.path)), signal);
464
+ if (this.gen !== gen || signal.aborted)
465
+ throw new Error('The install was cancelled.');
466
+ rmSync(this.voiceDir(v.id), { recursive: true, force: true });
467
+ renameSync(tmp, this.voiceDir(v.id));
468
+ }
469
+ catch (e) {
470
+ rmSync(tmp, { recursive: true, force: true });
471
+ throw e;
472
+ }
473
+ }
474
+ /**
475
+ * One voice file: an overall deadline and an idle deadline on the body, every redirect hop https, and the bytes held
476
+ * to the manifest's size and sha256. Any failure leaves no `.part`.
477
+ */
478
+ async fetchVoiceFile(file, dest, signal) {
479
+ const part = `${dest}.part`;
480
+ const name = basename(file.path);
481
+ const stop = new AbortController();
482
+ let why = null;
483
+ const halt = (reason) => { why ??= reason; stop.abort(); };
484
+ const overall = setTimeout(() => halt(`The voice download of ${name} took longer than ${Math.round(this.downloadMs / 1000)} s and was stopped.`), this.downloadMs);
485
+ let idle = null;
486
+ const touch = () => {
487
+ if (idle !== null)
488
+ clearTimeout(idle);
489
+ idle = setTimeout(() => halt(`The voice download of ${name} stalled (no data for ${Math.round(this.idleMs / 1000)} s) and was stopped.`), this.idleMs);
490
+ };
491
+ const linked = AbortSignal.any([signal, stop.signal]);
492
+ const aborted = new Promise((_, reject) => {
493
+ const fail = () => reject(new Error(why ?? 'The install was cancelled.'));
494
+ // AbortSignal.any() can be born already aborted; an 'abort' listener added afterwards never fires. Reject at once.
495
+ if (linked.aborted)
496
+ fail();
497
+ else
498
+ linked.addEventListener('abort', fail, { once: true });
499
+ });
500
+ aborted.catch(() => undefined);
501
+ let res = null;
502
+ try {
503
+ touch();
504
+ if (linked.aborted)
505
+ throw new Error(why ?? 'The install was cancelled.');
506
+ let url = ttsVoiceUrl(file);
507
+ for (let hop = 0; hop <= TTS_MAX_REDIRECTS; hop++) {
508
+ if (new URL(url).protocol !== 'https:')
509
+ throw new Error(`The voice download for ${name} was refused: it is not https.`);
510
+ const r = await Promise.race([this.fetchImpl(url, { redirect: 'manual', signal: linked }), aborted]);
511
+ if (r.status >= 300 && r.status < 400) {
512
+ const loc = r.headers.get('location');
513
+ void r.body?.cancel().catch(() => undefined);
514
+ if (loc === null)
515
+ throw new Error(`The voice download answered ${r.status} with no place to go.`);
516
+ url = new URL(loc, url).toString();
517
+ continue;
518
+ }
519
+ res = r;
520
+ break;
521
+ }
522
+ if (res === null)
523
+ throw new Error(`The voice download for ${name} was redirected too many times.`);
524
+ if (!res.ok || res.body === null)
525
+ throw new Error(`The voice download answered ${res.status}.`);
526
+ const hash = createHash('sha256');
527
+ let size = 0;
528
+ const count = new Transform({
529
+ transform: (chunk, _enc, cb) => {
530
+ touch();
531
+ size += chunk.length;
532
+ if (size > file.bytes)
533
+ return cb(new Error(`The voice file ${name} is larger than its published size (${file.bytes} bytes); nothing was kept.`));
534
+ hash.update(chunk);
535
+ cb(null, chunk);
536
+ },
537
+ });
538
+ try {
539
+ await pipeline(Readable.fromWeb(res.body), count, createWriteStream(part), { signal: linked });
540
+ }
541
+ catch (e) {
542
+ throw why !== null ? new Error(why) : e;
543
+ }
544
+ const got = hash.digest('hex');
545
+ if (size !== file.bytes)
546
+ throw new Error(`The voice file ${name} is ${size} bytes, not its published ${file.bytes}; nothing was kept.`);
547
+ if (got !== file.sha256)
548
+ throw new Error(`The voice file ${name} did not match its published checksum (got sha256 ${got}); nothing was kept.`);
549
+ renameSync(part, dest);
550
+ }
551
+ catch (e) {
552
+ rmSync(part, { force: true });
553
+ throw e;
554
+ }
555
+ finally {
556
+ stop.abort();
557
+ if (res?.body !== null && res?.body !== undefined && !res.body.locked)
558
+ void res.body.cancel().catch(() => undefined);
559
+ clearTimeout(overall);
560
+ if (idle !== null)
561
+ clearTimeout(idle);
562
+ }
563
+ }
564
+ /** Remove the engine, the voices and the cached samples. An install in flight is cancelled first. */
565
+ async remove() {
566
+ this.gen += 1;
567
+ this.epoch += 1;
568
+ this.removing += 1;
569
+ this.probeRound += 1;
570
+ this.picking = null;
571
+ this.picked = null;
572
+ try {
573
+ const install = this.inflight;
574
+ install?.abort.abort();
575
+ for (const p of this.probes)
576
+ p.abort.abort();
577
+ for (const s of this.synths)
578
+ s.abort.abort();
579
+ // The files go only after every child has closed: no descendant can write into a directory being removed.
580
+ await Promise.allSettled([install?.done, ...[...this.probes].map((x) => x.done), ...[...this.synths].map((x) => x.done)]);
581
+ this.inflight = null;
582
+ this.installState = null;
583
+ this.picked = null;
584
+ const had = this.exists(this.root());
585
+ rmSync(this.root(), { recursive: true, force: true });
586
+ return { removed: had };
587
+ }
588
+ finally {
589
+ this.removing -= 1;
590
+ }
591
+ }
592
+ /** Speak `text` in `voice`; the WAV bytes. Nothing about the text is kept. */
593
+ async speak(text, voice) {
594
+ const v = this.voiceById(voice);
595
+ this.ready(v);
596
+ const line = normalizeSpeakText(text);
597
+ if (line === '')
598
+ throw new VoiceError(400, 'voice_text_empty', 'There is nothing to read aloud.');
599
+ const epoch = this.epoch;
600
+ return this.exclusive(async () => {
601
+ this.ready(v, epoch);
602
+ return this.synthesize(v, line);
603
+ });
604
+ }
605
+ /** A fixed sentence in `voice`, cached per (voice, piper version); a cached one is re-verified on every read. */
606
+ async sample(voice) {
607
+ const v = this.voiceById(voice);
608
+ this.ready(v);
609
+ const epoch = this.epoch;
610
+ return this.exclusive(async () => {
611
+ this.ready(v, epoch);
612
+ const cached = this.samplePath(v.id);
613
+ const sum = `${cached}.sha256`;
614
+ if (this.exists(cached)) {
615
+ try {
616
+ const st = lstatSync(cached);
617
+ if (!st.isFile() || st.size > this.maxWav)
618
+ throw new Error('Invalid cached sample.');
619
+ // The sidecar is lstat-checked before it is opened: a FIFO there would block the event loop, and an
620
+ // oversized file would be read whole. Only a small regular file is read; anything else is a cache miss.
621
+ const ss = lstatSync(sum);
622
+ if (!ss.isFile() || ss.size > TTS_SIDECAR_MAX_BYTES)
623
+ throw new Error('Invalid cached sidecar.');
624
+ const wav = readFileSync(cached);
625
+ if (ttsWavProblem(wav) === null && readFileSync(sum, 'utf8').trim() === createHash('sha256').update(wav).digest('hex'))
626
+ return wav;
627
+ }
628
+ catch { /* unreadable or unrecorded: re-made below */ }
629
+ rmSync(cached, { recursive: true, force: true });
630
+ rmSync(sum, { recursive: true, force: true });
631
+ }
632
+ const wav = await this.synthesize(v, TTS_SAMPLE_TEXT);
633
+ mkdirSync(dirname(cached), { recursive: true });
634
+ const part = `${cached}.part`;
635
+ writeFileSync(part, wav);
636
+ writeFileSync(sum, createHash('sha256').update(wav).digest('hex'));
637
+ renameSync(part, cached);
638
+ return wav;
639
+ });
640
+ }
641
+ /** One synthesis at a time and one waiting: a third is refused 429 `voice_busy`. */
642
+ async exclusive(fn) {
643
+ if (this.busy && this.waiting.length >= 1)
644
+ throw new VoiceError(429, 'voice_busy', 'Still reading the last thing aloud.');
645
+ if (this.busy)
646
+ await new Promise((r) => this.waiting.push(r));
647
+ this.busy = true;
648
+ try {
649
+ return await fn();
650
+ }
651
+ finally {
652
+ const next = this.waiting.shift();
653
+ if (next !== undefined)
654
+ next();
655
+ else
656
+ this.busy = false;
657
+ }
658
+ }
659
+ /** The engine and the voice, or the 409 that names what is missing (no fallback). */
660
+ ready(v, epoch = this.epoch) {
661
+ if (this.removing > 0 || epoch !== this.epoch)
662
+ throw new VoiceError(409, 'voice_tts_missing', 'The speech engine is being removed.');
663
+ if (!this.engineInstalled())
664
+ throw new VoiceError(409, 'voice_tts_missing', 'The speech engine is not installed; install it first (it needs your consent).');
665
+ if (!this.voiceInstalled(v))
666
+ throw new VoiceError(409, 'voice_tts_missing', `The voice ${v.id} is not installed; install it first.`);
667
+ }
668
+ /**
669
+ * Piper writes into a fresh private directory; the output must be a regular file (lstat, so a symlink or a device
670
+ * is refused), before and while its size is watched. The directory goes only after the child has closed.
671
+ */
672
+ synthesize(v, line) {
673
+ const entry = { abort: new AbortController(), done: Promise.resolve(undefined) };
674
+ const run = this.synthesizeIn(v, line, entry.abort.signal);
675
+ entry.done = run.catch(() => undefined).finally(() => this.synths.delete(entry));
676
+ this.synths.add(entry);
677
+ return run;
678
+ }
679
+ async synthesizeIn(v, line, signal) {
680
+ const workDir = join(this.root(), 'work');
681
+ mkdirSync(workDir, { recursive: true });
682
+ const scratch = mkdtempSync(join(workDir, 's-'));
683
+ const out = join(scratch, 'out.wav');
684
+ try {
685
+ const r = await this.run(this.enginePython(), [
686
+ '-I', '-m', 'piper', '-m', join(this.voiceDir(v.id), basename(v.model.path)), '-c', join(this.voiceDir(v.id), basename(v.config.path)), '-f', out,
687
+ ], { env: this.childEnv(), timeoutMs: this.timeoutMs, stdin: `${line}\n`, signal, cancelled: () => new VoiceError(409, 'voice_tts_missing', 'The speech engine was removed while it was reading.'), watch: { file: out, maxBytes: this.maxWav } });
688
+ // The child's stderr can echo the spoken text: it is never put in an error.
689
+ if (r.code !== 0)
690
+ throw new VoiceError(500, 'voice_tts_failed', SYNTH_FAILED);
691
+ const st = lstatOrNull(out);
692
+ if (st === null)
693
+ throw new VoiceError(500, 'voice_tts_failed', 'piper wrote no audio.');
694
+ if (!st.isFile())
695
+ throw new VoiceError(500, 'voice_tts_failed', 'piper wrote its output as something other than a plain file; it was refused.');
696
+ if (st.size > this.maxWav)
697
+ throw new VoiceError(500, 'voice_tts_failed', 'The audio is larger than the limit and was dropped.');
698
+ const wav = readFileSync(out);
699
+ const problem = ttsWavProblem(wav);
700
+ if (problem !== null)
701
+ throw new VoiceError(500, 'voice_tts_failed', `piper wrote audio that is not a usable WAV (${problem}).`);
702
+ return wav;
703
+ }
704
+ finally {
705
+ rmSync(scratch, { recursive: true, force: true });
706
+ }
707
+ }
708
+ /**
709
+ * Run a child with argv only (never a shell), in its own process group, with the voice dir as its cwd; stdout and
710
+ * stderr each capped. A timeout, a cancel or an output file that passes a limit kills the whole group, and the
711
+ * promise settles only on the child's `close`, so no descendant can write after the caller cleans up.
712
+ */
713
+ run(command, args, o) {
714
+ return runChild(command, args, o, this.spawnImpl, this.dir);
715
+ }
716
+ }
717
+ /** Shared by probes, installers and synthesis: kill the group, then await close. */
718
+ function runChild(command, args, o, spawnImpl, cwd) {
719
+ mkdirSync(cwd, { recursive: true });
720
+ return new Promise((resolve, reject) => {
721
+ let child;
722
+ try {
723
+ child = spawnImpl(command, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: true, cwd, env: childEnvWithBootEstateDb(o.env) });
724
+ }
725
+ catch {
726
+ reject(new VoiceError(500, 'voice_tts_failed', 'Could not start the speech engine.'));
727
+ return;
728
+ }
729
+ const out = [];
730
+ const err = [];
731
+ const held = { out: 0, err: 0 };
732
+ let settled = false;
733
+ let pending = null;
734
+ let watcher = null;
735
+ const finish = (f) => {
736
+ if (settled)
737
+ return;
738
+ settled = true;
739
+ clearTimeout(timer);
740
+ if (watcher !== null)
741
+ clearInterval(watcher);
742
+ o.signal?.removeEventListener('abort', onAbort);
743
+ f();
744
+ };
745
+ const kill = () => {
746
+ try {
747
+ if (child.pid !== undefined && process.platform !== 'win32')
748
+ process.kill(-child.pid, 'SIGKILL');
749
+ else
750
+ child.kill('SIGKILL');
751
+ }
752
+ catch {
753
+ try {
754
+ child.kill('SIGKILL');
755
+ }
756
+ catch { /* already gone */ }
757
+ }
758
+ };
759
+ /** Record why, kill the group, and wait for `close` to settle. */
760
+ const stop = (e) => {
761
+ if (settled || pending !== null)
762
+ return;
763
+ pending = e;
764
+ clearTimeout(timer);
765
+ if (watcher !== null)
766
+ clearInterval(watcher);
767
+ kill();
768
+ };
769
+ const timer = setTimeout(() => stop(new VoiceError(504, 'voice_timeout', `Reading aloud took longer than ${Math.round(o.timeoutMs / 1000)} s and was stopped.`)), o.timeoutMs);
770
+ const onAbort = () => stop(o.cancelled?.() ?? new Error('The install was cancelled.'));
771
+ o.signal?.addEventListener('abort', onAbort, { once: true });
772
+ if (o.signal?.aborted === true)
773
+ onAbort();
774
+ if (o.watch !== undefined) {
775
+ const { file, maxBytes } = o.watch;
776
+ watcher = setInterval(() => {
777
+ const st = lstatOrNull(file);
778
+ if (st === null)
779
+ return;
780
+ if (!st.isFile())
781
+ stop(new VoiceError(500, 'voice_tts_failed', 'piper wrote its output as something other than a plain file; it was refused.'));
782
+ else if (st.size > maxBytes)
783
+ stop(new VoiceError(500, 'voice_tts_failed', 'The audio grew past its size limit and was stopped.'));
784
+ }, 50);
785
+ }
786
+ // Each stream keeps at most TTS_OUTPUT_CAP_BYTES BYTES; it is decoded only after the cap.
787
+ const keep = (into, which) => (d) => {
788
+ const chunk = typeof d === 'string' ? Buffer.from(d) : d;
789
+ const room = TTS_OUTPUT_CAP_BYTES - held[which];
790
+ if (room <= 0)
791
+ return;
792
+ const part = chunk.length > room ? chunk.subarray(0, room) : chunk;
793
+ into.push(part);
794
+ held[which] += part.length;
795
+ };
796
+ child.stdout?.on('data', keep(out, 'out'));
797
+ child.stderr?.on('data', keep(err, 'err'));
798
+ child.on('error', () => { pending ??= new VoiceError(500, 'voice_tts_failed', 'Could not start the speech engine.'); });
799
+ child.on('close', (code) => finish(() => {
800
+ if (pending !== null)
801
+ reject(pending);
802
+ else
803
+ resolve({ code, stdout: decodeCapped(out), stderr: decodeCapped(err) });
804
+ }));
805
+ child.stdin?.on('error', () => undefined);
806
+ child.stdin?.end(o.stdin ?? '');
807
+ });
808
+ }
809
+ function lstatOrNull(p) {
810
+ try {
811
+ return lstatSync(p);
812
+ }
813
+ catch {
814
+ return null;
815
+ }
816
+ }
817
+ /** Buffers cut at a byte cap, decoded as UTF-8; StringDecoder without `end()` drops a torn trailing character. */
818
+ function decodeCapped(chunks) {
819
+ return new StringDecoder('utf8').write(Buffer.concat(chunks));
820
+ }
821
+ //# sourceMappingURL=tts.js.map