decklight 0.2.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +855 -80
  3. package/cli/agents.mjs +113 -9
  4. package/cli/associate.mjs +279 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +564 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +730 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +646 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +560 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +201 -0
  34. package/cli/units.mjs +488 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +5 -4
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +11 -2
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +139 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +316 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
@@ -2,11 +2,16 @@
2
2
  // Copyright 2026 Gilles Philippart
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
- // The voices decklight can speak with. One factory, three engines, one shape:
5
+ // The voices decklight can speak with. One factory, four engines, one shape:
6
6
  //
7
7
  // createEngine({ engine, … }) → { name, model, voices, needsProject,
8
8
  // synth(text, { voice, style }) → { wav, usage } }
9
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
+ //
10
15
  // gemini — gemini-2.5-{pro,flash}-tts on Vertex AI. Best delivery, and the
11
16
  // only engine that takes a STYLE instruction. No free tier, and a
12
17
  // fresh project's per-minute quota is small: bursty narration 429s.
@@ -18,19 +23,96 @@
18
23
  // ignored: Chirp has no delivery-instruction channel.
19
24
  // piper — local neural TTS. Free, offline, unlimited, no credentials. One
20
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.
21
33
  //
22
34
  // Cost is always an ESTIMATE from published list prices. Chirp's estimate is
23
35
  // the list price *ignoring* the free tier — we cannot see your monthly usage,
24
36
  // so the bridge reports characters too, which is what the free tier is
25
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.
26
44
 
27
45
  import { execFileSync, spawn } from 'node:child_process';
28
- import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
46
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
29
47
  import { homedir, tmpdir } from 'node:os';
30
48
  import { join } from 'node:path';
31
- import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId } from './gemini-tts.mjs';
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
+ }
32
108
 
33
- export const ENGINES = ['gemini', 'chirp', 'piper'];
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');
34
116
 
35
117
  // Chirp 3: HD ships the same roster as Gemini TTS (verified against
36
118
  // texttospeech.googleapis.com/v1/voices) — one name, two engines.
