decklight 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +23 -11
  2. package/SPEC.md +187 -23
  3. package/cli/agents.mjs +52 -2
  4. package/cli/associate.mjs +2 -2
  5. package/cli/banner.mjs +125 -0
  6. package/cli/bundle.mjs +15 -5
  7. package/cli/{rec.mjs → cast.mjs} +25 -8
  8. package/cli/comments.mjs +389 -0
  9. package/cli/commit-flow.mjs +157 -0
  10. package/cli/commit-message.mjs +125 -0
  11. package/cli/decklight.mjs +96 -25
  12. package/cli/dev.mjs +159 -13
  13. package/cli/edit.mjs +981 -40
  14. package/cli/git-tree.mjs +87 -0
  15. package/cli/git.mjs +22 -0
  16. package/cli/import.mjs +41 -11
  17. package/cli/init.mjs +37 -5
  18. package/cli/pdf.mjs +59 -14
  19. package/cli/port-conflict.mjs +187 -16
  20. package/cli/pptx-export.mjs +107 -0
  21. package/cli/present.mjs +8 -4
  22. package/cli/publish.mjs +25 -42
  23. package/cli/record.mjs +154 -0
  24. package/cli/review-remote.mjs +330 -0
  25. package/cli/review-store.mjs +107 -0
  26. package/cli/review-submit.mjs +292 -0
  27. package/cli/review.mjs +361 -0
  28. package/cli/serve.mjs +36 -1
  29. package/cli/skill-content.mjs +4 -1
  30. package/cli/units.mjs +2 -2
  31. package/cli/util.mjs +59 -0
  32. package/dist/build-info.json +1 -0
  33. package/dist/decklight.css +254 -1
  34. package/dist/decklight.js +153 -79
  35. package/dist/decklight.js.map +4 -4
  36. package/docs/architecture.svg +10 -3
  37. package/package.json +3 -1
  38. package/tools/args.mjs +20 -0
  39. package/tools/bridge.mjs +25 -2
  40. package/tools/deck-html.mjs +59 -0
  41. package/tools/elevenlabs-tts.mjs +3 -3
  42. package/tools/exec.mjs +54 -0
  43. package/tools/gemini-tts.mjs +4 -4
  44. package/tools/lipsync-server.mjs +70 -2
  45. package/tools/lipsync.mjs +46 -30
  46. package/tools/local-voice.mjs +243 -19
  47. package/tools/pptx-write.mjs +151 -0
  48. package/tools/pptx.mjs +82 -2
  49. package/tools/publish-site-voices.mjs +2 -2
  50. package/tools/publish-targets.mjs +39 -2
  51. package/tools/publish-voices.mjs +80 -20
  52. package/tools/recording-impact.mjs +110 -0
  53. package/tools/review-anchor.mjs +180 -0
  54. package/tools/template-theme.mjs +154 -0
  55. package/tools/test-impact.mjs +266 -0
  56. package/tools/tts-cache.mjs +191 -0
  57. package/tools/tts-engines.mjs +85 -8
  58. package/tools/tts-setup.mjs +4 -3
  59. package/tools/video.mjs +21 -6
  60. package/tools/voiceover-server.mjs +163 -17
  61. package/tools/voiceover.mjs +124 -16
@@ -47,11 +47,14 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
47
47
  import { homedir, tmpdir } from 'node:os';
48
48
  import { delimiter, join } from 'node:path';
49
49
  import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId, authHeaders } from './gemini-tts.mjs';
50
+ import { run, PROBE_MS } from './exec.mjs';
50
51
  import {
51
52
  createSynth as createElevenLabs, apiKey as elevenLabsKey, KEY_ENV as ELEVENLABS_KEY_ENV,
52
53
  DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL,
53
54
  } from './elevenlabs-tts.mjs';
54
- import { detectLocalVoice, sayArgs, sapiArgs } from './local-voice.mjs';
55
+ import {
56
+ detectLocalVoice, sayArgs, sapiArgs, winrtArgs, TIER_LABEL, withoutSupersededPlain,
57
+ } from './local-voice.mjs';
55
58
 
56
59
  export const ENGINES = ['gemini', 'chirp', 'piper', 'elevenlabs', 'say', 'sapi'];
57
60
  /** The two engines that are already on the machine — nothing to install. */
@@ -70,7 +73,7 @@ const onPath = (bin) => {
70
73
  } catch { return false; }
71
74
  };
