decklight 0.1.0 → 0.3.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 (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
@@ -0,0 +1,455 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // The voices decklight can speak with. One factory, four engines, one shape:
6
+ //
7
+ // createEngine({ engine, … }) → { name, model, voices, needsProject,
8
+ // synth(text, { voice, style }) → { wav, usage } }
9
+ //
10
+ // `voices` is the roster the player's picker offers. Three engines know theirs
11
+ // up front; ElevenLabs cannot, because the interesting ones are the voices YOU
12
+ // made — so it also returns `listVoices()`, an async, cached lookup the bridge
13
+ // awaits before answering /ping. An engine without it just has `voices`.
14
+ //
15
+ // gemini — gemini-2.5-{pro,flash}-tts on Vertex AI. Best delivery, and the
16
+ // only engine that takes a STYLE instruction. No free tier, and a
17
+ // fresh project's per-minute quota is small: bursty narration 429s.
18
+ // pro is slow (~20s a sentence); flash is the one to reach for.
19
+ // chirp — Chirp 3: HD on the Cloud Text-to-Speech API. A DIFFERENT API from
20
+ // Vertex, with a permanent free tier (1M chars/month), ~1s a
21
+ // sentence, and — conveniently — the same 30 star-named voices as
22
+ // Gemini, so a deck keeps its voice when it changes engine. Style is
23
+ // ignored: Chirp has no delivery-instruction channel.
24
+ // piper — local neural TTS. Free, offline, unlimited, no credentials. One
25
+ // voice per installed model, so the picker's roster doesn't apply.
26
+ // elevenlabs — the one whose roster is YOUR account's, cloned voices included.
27
+ // Needs $ELEVENLABS_API_KEY (never saved to disk). Metered in
28
+ // characters against a plan allowance we cannot see, so it reports
29
+ // characters and no dollar estimate. Style is ignored on every
30
+ // model except the opt-in --tts-model eleven_v3 (its own delivery
31
+ // channel: bracketed audio tags read as direction, not words), so
32
+ // `stylable` here depends on the model chosen, not just the engine.
33
+ //
34
+ // Cost is always an ESTIMATE from published list prices. Chirp's estimate is
35
+ // the list price *ignoring* the free tier — we cannot see your monthly usage,
36
+ // so the bridge reports characters too, which is what the free tier is
37
+ // denominated in.
38
+ //
39
+ // A seventh engine is whatever the machine INSTALLED (SPEC ENGINE_UNITS):
40
+ // `resolveEngine` at the bottom of this file takes any name, answers the six
41
+ // above itself, and hands anything else to the unit library. The six stay
42
+ // core and unversioned — they need no marketplace, so a machine with none
43
+ // registered reaches its own voice exactly as it always did.
44
+
45
+ import { execFileSync, spawn } from 'node:child_process';
46
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
47
+ import { homedir, tmpdir } from 'node:os';
48
+ import { join } from 'node:path';
49
+ import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId, authHeaders } from './gemini-tts.mjs';
50
+ import {
51
+ createSynth as createElevenLabs, apiKey as elevenLabsKey,
52
+ DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL,
53
+ } from './elevenlabs-tts.mjs';
54
+ import { detectLocalVoice, sayArgs, sapiArgs } from './local-voice.mjs';
55
+
56
+ export const ENGINES = ['gemini', 'chirp', 'piper', 'elevenlabs', 'say', 'sapi'];
57
+ /** The two engines that are already on the machine — nothing to install. */
58
+ export const NATIVE_ENGINES = ['say', 'sapi'];
59
+
60
+ // Piper's defaults, shared with the setup wizard (tools/tts-setup.mjs) so the
61
+ // model it checks for is the model createPiper will load.
62
+ export const PIPER_DEFAULT_VOICE = 'en_US-ryan-high';
63
+ export const piperModelDir = (env = process.env) =>
64
+ join(env.HOME || homedir(), '.local', 'share', 'piper');
65
+
66
+ const onPath = (bin) => {
67
+ try {
68
+ execFileSync(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' });
69
+ return true;
70
+ } catch { return false; }
71
+ };
72
+ const canImportPiper = (py) => {
73
+ try { execFileSync(py, ['-c', 'import piper.download_voices'], { stdio: 'ignore' }); return true; }
74
+ catch { return false; }
75
+ };
76
+
77
+ /**
78
+ * How to fetch a piper voice model ON THIS MACHINE.
79
+ *
80
+ * This used to be a constant — `python -m piper.download_voices …` — and it did
81
+ * not work for the install decklight itself recommends. `uv tool install
82
+ * piper-tts` puts piper in an ISOLATED virtualenv, on purpose; the ambient
83
+ * python cannot import from it, so the printed command fails with
84
+ * ModuleNotFoundError on a machine where piper is installed and working fine.
85
+ *
86
+ * So the command is chosen rather than assumed: a python that can already
87
+ * import piper (a pip install into the active environment) gets the plain form,
88
+ * and otherwise `uvx --from piper-tts` runs it inside the venv `uv` made.
89
+ * Returns null when neither is possible, which is a different message.
90
+ */
91
+ /**
92
+ * Where a piper voice model lives. A voice given as a PATH is already the
93
+ * answer; a bare name only resolves against a data dir — the same rule
94
+ * createPiper applies when it decides whether to pass --data-dir.
95
+ */
96
+ export function piperModelPath(voice = PIPER_DEFAULT_VOICE, dataDir = piperModelDir()) {
97
+ return (voice.includes('/') || voice.endsWith('.onnx')) ? voice : join(dataDir, `${voice}.onnx`);
98
+ }
99
+
100
+ export function piperDownloadCmd(voice = PIPER_DEFAULT_VOICE, models = piperModelDir(), {
101
+ hasBin = onPath, canImport = canImportPiper,
102
+ } = {}) {
103
+ const tail = ['-m', 'piper.download_voices', voice, '--data-dir', models];
104
+ for (const py of ['python3', 'python']) if (canImport(py)) return { bin: py, args: tail };
105
+ if (hasBin('uvx')) return { bin: 'uvx', args: ['--from', 'piper-tts', 'python', ...tail] };
106
+ return null;
107
+ }
108
+
109
+ /** A chosen command as the line a human would type, or the way to get one. */
110
+ export const piperDownloadLine = (cmd) => (cmd
111
+ ? [cmd.bin, ...cmd.args].join(' ')
112
+ // piper may well be installed — what is missing is a way to REACH its
113
+ // downloader, which is a different problem and a different fix
114
+ : 'no python here can import piper, and uvx is not on PATH — '
115
+ + 'install uv (https://docs.astral.sh/uv) or: pip install piper-tts');
116
+
117
+ // Chirp 3: HD ships the same roster as Gemini TTS (verified against
118
+ // texttospeech.googleapis.com/v1/voices) — one name, two engines.
119
+ const CHIRP_PRICE_PER_1M = 30.0; // USD, list, after the 1M chars/month free tier
120
+ const chirpVoice = (voice, lang) => `${lang}-Chirp3-HD-${voice}`;
121
+
122
+ function createChirp({ project, lang = 'en-US' }) {
123
+ if (!project) throw new Error('chirp needs a GCP project — pass --project <id> or set GOOGLE_CLOUD_PROJECT');
124
+ if (!validProjectId(project)) throw new Error(`not a GCP project id: ${JSON.stringify(project)}`);
125
+ let token = null;
126
+
127
+ async function call(text, voice) {
128
+ const res = await fetch('https://texttospeech.googleapis.com/v1/text:synthesize', {
129
+ method: 'POST',
130
+ headers: authHeaders(token, project),
131
+ body: JSON.stringify({
132
+ input: { text },
133
+ voice: { languageCode: lang, name: chirpVoice(voice, lang) },
134
+ audioConfig: { audioEncoding: 'LINEAR16', sampleRateHertz: 24000 },
135
+ }),
136
+ });
137
+ if (!res.ok) { const e = new Error(`${res.status} ${(await res.text()).slice(0, 200)}`); e.status = res.status; throw e; }
138
+ const { audioContent } = await res.json();
139
+ if (!audioContent) throw new Error('no audio in response');
140
+ // LINEAR16 comes back as a complete RIFF/WAVE — no header to bolt on
141
+ return Buffer.from(audioContent, 'base64');
142
+ }
143
+
144
+ return async function synth(text, { voice = 'Alnilam' } = {}) {
145
+ token ??= gcloudToken();
146
+ let lastErr;
147
+ for (let attempt = 0; attempt < 3; attempt++) {
148
+ try {
149
+ return {
150
+ wav: await call(text, voice),
151
+ usage: {
152
+ model: 'chirp3-hd',
153
+ chars: text.length,
154
+ cost: (text.length / 1e6) * CHIRP_PRICE_PER_1M,
155
+ note: `${text.length} chars`,
156
+ },
157
+ };
158
+ } catch (e) {
159
+ lastErr = e;
160
+ if (e.status === 401) { token = gcloudToken(); continue; }
161
+ if (e.status === 429 || e.status >= 500) { await new Promise((ok) => setTimeout(ok, 2000 * (attempt + 1))); continue; }
162
+ break;
163
+ }
164
+ }
165
+ throw lastErr;
166
+ };
167
+ }
168
+
169
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
170
+
171
+ /**
172
+ * Piper, kept RESIDENT.
173
+ *
174
+ * piper reloads its model on every start — ~13s for en_US-ryan-high (116 MB),
175
+ * against ~1.6s of interpreter startup — so a process per sentence would make
176
+ * the offline engine slower than the cloud one and useless for live narration.
177
+ * Held open it pays that once, and a warm sentence costs about twice its own
178
+ * playing time (~4s for 2s of speech on a laptop CPU) — which the player's
179
+ * lookahead buffer covers, since it synthesizes ahead of the playhead.
180
+ *
181
+ * Its stream interface is line-oriented: one line of text in, one WAV out, into
182
+ * a spool dir, in order. So requests are serialized and the next unseen file is
183
+ * ours — which also means the text must be flattened to a single line, or one
184
+ * request would silently become several utterances.
185
+ */
186
+ function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
187
+ try { execFileSync('piper', ['--help'], { stdio: 'ignore' }); }
188
+ catch { throw new Error('piper not found — install with: uv tool install piper-tts'); }
189
+ // A bare model NAME only resolves against a data dir — without one, piper
190
+ // searches its own default and calls the voice missing even when it is
191
+ // sitting right there. A model PATH needs no dir at all.
192
+ const models = dataDir ?? piperModelDir();
193
+ const byPath = voice.includes('/') || voice.endsWith('.onnx');
194
+
195
+ let proc = null, spool = null;
196
+ let fatal = null; // a config error (missing voice) — retrying cannot fix it
197
+ let chain = Promise.resolve();
198
+ const finished = []; // paths piper has announced as written, in order
199
+ let wake = null;
200
+
201
+ function ensure() {
202
+ if (proc) return;
203
+ if (fatal) throw new Error(fatal);
204
+ spool = mkdtempSync(join(tmpdir(), 'decklight-piper-'));
205
+ finished.length = 0;
206
+ const p = spawn('piper', [
207
+ '-m', voice, ...(byPath ? [] : ['--data-dir', models]),
208
+ '-d', spool, '--output-dir-naming', 'timestamp',
209
+ ], { stdio: ['pipe', 'ignore', 'pipe'] });
210
+ let err = '';
211
+ let tail = '';
212
+ p.stderr.on('data', (b) => {
213
+ err = (err + b).slice(-4000);
214
+ // `INFO:__main__:Wrote <path>` — piper's end-of-utterance signal
215
+ tail += b;
216
+ const lines = tail.split('\n');
217
+ tail = lines.pop() ?? '';
218
+ for (const line of lines) {
219
+ const m = /Wrote (.+\.wav)\s*$/.exec(line);
220
+ if (m) { finished.push(m[1].trim()); wake?.(); }
221
+ }
222
+ });
223
+ p.on('exit', (code) => {
224
+ if (proc === p) proc = null;
225
+ rmSync(spool, { recursive: true, force: true });
226
+ if (/Unable to find voice/.test(err)) {
227
+ fatal = `piper voice '${voice}' not in ${models} — fetch it with: `
228
+ + piperDownloadLine(piperDownloadCmd(voice, models));
229
+ } else if (code) {
230
+ // a crash is not necessarily terminal: the next call respawns
231
+ lastExit = `piper exited (${code}) ${err.trim().split('\n').pop() ?? ''}`.trim();
232
+ }
233
+ });
234
+ proc = p;
235
+ }
236
+ let lastExit = null;
237
+
238
+ // The FILE cannot tell you when an utterance is done — only piper can.
239
+ //
240
+ // The obvious signal is a lie. Piper keeps the RIFF header in sync as it
241
+ // streams, so "the header's declared length matches the bytes on disk" is
242
+ // already true at the FIRST sentence boundary. And because piper synthesizes
243
+ // sentence by sentence, the file then sits at exactly that size for as long
244
+ // as the next sentence takes to generate — so "wait until it stops growing"
245
+ // fails too, however long you wait. Any file-watching heuristic hands back a
246
+ // well-formed WAV holding only the first sentence, and nothing downstream can
247
+ // tell: the deck just says half the line, in a clip whose duration looks
248
+ // plausible. (Measured on en_US-ryan-high: header first matched at 151084
249
+ // bytes of a 301612-byte file — half the utterance.)
250
+ //
251
+ // Piper announces each finished utterance on stderr:
252
+ // INFO:__main__:Wrote /tmp/decklight-piper-XXXX/1234567890.wav
253
+ // That says no further sentence is coming — the one thing the file cannot.
254
+ // It does NOT mean every byte is on disk (piper logs it before closing the
255
+ // handle, so reading immediately still truncates at the last flush boundary:
256
+ // a 7.44s and a 7.24s clip both came back as the same 314924 bytes). So the
257
+ // two signals compose, and neither alone would do: stderr ends the utterance,
258
+ // and only THEN does header-match + settled-size mean "closed" rather than
259
+ // "between sentences".
260
+ const headerMatches = (b) => b.length > 44 && b.readUInt32LE(4) + 8 === b.length;
261
+
262
+ async function drain(f, timeoutMs = 10_000) {
263
+ const t0 = Date.now();
264
+ let last = -1;
265
+ for (;;) {
266
+ const b = readFileSync(f);
267
+ if (headerMatches(b) && b.length === last) return b; // closed
268
+ last = b.length;
269
+ if (Date.now() - t0 >= timeoutMs) return b; // never settled — take it
270
+ await sleep(20);
271
+ }
272
+ }
273
+
274
+ // Requests are serialized (one line in → one file out, in order), so the next
275
+ // announced path is ours.
276
+ async function nextWav(timeoutMs = 180_000) {
277
+ const t0 = Date.now();
278
+ for (;;) {
279
+ if (!proc) throw new Error(fatal ?? lastExit ?? 'piper stopped');
280
+ const f = finished.shift();
281
+ if (f) {
282
+ const b = await drain(f);
283
+ rmSync(f, { force: true });
284
+ return b;
285
+ }
286
+ if (Date.now() - t0 >= timeoutMs) throw new Error('piper timed out');
287
+ await new Promise((resolve) => {
288
+ wake = resolve;
289
+ setTimeout(resolve, 50); // also covers a missed wake
290
+ });
291
+ wake = null;
292
+ }
293
+ }
294
+
295
+ function synth(text) {
296
+ const line = String(text).replace(/\s+/g, ' ').trim(); // one utterance, one line
297
+ chain = chain.catch(() => {}).then(async () => {
298
+ ensure();
299
+ proc.stdin.write(`${line}\n`);
300
+ return {
301
+ wav: await nextWav(),
302
+ usage: { model: voice, chars: line.length, cost: 0, note: `${line.length} chars · local` },
303
+ };
304
+ });
305
+ return chain;
306
+ }
307
+ // Start the model loading NOW rather than on the first sentence — otherwise
308
+ // the presenter's first keypress pays the whole ~13s load, which reads as a
309
+ // hung deck. By the time anyone has opened a slide, piper is warm.
310
+ synth.warm = () => { try { ensure(); } catch { /* reported at synth time */ } };
311
+ // The resident process outlives the work: its piped stdio keeps Node's event
312
+ // loop alive, so a BATCH caller that simply stops calling synth() never exits
313
+ // (the bridge doesn't care — it is a server — but tools/voiceover.mjs hung on
314
+ // its own success). Batch callers close when they are done.
315
+ synth.close = () => { proc?.kill(); proc = null; };
316
+ return synth;
317
+ }
318
+
319
+ /**
320
+ * One engine, one shape. `voices` is what the player should offer: the star
321
+ * roster for the cloud engines, and for piper the single installed model —
322
+ * offering 30 Gemini names it cannot speak would just be a lie.
323
+ */
324
+
325
+ /**
326
+ * The voice the operating system already has.
327
+ *
328
+ * macOS `say` and Windows SAPI are one implementation with two spellings: both
329
+ * are "hand a line of text and a file path to a program, get a WAV back". No
330
+ * credentials, no download, no resident process — a fresh child per sentence,
331
+ * which is affordable because neither loads a 120 MB model to start.
332
+ *
333
+ * Neither takes a delivery instruction, so both are `stylable: false` and the
334
+ * picker skips the tone step, exactly as it does for piper and ElevenLabs.
335
+ */
336
+ function createNative({ kind, voice, shell = 'powershell.exe' }) {
337
+ const bin = kind === 'say' ? 'say' : shell;
338
+ const build = kind === 'say' ? sayArgs : sapiArgs;
339
+ return async (text) => {
340
+ // one line: `say` treats newlines as pauses and PowerShell quoting gets
341
+ // harder the moment a string spans lines
342
+ const line = String(text).replace(/\s+/g, ' ').trim();
343
+ if (!line) throw new Error('nothing to say');
344
+ const dir = mkdtempSync(join(tmpdir(), 'decklight-native-'));
345
+ const file = join(dir, 'out.wav');
346
+ try {
347
+ execFileSync(bin, build(line, voice, file), { stdio: ['ignore', 'ignore', 'pipe'] });
348
+ const wav = readFileSync(file);
349
+ if (!wav.length) throw new Error(`${kind} produced no audio`);
350
+ return wav;
351
+ } catch (e) {
352
+ throw new Error(`${kind}: ${String(e.stderr ?? e.message).trim().split('\n')[0] || 'synthesis failed'}`);
353
+ } finally {
354
+ rmSync(dir, { recursive: true, force: true });
355
+ }
356
+ };
357
+ }
358
+
359
+ export function createEngine({
360
+ engine = 'gemini', project, model, location, voice, dataDir, lang, format, stability, env = process.env,
361
+ } = {}) {
362
+ if (!ENGINES.includes(engine)) {
363
+ throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')},`
364
+ + ` or install one: decklight engine add ${engine}`);
365
+ }
366
+
367
+ // `cost` is the human-facing price note — the bridge's startup line and the
368
+ // setup wizard's test-synthesis report both quote it.
369
+ if (engine === 'piper') {
370
+ const m = voice ?? PIPER_DEFAULT_VOICE;
371
+ return {
372
+ name: 'piper', model: m, needsProject: false, stylable: false,
373
+ cost: 'free · offline',
374
+ voices: [[m, 'local']],
375
+ synth: createPiper({ voice: m, dataDir }),
376
+ };
377
+ }
378
+ if (engine === 'say' || engine === 'sapi') {
379
+ const detected = detectLocalVoice({ lang });
380
+ const pick = voice ?? detected.voices?.[0]?.name;
381
+ if (!pick) throw new Error(detected.why ?? `no ${engine} voices on this machine`);
382
+ return {
383
+ name: engine, model: pick, needsProject: false, stylable: false,
384
+ cost: 'free · offline · already on this machine',
385
+ voices: (detected.voices ?? []).map((v) => [v.name, v.locale || 'system']),
386
+ synth: createNative({ kind: engine, voice: pick, shell: detected.shell }),
387
+ };
388
+ }
389
+ if (engine === 'elevenlabs') {
390
+ const m = model ?? ELEVENLABS_MODEL;
391
+ const isV3 = m === ELEVENLABS_V3_MODEL;
392
+ const { listVoices, synth } = createElevenLabs({
393
+ key: elevenLabsKey(env), model: m, format: format ?? 'pcm', stability,
394
+ });
395
+ return {
396
+ name: 'elevenlabs', model: m, needsProject: false,
397
+ // v3 alone reads audio tags as direction — every other ElevenLabs model
398
+ // would read a tag's brackets aloud as words, so the tone step is v3-only,
399
+ // decided here from the model rather than the picker guessing by name.
400
+ stylable: isV3,
401
+ cost: 'metered in characters against your plan',
402
+ // Stated once, at startup, where the presenter is still choosing —
403
+ // v3 trades latency and consistency for expressiveness, and ElevenLabs'
404
+ // own guidance targets prompts over ~250 characters against decklight's
405
+ // one spoken sentence at a time, read live rather than pre-rendered.
406
+ caveat: isV3
407
+ ? 'eleven_v3: higher latency, more variable consistency, and ElevenLabs '
408
+ + 'recommends prompts over ~250 characters — a live decklight sentence is '
409
+ + 'shorter than that, so delivery may vary more than a ⇧V recording.'
410
+ : undefined,
411
+ // the real roster arrives from the account; until it does the picker has
412
+ // nothing truthful to show, which is better than thirty names it cannot say
413
+ voices: [], listVoices,
414
+ synth,
415
+ };
416
+ }
417
+ if (engine === 'chirp') {
418
+ return {
419
+ name: 'chirp', model: 'chirp3-hd', needsProject: true, stylable: false,
420
+ cost: 'first 1M chars/month free',
421
+ voices: GEMINI_VOICES,
422
+ synth: createChirp({ project, lang: lang ?? 'en-US' }),
423
+ };
424
+ }
425
+ const m = model ?? 'gemini-2.5-pro-tts';
426
+ return {
427
+ name: 'gemini', model: m, needsProject: true, stylable: true,
428
+ cost: 'billed per call — no free tier',
429
+ voices: GEMINI_VOICES,
430
+ synth: createGemini({ project, ttsModel: m, location }),
431
+ };
432
+ }
433
+
434
+ /**
435
+ * The engine for `name`, whether decklight ships it or the machine installed
436
+ * it (SPEC `ENGINE_UNITS`).
437
+ *
438
+ * The six above are resolved first and synchronously — they are not units,
439
+ * they need no library and no catalog, and a machine with no marketplace
440
+ * registered must reach its own voice by exactly the path it always did.
441
+ * Only a name that is NOT one of them reaches the unit library, so the
442
+ * loader (and the `cli/` half of the tree it pulls in) is imported lazily:
443
+ * `decklight tts --engine piper` should not pay to read a registry it will
444
+ * not consult.
445
+ *
446
+ * Async because loading an installed engine means `import()`ing it. Callers
447
+ * that only ever speak with a built-in can keep calling `createEngine`
448
+ * directly; the bridge cannot know which it has been given, so it awaits this.
449
+ */
450
+ export async function resolveEngine(opts = {}) {
451
+ const name = opts.engine ?? 'gemini';
452
+ if (ENGINES.includes(name)) return createEngine(opts);
453
+ const { loadEngine } = await import('../cli/loader.mjs');
454
+ return loadEngine(name, opts);
455
+ }