@@ -45,11 +127,7 @@ function createChirp({ project, lang = 'en-US' }) {
45
127
  async function call(text, voice) {
46
128
  const res = await fetch('https://texttospeech.googleapis.com/v1/text:synthesize', {
47
129
  method: 'POST',
48
- headers: {
49
- authorization: `Bearer ${token}`,
50
- 'content-type': 'application/json',
51
- 'x-goog-user-project': project, // ADC is a user credential — bill/quota the project, not the user
52
- },
130
+ headers: authHeaders(token, project),
53
131
  body: JSON.stringify({
54
132
  input: { text },
55
133
  voice: { languageCode: lang, name: chirpVoice(voice, lang) },
@@ -105,36 +183,49 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
105
183
  * ours — which also means the text must be flattened to a single line, or one
106
184
  * request would silently become several utterances.
107
185
  */
108
- function createPiper({ voice = 'en_US-ryan-high', dataDir }) {
186
+ function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
109
187
  try { execFileSync('piper', ['--help'], { stdio: 'ignore' }); }
110
188
  catch { throw new Error('piper not found — install with: uv tool install piper-tts'); }
111
189
  // A bare model NAME only resolves against a data dir — without one, piper
112
190
  // searches its own default and calls the voice missing even when it is
113
191
  // sitting right there. A model PATH needs no dir at all.
114
- const models = dataDir ?? join(homedir(), '.local', 'share', 'piper');
192
+ const models = dataDir ?? piperModelDir();
115
193
  const byPath = voice.includes('/') || voice.endsWith('.onnx');
116
194
 
117
- let proc = null, spool = null, seen = null;
195
+ let proc = null, spool = null;
118
196
  let fatal = null; // a config error (missing voice) — retrying cannot fix it
119
197
  let chain = Promise.resolve();
198
+ const finished = []; // paths piper has announced as written, in order
199
+ let wake = null;
120
200
 
121
201
  function ensure() {
122
202
  if (proc) return;
123
203
  if (fatal) throw new Error(fatal);
124
204
  spool = mkdtempSync(join(tmpdir(), 'decklight-piper-'));
125
- seen = new Set();
205
+ finished.length = 0;
126
206
  const p = spawn('piper', [
127
207
  '-m', voice, ...(byPath ? [] : ['--data-dir', models]),
128
208
  '-d', spool, '--output-dir-naming', 'timestamp',
129
209
  ], { stdio: ['pipe', 'ignore', 'pipe'] });
130
210
  let err = '';
131
- p.stderr.on('data', (b) => { err = (err + b).slice(-4000); });
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
+ });
132
223
  p.on('exit', (code) => {
133
224
  if (proc === p) proc = null;
134
225
  rmSync(spool, { recursive: true, force: true });
135
226
  if (/Unable to find voice/.test(err)) {
136
227
  fatal = `piper voice '${voice}' not in ${models} — fetch it with: `
137
- + `python -m piper.download_voices ${voice} --data-dir ${models}`;
228
+ + piperDownloadLine(piperDownloadCmd(voice, models));
138
229
  } else if (code) {
139
230
  // a crash is not necessarily terminal: the next call respawns
140
231
  lastExit = `piper exited (${code}) ${err.trim().split('\n').pop() ?? ''}`.trim();
@@ -144,35 +235,61 @@ function createPiper({ voice = 'en_US-ryan-high', dataDir }) {
144
235
  }
145
236
  let lastExit = null;
146
237
 
147
- // A WAV is complete when the RIFF header's declared length matches the bytes
148
- // on disk — piper patches that length when it closes the file. That is an
149
- // exact signal; "the size stopped changing" is not, since a write can simply
150
- // stall, and half a WAV is a corrupt WAV. (Belt and braces: if some build
151
- // never patched the header, fall back to a file that has not grown for ~1s.)
152
- const complete = (b) => b.length > 44 && b.readUInt32LE(4) + 8 === b.length;
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;
153
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.
154
276
  async function nextWav(timeoutMs = 180_000) {
155
277
  const t0 = Date.now();
156
- while (Date.now() - t0 < timeoutMs) {
278
+ for (;;) {
157
279
  if (!proc) throw new Error(fatal ?? lastExit ?? 'piper stopped');
158
- // one line in → one file out, in order, and we serialize: the next file
159
- // we have not seen is this request's
160
- const [name] = readdirSync(spool).filter((f) => f.endsWith('.wav') && !seen.has(f));
161
- if (name) {
162
- const f = join(spool, name);
163
- let last = -1, still = 0;
164
- for (;;) {
165
- const b = readFileSync(f);
166
- if (complete(b)) { seen.add(name); rmSync(f, { force: true }); return b; }
167
- still = b.length === last ? still + 1 : 0;
168
- last = b.length;
169
- if (still >= 12 && b.length > 44) { seen.add(name); rmSync(f, { force: true }); return b; }
170
- await sleep(80);
171
- }
280
+ const f = finished.shift();
281
+ if (f) {
282
+ const b = await drain(f);
283
+ rmSync(f, { force: true });
284
+ return b;
172
285
  }
173
- await sleep(40);
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;
174
292
  }
175
- throw new Error('piper timed out');
176
293
  }
177
294
 
178
295
  function synth(text) {
@@ -191,6 +308,11 @@ function createPiper({ voice = 'en_US-ryan-high', dataDir }) {
191
308
  // the presenter's first keypress pays the whole ~13s load, which reads as a
192
309
  // hung deck. By the time anyone has opened a slide, piper is warm.
193
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; };
194
316
  return synth;
195
317
  }
196
318
 
@@ -199,20 +321,103 @@ function createPiper({ voice = 'en_US-ryan-high', dataDir }) {
199
321
  * roster for the cloud engines, and for piper the single installed model —
200
322
  * offering 30 Gemini names it cannot speak would just be a lie.
201
323
  */
202
- export function createEngine({ engine = 'gemini', project, model, location, voice, dataDir, lang } = {}) {
203
- if (!ENGINES.includes(engine)) throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')}`);
204
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.
205
369
  if (engine === 'piper') {
206
- const m = voice ?? 'en_US-ryan-high';
370
+ const m = voice ?? PIPER_DEFAULT_VOICE;
207
371
  return {
208
372
  name: 'piper', model: m, needsProject: false, stylable: false,
373
+ cost: 'free · offline',
209
374
  voices: [[m, 'local']],
210
375
  synth: createPiper({ voice: m, dataDir }),
211
376
  };
212
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
+ }
213
417
  if (engine === 'chirp') {
214
418
  return {
215
419
  name: 'chirp', model: 'chirp3-hd', needsProject: true, stylable: false,
420
+ cost: 'first 1M chars/month free',
216
421
  voices: GEMINI_VOICES,
217
422
  synth: createChirp({ project, lang: lang ?? 'en-US' }),
218
423
  };
@@ -220,7 +425,31 @@ export function createEngine({ engine = 'gemini', project, model, location, voic
220
425
  const m = model ?? 'gemini-2.5-pro-tts';
221
426
  return {
222
427
  name: 'gemini', model: m, needsProject: true, stylable: true,
428
+ cost: 'billed per call — no free tier',
223
429
  voices: GEMINI_VOICES,
224
430
  synth: createGemini({ project, ttsModel: m, location }),
225
431
  };
226
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
+ }