72
75
  const canImportPiper = (py) => {
73
- try { execFileSync(py, ['-c', 'import piper.download_voices'], { stdio: 'ignore' }); return true; }
76
+ try { run(py, ['-c', 'import piper.download_voices'], { stdio: 'ignore', timeout: PROBE_MS }); return true; }
74
77
  catch { return false; }
75
78
  };
76
79
 
@@ -184,7 +187,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
184
187
  * request would silently become several utterances.
185
188
  */
186
189
  function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
187
- try { execFileSync('piper', ['--help'], { stdio: 'ignore' }); }
190
+ try { run('piper', ['--help'], { stdio: 'ignore', timeout: PROBE_MS }); }
188
191
  catch { throw new Error('piper not found — install with: uv tool install piper-tts'); }
189
192
  // A bare model NAME only resolves against a data dir — without one, piper
190
193
  // searches its own default and calls the voice missing even when it is
@@ -333,9 +336,26 @@ function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
333
336
  * Neither takes a delivery instruction, so both are `stylable: false` and the
334
337
  * picker skips the tone step, exactly as it does for piper and ElevenLabs.
335
338
  */
336
- function createNative({ kind, voice, shell = 'powershell.exe', voices = [] }) {
339
+ /**
340
+ * How long one sentence may take before the synthesizer is declared wedged.
341
+ *
342
+ * `say -o` renders far faster than real time — a whole slide's notes is a few
343
+ * seconds — so this is not a budget, it is a tripwire. The failure it exists
344
+ * for: macOS's speech server (speechsynthesisd) can deadlock under concurrent
345
+ * `say` calls, and the child then sits forever with no CPU and no output.
346
+ * Unbounded, that hung `decklight voiceover` indefinitely with no message,
347
+ * and hung the unit suite for eight minutes before anyone looked.
348
+ */
349
+ export const NATIVE_TIMEOUT_MS = 60_000;
350
+
351
+ function createNative({
352
+ kind, voice, shell = 'powershell.exe', voices = [], api = null, timeoutMs = NATIVE_TIMEOUT_MS,
353
+ }) {
337
354
  const bin = kind === 'say' ? 'say' : shell;
338
- const build = kind === 'say' ? sayArgs : sapiArgs;
355
+ // on Windows the API decides the voices: WinRT sees the natural ones,
356
+ // System.Speech only the 2006 roster — detectLocalVoice chose, and the
357
+ // synthesis must speak through the same stack that listed the voice
358
+ const build = kind === 'say' ? sayArgs : api === 'winrt' ? winrtArgs : sapiArgs;
339
359
  // The roster this machine actually has, for the guard below. Held as names
340
360
  // because that is what the player sends and what `say -v` takes.
341
361
  const known = new Set(voices.map((v) => v?.name ?? v).filter(Boolean));
@@ -366,7 +386,11 @@ function createNative({ kind, voice, shell = 'powershell.exe', voices = [] }) {
366
386
  const dir = mkdtempSync(join(tmpdir(), 'decklight-native-'));
367
387
  const file = join(dir, 'out.wav');
368
388
  try {
369
- execFileSync(bin, build(line, pick, file), { stdio: ['ignore', 'ignore', 'pipe'] });
389
+ // SIGKILL, not the default SIGTERM: a wedged synthesizer is blocked in a
390
+ // syscall and a polite signal is exactly what it is not answering.
391
+ execFileSync(bin, build(line, pick, file), {
392
+ stdio: ['ignore', 'ignore', 'pipe'], timeout: timeoutMs, killSignal: 'SIGKILL',
393
+ });
370
394
  const wav = readFileSync(file);
371
395
  if (!wav.length) throw new Error(`${kind} produced no audio`);
372
396
  // `{ wav, usage }`, like every other engine and like this file's own
@@ -381,6 +405,15 @@ function createNative({ kind, voice, shell = 'powershell.exe', voices = [] }) {
381
405
  usage: { model: pick ?? kind, chars: line.length, cost: 0, note: `${line.length} chars · local` },
382
406
  };
383
407
  } catch (e) {
408
+ // A timeout is not "synthesis failed": the words were fine, the daemon
409
+ // is stuck, and the fix is a restart of IT — say so, or the next thing
410
+ // the person tries is rewording the sentence.
411
+ if (e.code === 'ETIMEDOUT' || e.signal === 'SIGKILL') {
412
+ throw new Error(`${kind} hung for ${Math.round(timeoutMs / 1000)}s and was killed — `
413
+ + (kind === 'say'
414
+ ? 'macOS\'s speech synthesizer can deadlock under concurrent calls; retry, or restart it: killall speechsynthesisd'
415
+ : 'the speech stack is not answering; retry'));
416
+ }
384
417
  throw new Error(`${kind}: ${String(e.stderr ?? e.message).trim().split('\n')[0] || 'synthesis failed'}`);
385
418
  } finally {
386
419
  rmSync(dir, { recursive: true, force: true });
@@ -394,6 +427,9 @@ export function createEngine({
394
427
  // built — and its voice handling asserted — on a machine that is not the one
395
428
  // the test happens to run on.
396
429
  detect = detectLocalVoice,
430
+ // The wedge tripwire (NATIVE_TIMEOUT_MS), injectable so a test can prove it
431
+ // fires without waiting a minute for it to.
432
+ nativeTimeoutMs,
397
433
  } = {}) {
398
434
  if (!ENGINES.includes(engine)) {
399
435
  throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')},`
@@ -406,6 +442,12 @@ export function createEngine({
406
442
  const m = voice ?? PIPER_DEFAULT_VOICE;
407
443
  return {
408
444
  name: 'piper', model: m, needsProject: false, stylable: false,
445
+ // piper's synth takes only text: the model is loaded once and a
446
+ // per-sentence voice request does nothing. The clip cache keys on the
447
+ // MODEL for this engine and ignores the asked-for voice, or two runs
448
+ // under different --voice models would collide on one key (SPEC
449
+ // `NARRATION`).
450
+ voiceIsFixed: true,
409
451
  cost: 'free · offline',
410
452
  voices: [[m, 'local']],
411
453
  synth: createPiper({ voice: m, dataDir }),
@@ -415,12 +457,47 @@ export function createEngine({
415
457
  const detected = detect({ lang });
416
458
  const pick = voice ?? detected.voices?.[0]?.name;
417
459
  if (!pick) throw new Error(detected.why ?? `no ${engine} voices on this machine`);
460
+ // The deck's language decides which voices get quality shelves; the rest
461
+ // share ONE group at the tail — contiguous by construction, because
462
+ // parseSayVoices sorts language first. ~140 of a real Mac's rows are
463
+ // other languages, and shelving them by quality answered a question
464
+ // nobody browsing an English deck was asking.
465
+ const want = (lang ?? 'en').slice(0, 2).toLowerCase();
466
+ const groupOf = (v) => (!Number.isInteger(v.tier) ? undefined
467
+ : (v.locale || '').toLowerCase().startsWith(want) ? TIER_LABEL[v.tier]
468
+ : 'other languages');
418
469
  return {
419
470
  name: engine, model: pick, needsProject: false, stylable: false,
471
+ // `model` here is the voice this process BOOTED with, not a model — and
472
+ // createNative honours a different voice per sentence, so the boot voice
473
+ // says nothing about how a given clip sounds. The cache keys on the
474
+ // spoken voice alone; including this would file one sentence in one
475
+ // voice under as many names as there are bridges (SPEC `NARRATION`).
476
+ modelIsDefaultVoice: true,
420
477
  cost: 'free · offline · already on this machine',
421
- voices: (detected.voices ?? []).map((v) => [v.name, v.locale || 'system']),
478
+ // [name, flavor, group]: the quality category travels as a STRUCTURED
479
+ // third element (best · good · average) and the picker draws it as a
480
+ // labelled separator over each shelf — the roster mixes this year's
481
+ // neural voices with 1990s robots under names that reveal nothing. The
482
+ // flavor stays the locale alone; repeating the category on every row
483
+ // was the suffix wallpaper the separators replace.
484
+ // One cut, and only one: `Daniel` goes when `Daniel (Enhanced)` is on
485
+ // the same list, because that is one voice offered twice and the worse
486
+ // row is not a choice. Everything else stays — the robots and personas
487
+ // because the picker already folds them to a single EXPANDABLE row, and
488
+ // a voice like Samantha because sharing a language with a Premium one
489
+ // does not make her a duplicate of it. `pick` survives regardless: it
490
+ // may have been named on the command line. The GUARD below keeps the
491
+ // FULL roster — hiding a voice must not turn saying it into an error.
492
+ voices: withoutSupersededPlain(detected.voices ?? [], { keep: pick })
493
+ .map((v) => [v.name, v.locale || 'system', groupOf(v)]),
494
+ // "download a Siri voice" rides the same channel every engine caveat
495
+ // does: the bridge's startup line and the deck's toast on switching
496
+ ...(detected.caveat ? { caveat: detected.caveat } : {}),
422
497
  synth: createNative({
423
498
  kind: engine, voice: pick, shell: detected.shell, voices: detected.voices ?? [],
499
+ api: detected.api ?? null,
500
+ ...(nativeTimeoutMs ? { timeoutMs: nativeTimeoutMs } : {}),
424
501
  }),
425
502
  };
426
503
  }
@@ -444,7 +521,7 @@ export function createEngine({
444
521
  caveat: isV3
445
522
  ? 'eleven_v3: higher latency, more variable consistency, and ElevenLabs '
446
523
  + 'recommends prompts over ~250 characters — a live decklight sentence is '
447
- + 'shorter than that, so delivery may vary more than a ⇧V recording.'
524
+ + 'shorter than that, so delivery may vary more than a recorded take (V → Record this deck…).'
448
525
  : undefined,
449
526
  // the real roster arrives from the account; until it does the picker has
450
527
  // nothing truthful to show, which is better than thirty names it cannot say
@@ -27,9 +27,10 @@ import {
27
27
  } from './tts-engines.mjs';
28
28
  import { gcloudToken, validProjectId } from './gemini-tts.mjs';
29
29
  import { KEY_ENV as ELEVENLABS_KEY_ENV, apiKey as elevenLabsKey } from './elevenlabs-tts.mjs';
30
+ import { run, NETWORK_MS } from './exec.mjs';
30
31
 
31
32
  // The picker's preview default (SPEC PRESENTING) — the wizard's proof is the same
32
- // audio the deck's N picker previews.
33
+ // audio the deck's V picker previews.
33
34
  export const TEST_SENTENCE = 'Hey, this is Decklight';
34
35
 
35
36
  /** The saved answers live at ~/.config/decklight/tts.json — $XDG_CONFIG_HOME honored. */
@@ -54,8 +55,8 @@ export function saveTtsConfig(config, env = process.env) {
54
55
  /** The project gcloud is configured with — the prefill when $GOOGLE_CLOUD_PROJECT is unset. */
55
56
  export function gcloudConfigProject() {
56
57
  try {
57
- const out = execFileSync('gcloud', ['config', 'get-value', 'project'],
58
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
58
+ const out = run('gcloud', ['config', 'get-value', 'project'],
59
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: NETWORK_MS }).trim();
59
60
  return out && !out.startsWith('(') ? out : null; // '(unset)' when none
60
61
  } catch { return null; }
61
62
  }
package/tools/video.mjs CHANGED
@@ -32,7 +32,7 @@
32
32
  // in one extra load, because the grouping is the runtime's and a second counter
33
33
  // written here would be a copy that drifts.
34
34
 
35
- import { execFile, execFileSync, spawnSync } from 'node:child_process';
35
+ import { execFile, spawnSync } from 'node:child_process';
36
36
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
37
  import { tmpdir } from 'node:os';
38
38
  import { basename, join, relative, resolve, sep } from 'node:path';
@@ -40,8 +40,9 @@ import { promisify } from 'node:util';
40
40
  import { fileURLToPath } from 'node:url';
41
41
  import { chromeBin, chromeArgs } from './chrome.mjs';
42
42
  import { argReader, isMain } from './args.mjs';
43
- import { injectBeforeBodyEnd, sectionBodies } from './deck-html.mjs';
43
+ import { injectBeforeBodyEnd, sectionBodies, isHiddenSection } from './deck-html.mjs';
44
44
  import { serveForRender } from '../cli/present.mjs';
45
+ import { run as runBounded, PROBE_MS } from './exec.mjs';
45
46
 
46
47
  const run = promisify(execFile);
47
48
 
@@ -109,19 +110,31 @@ export function extractHolds(html, defaultHold) {
109
110
  }
110
111
 
111
112
  /**
112
- * Per-slide narration beat: data-narration-pause="2" on the section, else 0.
113
+ * The runtime's built-in hold before a slide turns (SLIDE_PAUSE_S in
114
+ * src/core/narration.js — not imported, because src/ does not ship in the
115
+ * package; test/video.test.mjs pins the two equal). An exported mp4 must
116
+ * breathe where the live deck does, and the live deck now breathes here by
117
+ * default.
118
+ */
119
+ export const SLIDE_PAUSE_DEFAULT = 1;
120
+
121
+ /**
122
+ * Per-slide narration beat: data-narration-pause="2" on the section, else
123
+ * the built-in default above.
113
124
  *
114
125
  * The recorded mirror of the live rule (PRESENTING): src/core/narration.js
115
126
  * holds that many seconds after a slide's last sentence before moving on, and
116
127
  * an exported mp4 must breathe in the same places the deck does. Read off the
117
128
  * raw open tag, like extractHolds, so the same attribute appearing in a
118
- * slide's CONTENT cannot be mistaken for the slide's own.
129
+ * slide's CONTENT cannot be mistaken for the slide's own. (The deck-wide
130
+ * `narration.slidePause` config tier is not read here: it lives inside the
131
+ * boot call, and this reads sections, not scripts.)
119
132
  */
120
133
  export function extractPauses(html) {
121
134
  return sectionBodies(html).map((sec) => {
122
135
  const tag = sec.slice(0, sec.indexOf('>'));
123
136
  const m = tag.match(/data-narration-pause="([\d.]+)"/);
124
- return m ? Number(m[1]) : 0;
137
+ return m ? Number(m[1]) : SLIDE_PAUSE_DEFAULT;
125
138
  });
126
139
  }
127
140
 
@@ -297,7 +310,7 @@ export function resolveNarration(deckPath, narrationDir) {
297
310
  }
298
311
 
299
312
  const have = (bin) => {
300
- try { execFileSync(bin, ['-version'], { stdio: 'ignore' }); return true; }
313
+ try { runBounded(bin, ['-version'], { stdio: 'ignore', timeout: PROBE_MS }); return true; }
301
314
  catch (e) { return e?.code !== 'ENOENT'; }
302
315
  };
303
316
 
@@ -410,7 +423,9 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
410
423
 
411
424
  // real durations, not the manifest's word count: ffprobe each audio file
412
425
  const durations = {};
426
+ const hidden = sectionBodies(html).map(isHiddenSection);
413
427
  for (let n = range.from; n <= range.to; n++) {
428
+ if (hidden[n - 1]) continue; // a hidden slide keeps its number and gets no frame
414
429
  const entry = narration?.slides?.[n - 1];
415
430
  // The slide's own audio AND its ⟨CLICK⟩ segments. Measured here rather
416
431
  // than trusted from the manifest, for the reason the per-slide durations
@@ -32,23 +32,81 @@
32
32
  // first, so /ping and /voices await that lookup rather than guessing.
33
33
  //
34
34
  // CORS is wide open (decks run on file://, origin "null") — the server binds
35
- // 127.0.0.1 only. Responses are cached in memory by (text, voice, style), so
36
- // stepping back through slides replays instantly and costs nothing.
35
+ // 127.0.0.1 only. Responses are cached in memory AND on disk (tools/tts-cache.mjs)
36
+ // by (engine, model, format, voice, style, text), so stepping back through
37
+ // slides replays instantly, a restarted bridge replays for free, and
38
+ // `decklight voiceover` reuses whatever this bridge already said.
37
39
 
38
40
  import { createServer } from 'node:http';
39
- import { createHash } from 'node:crypto';
40
41
  import { createInterface } from 'node:readline/promises';
42
+ import { canBind, resolvePortConflict } from '../cli/port-conflict.mjs';
43
+ import { execFile } from 'node:child_process';
44
+ import { cacheHome, clipKey, createTtsCache, extFor } from './tts-cache.mjs';
45
+
46
+ /**
47
+ * The one exec a deck may trigger: open macOS's voice-download pane.
48
+ *
49
+ * The argv is a FROZEN CONSTANT — no byte of any request reaches it — and it
50
+ * opens a System Settings pane and nothing else; the download itself stays a
51
+ * human clicking through, which is the point of the pane. `exec` is injected
52
+ * so the test can assert the argv without a Settings window opening mid-suite.
53
+ */
54
+ export const VOICE_SETTINGS_URI = 'x-apple.systempreferences:com.apple.preference.universalaccess';
55
+ /** …and Windows' Narrator page, where "Add natural voices" lives. */
56
+ export const WINDOWS_VOICE_SETTINGS_URI = 'ms-settings:easeofaccess-narrator';
57
+ export function openVoiceSettings(exec = execFile, platform = process.platform) {
58
+ if (platform === 'win32') {
59
+ // `start` is a cmd builtin; the empty "" is its title argument, so the
60
+ // URI is never mistaken for one. Every token is a constant.
61
+ exec('cmd', ['/c', 'start', '""', WINDOWS_VOICE_SETTINGS_URI], () => { /* fire and forget */ });
62
+ return;
63
+ }
64
+ exec('open', [VOICE_SETTINGS_URI], () => { /* fire and forget — Settings owns the rest */ });
65
+ }
41
66
  import { resolveEngine, engineBlocker, engineMenu, engineStatus, ENGINES } from './tts-engines.mjs';
42
67
  import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
43
68
  import { argReader, isMain } from './args.mjs';
44
69
  import { corsHeaders, readBody } from './bridge.mjs';
45
70
  import { installedVoices } from '../cli/units.mjs';
71
+ import { readyLine } from '../cli/banner.mjs';
72
+
73
+ /** One line from the terminal, for the taken-port question. Closed straight after. */
74
+ async function askLine(prompt) {
75
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
76
+ // EOF ANSWERS THE SAFE WAY. `rl.question` never settles if the input closes
77
+ // first (a Ctrl-D, a terminal whose stdin is a spent pipe), and an unsettled
78
+ // promise here aborted the bridge through the top-level handler — reported to
79
+ // the user as "this one is a bug, please report it", over a question about a
80
+ // port. An empty answer is the declining answer everywhere it is read.
81
+ try {
82
+ return await new Promise((resolve) => {
83
+ // `line` is registered FIRST and readline emits it before `close`, so a
84
+ // key that was actually typed always beats the EOF that follows it. The
85
+ // two racing as promises did not: a piped `k\n` lost to the close and
86
+ // read as a decline, which is a terrible way to lose a keystroke.
87
+ let answered = false;
88
+ const done = (v) => { if (!answered) { answered = true; resolve(v); } };
89
+ rl.once('line', done);
90
+ rl.once('close', () => done(''));
91
+ rl.setPrompt(prompt);
92
+ rl.prompt();
93
+ });
94
+ } finally { rl.close(); }
95
+ }
46
96
 
47
97
  export async function ttsMain(args) {
98
+ // A clean exit on SIGTERM, not the default abrupt one. The difference is
99
+ // invisible in production and decisive under test: V8 writes a process's
100
+ // coverage only when it exits through process.exit, so a bridge the suite
101
+ // stops with SIGKILL — or with an unhandled SIGTERM — reports NOTHING, and
102
+ // the request handler that is this file's whole point read as 27% covered
103
+ // while thirty tests drove it. The edit and present servers already do this.
104
+ process.on('SIGTERM', () => process.exit(0));
48
105
  if (args.includes('--help')) {
49
106
  console.log(`usage: decklight tts [--port 8787] [--engine ${ENGINES.join('|')}|<installed>] [--project <id>]
50
107
  [--tts-model id] [--location global] [--voice name] [--data-dir dir] [--lang en-US]
51
108
  [--tts-format pcm|mp3] [--tts-stability creative|natural|robust] [--setup]
109
+ [--no-cache]
52
110
 
53
111
  gemini gemini-2.5-pro-tts (default) or --tts-model gemini-2.5-flash-tts — Vertex AI, best
54
112
  delivery, the only engine that honors a style instruction. No free tier.
@@ -63,13 +121,20 @@ export async function ttsMain(args) {
63
121
  the picker's tone step appears for.
64
122
  --tts-stability creative|natural|robust — how hard v3 follows a tag (v3 only;
65
123
  refused on any other model rather than silently doing nothing).
66
- --tts-format mp3 if your plan has no PCM output (costs you ⇧V and lip-sync).
124
+ --tts-format mp3 if your plan has no PCM output (costs you the panel's
125
+ Record this deck… and lip-sync, both of which read WAV).
67
126
 
68
127
  <installed> any engine from a marketplace (decklight engine add <name>) — --engine
69
128
  takes its name like any of the six above, and the picker treats it the same.
70
129
 
71
130
  project also read from $GOOGLE_CLOUD_PROJECT (gemini and chirp only)
72
131
 
132
+ cache every synthesis is kept in ${cacheHome()} under a key made of
133
+ (engine, model, format, voice, style, text), so a restarted bridge
134
+ replays for free and 'decklight voiceover' reuses what you already
135
+ previewed instead of paying for it twice. Oldest clips are dropped
136
+ past 400 MB. --no-cache re-synthesizes everything, for a fresh take.
137
+
73
138
  first run: with nothing configured on a terminal, tts asks a few guided
74
139
  questions (engine, prerequisites, one test synthesis) and saves the answers
75
140
  to ${ttsConfigPath()} — --setup re-runs them.
@@ -167,6 +232,16 @@ export async function ttsMain(args) {
167
232
  // engine's audio under another's voice — the cache survives the switch, and
168
233
  // switching back replays instantly rather than re-billing.
169
234
  const cache = new Map();
235
+ // The DISK half (tools/tts-cache.mjs), for EVERY engine including the paid
236
+ // ones. Warming 184 say previews took ~6 minutes of background synthesis and
237
+ // should cost that once per machine rather than once per bridge — and an
238
+ // ElevenLabs sentence should be paid for once per sentence, not once per
239
+ // process, which is what a memory-only cache charged for a preview here and
240
+ // a batch recording ten minutes later. The MODEL is in the key, so a cloud
241
+ // engine changing its model underneath us is a miss rather than a stale clip.
242
+ // `--no-cache` opts out for a deliberate re-roll.
243
+ const disk = createTtsCache({ enabled: !args.includes('--no-cache') });
244
+ disk.prune();
170
245
 
171
246
  // What the bridge could become, and what stands in the way. The options the
172
247
  // deck's picker draws (SPEC `NARRATION`).
@@ -202,9 +277,31 @@ export async function ttsMain(args) {
202
277
  engine: engine.name,
203
278
  model: engine.model,
204
279
  stylable: engine.stylable, // gemini alone can be told HOW to say it
280
+ // the engine's standing note — for `say` with no Siri voice this is
281
+ // the download hint, and the picker keys its install row off it
282
+ ...(engine.caveat ? { caveat: engine.caveat } : {}),
205
283
  voices, // piper speaks one voice, not the star roster
206
284
  }));
207
285
  }
286
+ // ── the one exec a deck may trigger: open the voice-download pane ──
287
+ // Darwin only, loopback only (like every route here), and the argv is a
288
+ // FROZEN CONSTANT — no byte of the request reaches it. It opens a System
289
+ // Settings pane and does nothing else; the download itself stays a human
290
+ // clicking, which is the whole point of the pane.
291
+ if (req.method === 'POST' && req.url === '/voices/install') {
292
+ if (process.platform !== 'darwin' && process.platform !== 'win32') { res.writeHead(404); return res.end(); }
293
+ try {
294
+ openVoiceSettings();
295
+ console.log(process.platform === 'win32'
296
+ ? ' voices: opened Settings → Accessibility → Narrator (add natural voices, then restart me)'
297
+ : ' voices: opened System Settings → Accessibility (download a Siri voice, then restart me)');
298
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
299
+ return res.end(JSON.stringify({ ok: true }));
300
+ } catch (e) {
301
+ res.writeHead(500, { ...CORS, 'content-type': 'application/json' });
302
+ return res.end(JSON.stringify({ ok: false, error: String(e?.message ?? e) }));
303
+ }
304
+ }
208
305
  // ── which engine is speaking, and what else could (SPEC `NARRATION`) ──
209
306
  if (req.method === 'GET' && req.url === '/engines') {
210
307
  // Ready or not, every engine is listed. Hiding the ones this machine
@@ -278,18 +375,25 @@ export async function ttsMain(args) {
278
375
  const { text, voice: picked, style } = JSON.parse((await readBody(req)).toString());
279
376
  if (!text?.trim()) { res.writeHead(400, CORS); return res.end('no text'); }
280
377
  const voice = refIds.get(picked) ?? picked;
281
- // NUL joins the fields so they cannot run together (a style ending in a
282
- // space and a text starting with one must not hash like their neighbours)
283
- // — but written as an ESCAPE, not a raw byte. This file used to carry
284
- // literal NULs, and git calls any file with one in its first 8 KB binary:
285
- // it silently became undiffable and unreviewable.
286
- const key = createHash('sha256')
287
- .update([engine.name, voice, style, text].join('\u0000')).digest('hex');
288
- const fresh = !cache.has(key);
378
+ // The key is the SAME function `decklight voiceover` hashes with, and
379
+ // that is the point: a sentence previewed here and then batch-recorded
380
+ // is one synthesis, not two identical bills (SPEC `NARRATION`).
381
+ const ext = extFor(engine.synth.mimeType ?? 'audio/wav');
382
+ const key = clipKey(engine, { voice, style, text });
383
+ let fresh = !cache.has(key);
384
+ if (fresh) {
385
+ const bytes = disk.read(key, ext);
386
+ if (bytes) {
387
+ cache.set(key, { wav: bytes, usage: { chars: 0, cost: 0, note: 'cached on disk' } });
388
+ fresh = false;
389
+ console.log(` ${engine.name} ${picked}: ${text.length} chars · cached on disk`);
390
+ }
391
+ }
289
392
  if (fresh) {
290
393
  process.stdout.write(` ${engine.name} ${picked}: ${text.length} chars … `);
291
394
  const t0 = Date.now();
292
395
  cache.set(key, await engine.synth(text, { voice, style }));
396
+ disk.write(key, cache.get(key).wav, ext);
293
397
  const u = cache.get(key).usage;
294
398
  // `cost` is OPTIONAL, and an installed engine is why (SPEC
295
399
  // ENGINE_UNITS): the six built-ins all happen to report one, so
@@ -340,7 +444,41 @@ export async function ttsMain(args) {
340
444
  res.end();
341
445
  });
342
446
 
343
- server.listen(port, '127.0.0.1', () => {
447
+ // A TAKEN PORT IS NOT A CRASH. Without this the bind threw EADDRINUSE as an
448
+ // unhandled 'error' event: a raw Node stack trace in the middle of author's
449
+ // startup output, which reads as decklight falling over when the truth is
450
+ // that something else has the port. The edit server has resolved conflicts
451
+ // for a long time (cli/port-conflict.mjs) — the bridges simply never called
452
+ // it, so they were the one place the deck could still look broken.
453
+ //
454
+ // On a TTY it names the occupant and offers a choice; anywhere else — and
455
+ // author spawns these with a piped stdin, so that is the usual case — it
456
+ // moves to the next free port and says so. The player finds the bridge by
457
+ // probing, so a moved port costs nothing.
458
+ // `canBind`, NOT `isPortOpen`: this file's own note says why, and getting it
459
+ // wrong the first time proved the point. `isPortOpen` CONNECTS, answering "is
460
+ // somebody there" — a listener that never accepts (backlog full, or a socket
461
+ // opened and ignored) refuses the connect and reads as free, and then the
462
+ // bind fails anyway. "May I have this port" is a different question and only
463
+ // a trial bind answers it.
464
+ //
465
+ // `--port 0` is "let the OS pick", which cannot conflict — resolving it would
466
+ // turn a deliberate 0 into port 1. Only a REAL port that is taken gets the
467
+ // question; everything else binds exactly as before.
468
+ const asked = port && !(await canBind(port))
469
+ ? await resolvePortConflict(port, {
470
+ kind: 'bridge',
471
+ ask: process.stdin.isTTY && process.stdout.isTTY ? askLine : undefined,
472
+ log: console.log,
473
+ })
474
+ : port;
475
+ // null is "stand down" — either a bridge is already serving this port, or
476
+ // somebody else holds it and this one cannot move (the deck only ever calls
477
+ // the one number). Exiting is the honest outcome: author prints "carrying on
478
+ // without it" and the deck degrades where you can see it, instead of a
479
+ // bridge running somewhere nothing will ever knock.
480
+ if (asked === null) process.exit(0);
481
+ server.listen(asked, '127.0.0.1', () => {
344
482
  // The BOUND port, not the requested one: `--port 0` legitimately means
345
483
  // "pick a free one", and printing the 0 back made the one line telling a
346
484
  // presenter where their bridge is into an unusable URL.
@@ -348,10 +486,18 @@ export async function ttsMain(args) {
348
486
  // `cost` is optional (SPEC ENGINE_UNITS) — an installed engine that
349
487
  // quotes no list price says nothing here rather than "(undefined)".
350
488
  const price = engine.cost ? ` (${engine.cost})` : '';
351
- console.log(`decklight tts bridge on http://127.0.0.1:${bound} — ${engine.name} · ${engine.model}${price} — Ctrl-C stops`);
352
- // Stated here, once, where the presenter is still choosing — not
353
- // discovered mid-talk when the delivery already varied more than expected.
354
- if (engine.caveat) console.log(` ${engine.caveat}`);
489
+ // Under author this is a banner ROW, not a line: author prints one block
490
+ // ending in the DECK's url, and a bridge url above it is the wrong thing
491
+ // to click. Standalone, the bridge is the whole program and says so.
492
+ if (process.env.DECKLIGHT_BANNER) {
493
+ console.log(readyLine({ key: 'voice', text: `${engine.name} · ${engine.model}${price} — on :${bound}` }));
494
+ if (engine.caveat) console.log(readyLine({ key: 'voice', text: engine.caveat }));
495
+ } else {
496
+ console.log(`decklight tts bridge on http://127.0.0.1:${bound} — ${engine.name} · ${engine.model}${price} — Ctrl-C stops`);
497
+ // Stated here, once, where the presenter is still choosing — not
498
+ // discovered mid-talk when the delivery already varied more than expected.
499
+ if (engine.caveat) console.log(` ${engine.caveat}`);
500
+ }
355
501
  // piper loads a ~120 MB model on start; do it now, while the deck is still
356
502
  // being opened, so the first sentence isn't a 13-second silence
357
503
  if (engine.synth.warm) {