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
@@ -18,7 +18,7 @@
18
18
  <text x="155" y="136" text-anchor="middle" font-size="10.5" fill="#aeb4c6">one file, written by humans &amp; agents</text>
19
19
 
20
20
  <rect x="40" y="186" width="230" height="72" rx="10" fill="#23444d" stroke="#3f6a76" stroke-width="1.5"/>
21
- <text x="155" y="212" text-anchor="middle" font-size="13" font-weight="700" fill="#e8eaf2">theme.css — 61 shipped</text>
21
+ <text x="155" y="212" text-anchor="middle" font-size="13" font-weight="700" fill="#e8eaf2">theme.css — 46 shipped themes</text>
22
22
  <text x="155" y="232" text-anchor="middle" font-size="10.5" fill="#aeb4c6">one token contract (~50 vars)</text>
23
23
  <text x="155" y="246" text-anchor="middle" font-size="10.5" fill="#aeb4c6">+ runtime generator (⌃T)</text>
24
24
 
@@ -31,7 +31,7 @@
31
31
  <rect x="348" y="126" width="140" height="30" rx="6" fill="#252a3a"/><text x="418" y="145" text-anchor="middle">engine · builds · nav</text>
32
32
  <rect x="500" y="126" width="142" height="30" rx="6" fill="#252a3a"/><text x="571" y="145" text-anchor="middle">themes · generator</text>
33
33
  <rect x="348" y="164" width="140" height="30" rx="6" fill="#252a3a"/><text x="418" y="183" text-anchor="middle">terminal player</text>
34
- <rect x="500" y="164" width="142" height="30" rx="6" fill="#252a3a"/><text x="571" y="183" text-anchor="middle">markdown · svg · code</text>
34
+ <rect x="500" y="164" width="142" height="30" rx="6" fill="#252a3a"/><text x="571" y="183" text-anchor="middle">svg · code · math</text>
35
35
  <rect x="348" y="202" width="140" height="30" rx="6" fill="#252a3a"/><text x="418" y="221" text-anchor="middle">narration · captions</text>
36
36
  <rect x="500" y="202" width="142" height="30" rx="6" fill="#252a3a"/><text x="571" y="221" text-anchor="middle">speaker · overlays</text>
37
37
  <rect x="348" y="240" width="294" height="30" rx="6" fill="#252a3a"/><text x="495" y="259" text-anchor="middle">quiz slides · transcript · debug log · edit mode</text>
@@ -57,13 +57,20 @@
57
57
  <rect x="40" y="356" width="620" height="86" rx="10" fill="#52402a" stroke="#7d6544" stroke-width="1.5"/>
58
58
  <text x="350" y="382" text-anchor="middle" font-size="13" font-weight="700" fill="#e8eaf2">CLI — node, the only place with native deps</text>
59
59
  <g font-size="10.5" fill="#efe9dd">
60
- <rect x="58" y="396" width="130" height="30" rx="6" fill="#453722"/><text x="123" y="415" text-anchor="middle">rec — real PTY casts</text>
60
+ <rect x="58" y="396" width="130" height="30" rx="6" fill="#453722"/><text x="123" y="415" text-anchor="middle">cast — real PTY casts</text>
61
61
  <rect x="200" y="396" width="130" height="30" rx="6" fill="#453722"/><text x="265" y="415" text-anchor="middle">refresh — drift check</text>
62
62
  <rect x="342" y="396" width="140" height="30" rx="6" fill="#453722"/><text x="412" y="415" text-anchor="middle">export — asciicast v2</text>
63
63
  <rect x="494" y="396" width="148" height="30" rx="6" fill="#453722"/><text x="568" y="415" text-anchor="middle">bundle — one-file deck</text>
64
64
  </g>
65
65
 
66
66
  <!-- ── verification band ────────────────────────────────────────── -->
67
+ <!-- decklight review — a third localhost server, and the only one whose write
68
+ surface is a single sidecar file (SPEC REVIEW) -->
69
+ <rect x="710" y="356" width="180" height="86" rx="10" fill="#274035" stroke="#43695a" stroke-width="1.5"/>
70
+ <text x="800" y="382" text-anchor="middle" font-size="13" font-weight="700" fill="#e8eaf2">decklight review</text>
71
+ <text x="800" y="400" text-anchor="middle" font-size="10.5" fill="#aeb4c6">M leaves comments on a slide</text>
72
+ <text x="800" y="416" text-anchor="middle" font-size="10.5" fill="#aeb4c6">writes deck.review.jsonl only</text>
73
+ <text x="800" y="432" text-anchor="middle" font-size="10.5" fill="#aeb4c6">git carries it · no /edit/*</text>
67
74
  <rect x="40" y="470" width="850" height="60" rx="10" fill="#1c2620" stroke="#39584a" stroke-width="1.5"/>
68
75
  <text x="465" y="494" text-anchor="middle" font-size="12.5" font-weight="700" fill="#9fd6b4">verification — SPEC.md is the contract</text>
69
76
  <text x="465" y="514" text-anchor="middle" font-size="10.5" fill="#8fae9c">WCAG contrast gates · R1–R8 palette rules · headless render assertions · property tests across seeds · data-overflow guardrail</text>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "A presentation library designed to be authored by AI agents and humans alike: single-file decks, Keynote-style builds, theme-aware SVG diagrams, and truthful terminal recordings.",
5
5
  "type": "module",
6
6
  "main": "dist/decklight.js",
@@ -37,7 +37,9 @@
37
37
  "build": "node build.mjs",
38
38
  "prepare": "npm run build",
39
39
  "test": "node test/run.mjs",
40
+ "coverage": "node test/run.mjs --experimental-test-coverage --test-coverage-include=src/core/** --test-coverage-include=cli/** --test-coverage-include=tools/**",
40
41
  "verify": "npm run build && node test/verify.mjs",
42
+ "test:impact": "node tools/test-impact.mjs",
41
43
  "soak": "node test/soak.mjs",
42
44
  "cross-engine": "node test/cross-engine.mjs"
43
45
  },
package/tools/args.mjs CHANGED
@@ -23,6 +23,26 @@ export function argReader(argv) {
23
23
  return { opt, opts };
24
24
  }
25
25
 
26
+ /**
27
+ * The first REAL positional — the first arg that neither starts with `-` nor
28
+ * is the value of a value-taking flag.
29
+ *
30
+ * `opt()` above reads a flag's value without consuming it, so a command that
31
+ * also does `args.find((a) => !a.startsWith('-'))` disagrees with its own flag
32
+ * reader: `--port 8790 deck.html` hands it "8790" as the deck, and the refusal
33
+ * says `no such deck: 8790`, which blames a file nobody named. Every dispatch
34
+ * that takes both flags-with-values and a positional goes through this, with
35
+ * the SAME flag list it reads values from.
36
+ *
37
+ * Deliberately not a file-extension test: `record` wants to SEE a `.yaml`
38
+ * positional so it can say "that is a cast, not a deck" — a filter that only
39
+ * passes `.html` would eat the very mistake the message exists for.
40
+ */
41
+ export function firstPositional(argv, valueFlags = []) {
42
+ const takesValue = new Set(valueFlags);
43
+ return argv.find((a, i) => !a.startsWith('-') && !takesValue.has(argv[i - 1]));
44
+ }
45
+
26
46
  /**
27
47
  * True when this module file was run directly (`node tools/x.mjs`), false when
28
48
  * imported. Path-resolved so it survives relative paths, symlinks and Windows —
package/tools/bridge.mjs CHANGED
@@ -23,8 +23,31 @@ export const corsHeaders = (expose = '') => ({
23
23
  * abort mid-request rejects the stream, and unguarded that would crash the
24
24
  * whole bridge. Callers that want text `.toString()` the result.
25
25
  */
26
- export async function readBody(req) {
26
+ /**
27
+ * The whole request body, as bytes.
28
+ *
29
+ * `max` is opt-in, and which callers set it is the design. The lipsync bridge
30
+ * receives a slide's WAV here and the TTS bridge a sentence; neither has a
31
+ * size a cap could sensibly name. The phone remote in cli/present.mjs does:
32
+ * it is the one route reachable from OFF this machine under --remote, its
33
+ * payloads are a few dozen bytes of "go to slide 7", and a body past 4 KB is
34
+ * not a bigger request, it is someone probing. So that caller passes `max`,
35
+ * and past it the socket is destroyed — no response, no 413 to time against,
36
+ * exactly what present.mjs did with its own reader before this shared one
37
+ * could — and the caller gets an error it can recognise and drop.
38
+ */
39
+ export async function readBody(req, { max = Infinity } = {}) {
27
40
  const chunks = [];
28
- for await (const c of req) chunks.push(c);
41
+ let size = 0;
42
+ for await (const c of req) {
43
+ size += c.length;
44
+ if (size > max) {
45
+ req.destroy();
46
+ const err = new Error(`request body past ${max} bytes`);
47
+ err.code = 'E2BIG';
48
+ throw err;
49
+ }
50
+ chunks.push(c);
51
+ }
29
52
  return Buffer.concat(chunks);
30
53
  }
@@ -21,6 +21,65 @@ export const NOTES_ASIDE = /<aside class="notes">([\s\S]*?)<\/aside>/;
21
21
  */
22
22
  export const sectionBodies = (html) => html.split(/<section\b/).slice(1);
23
23
 
24
+ /**
25
+ * Is a `sectionBodies` entry a hidden slide? `data-hidden` on the open tag
26
+ * (DECK_ANATOMY). File-side tools that produce one THING per slide — a video
27
+ * frame, a voiceover file, a PDF page — skip it; tools that NUMBER slides —
28
+ * comments, review anchors, history — do not, because a hidden slide keeps
29
+ * its number exactly as it does in PowerPoint.
30
+ */
31
+ export const isHiddenSection = (body) => /^[^>]*\sdata-hidden(?=[\s=>\/])/.test(body);
32
+
33
+ /**
34
+ * A section body from `sectionBodies`, reduced to what is actually inside the
35
+ * section.
36
+ *
37
+ * `sectionBodies` splits on `<section` and keeps everything after it, so each
38
+ * piece begins with the REST OF THE OPEN TAG (` class="x">`) and ends with the
39
+ * closing tag and whatever follows. A DOM reader never sees either. Anything
40
+ * comparing the two — the review fingerprint does — has to drop them, or the
41
+ * file side hashes a stray `>` that the browser side cannot produce.
42
+ */
43
+ export const sectionInner = (body) => {
44
+ const s = String(body ?? '');
45
+ const open = s.indexOf('>');
46
+ const inner = open === -1 ? s : s.slice(open + 1);
47
+ const close = inner.toLowerCase().lastIndexOf('</section>');
48
+ return close === -1 ? inner : inner.slice(0, close);
49
+ };
50
+
51
+ /**
52
+ * A slide's own text, as the fingerprint that anchors review comments sees it
53
+ * (SPEC REVIEW) — the file-reading twin of `slideBody` in src/core/finder.js.
54
+ *
55
+ * Asides are dropped before anything else: a comment is about what the audience
56
+ * sees, so an author rewriting their own speaker notes must not orphan every
57
+ * comment on the slide. Scripts and styles go for the same reason the DOM side
58
+ * filters them — they are machinery, not content.
59
+ *
60
+ * The two sides do NOT have to agree about spacing, because `fingerprint`
61
+ * removes whitespace rather than collapsing it. They do have to agree about
62
+ * what counts as content, which is what this shares with its DOM twin.
63
+ */
64
+ export const slideText = (sectionBody) => String(sectionBody ?? '')
65
+ .replace(/<aside\b[\s\S]*?<\/aside>/gi, ' ')
66
+ .replace(/<script\b[\s\S]*?<\/script>/gi, ' ')
67
+ .replace(/<style\b[\s\S]*?<\/style>/gi, ' ')
68
+ .replace(/<[^>]+>/g, ' ')
69
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
70
+ .replace(/\s+/g, ' ')
71
+ .trim();
72
+
73
+ /**
74
+ * A slide's title as the finder and the comment list both name it: the first
75
+ * heading, else its opening words. The file-reading twin of `slideTitle`.
76
+ */
77
+ export const slideHeading = (sectionBody, i) => {
78
+ const h = /<h[1-3]\b[^>]*>([\s\S]*?)<\/h[1-3]>/i.exec(sectionBody);
79
+ const fromHeading = h ? slideText(h[1]) : '';
80
+ return fromHeading || slideText(sectionBody).slice(0, 60) || `slide ${i + 1}`;
81
+ };
82
+
24
83
  /**
25
84
  * Speaker-note HTML as plain text: tags out, entities back, whitespace flat.
26
85
  *
@@ -5,7 +5,7 @@
5
5
  //
6
6
  // The other three engines offer a fixed roster: Google's thirty star names, or
7
7
  // whichever piper model is on disk. ElevenLabs is the one whose roster is your
8
- // account's, so a voice you cloned shows up in the deck's N picker beside the
8
+ // account's, so a voice you cloned shows up in the deck's V picker beside the
9
9
  // stock ones. That is the whole reason it is here, and it is why this engine
10
10
  // alone fetches its voices instead of shipping them: they are not knowable
11
11
  // until someone's key is in hand.
@@ -65,7 +65,7 @@ export function styleTag(style, maxLen = MAX_TAG_LEN) {
65
65
  return cue ? `[${cue}]` : '';
66
66
  }
67
67
 
68
- // PCM is what the rest of decklight is built on: ⇧V stitches per-slide WAVs
68
+ // PCM is what the rest of decklight is built on: the deck's recorder stitches per-slide WAVs
69
69
  // out of the sentence cache, and rhubarb reads WAV to find visemes. mp3 plays
70
70
  // perfectly well in the deck but does neither, so it is opt-in rather than a
71
71
  // silent downgrade. PCM output needs a paid ElevenLabs tier; see synthError.
@@ -130,7 +130,7 @@ export function synthError(status, body, { format = 'pcm' } = {}) {
130
130
  }
131
131
  if (format === 'pcm' && /output_format|pcm|tier|subscription/i.test(text)) {
132
132
  return 'ElevenLabs will not serve pcm_24000 on this plan (PCM output is a paid tier). '
133
- + 'Pass --tts-format mp3 to use mp3 instead — the deck plays it fine, but ⇧V offline '
133
+ + 'Pass --tts-format mp3 to use mp3 instead — the deck plays it fine, but the panel\'s Record this deck… offline '
134
134
  + 'recording and the lip-sync bridge both need WAV and will not work with it.';
135
135
  }
136
136
  if (status === 429) return 'ElevenLabs rate limit (429) — the lookahead buffer is bursty; try a smaller deck or wait';
package/tools/exec.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * One bounded child exec, for the sixteen places a hang could sit forever.
6
+ *
7
+ * #431 found a `say` with 0.31s of CPU after eight minutes, blocked in macOS's
8
+ * speech server, and an execFileSync above it with no timeout — so
9
+ * `decklight voiceover` waited with it, silently. That was one call of forty-
10
+ * three. The others are the same shape with different daemons behind them:
11
+ * gcloud waiting on a login that expired, gh waiting on the network, ffmpeg
12
+ * spinning on a file that is not what its extension says, Chrome waiting on
13
+ * a resource a slide points at. None of them ever say so.
14
+ *
15
+ * `run` is execFileSync with two things that should never be optional: a
16
+ * timeout, and SIGKILL rather than SIGTERM when it fires — a wedged process
17
+ * is blocked in a syscall and a polite signal is exactly what it is not
18
+ * answering. A timeout throws an error that names the binary, the wait, and
19
+ * WHY (the caller's word for what is probably stuck), because the person
20
+ * reading it will otherwise reword the sentence, re-encode the file, or
21
+ * reinstall the tool — anything but restart the daemon that is the actual
22
+ * problem.
23
+ *
24
+ * Every OTHER error is rethrown untouched. Callers inspect `.status`,
25
+ * `.stderr` and `.code === 'ENOENT'` — a probe that treats "present but
26
+ * exiting 1" as present depends on that — and wrapping them would break every
27
+ * one.
28
+ *
29
+ * Budgets, named for what they are rather than how long: a probe answers in
30
+ * milliseconds, the network in seconds, a codec in as long as the audio is.
31
+ */
32
+
33
+ import { execFileSync } from 'node:child_process';
34
+
35
+ /** `--version` and its kin. Anything slower than this is not answering. */
36
+ export const PROBE_MS = 15_000;
37
+ /** gcloud, gh: a login prompt nobody can see, or a network that is not there. */
38
+ export const NETWORK_MS = 60_000;
39
+ /** ffmpeg, afconvert, Chrome: a whole slide's audio, a whole deck's render. */
40
+ export const CODEC_MS = 5 * 60_000;
41
+
42
+ export function run(bin, args, { timeout = NETWORK_MS, why = '', ...opts } = {}) {
43
+ try {
44
+ return execFileSync(bin, args, { ...opts, timeout, killSignal: 'SIGKILL' });
45
+ } catch (e) {
46
+ if (e.code === 'ETIMEDOUT' || (e.signal === 'SIGKILL' && e.status == null)) {
47
+ const err = new Error(`${bin} hung for ${Math.round(timeout / 1000)}s and was killed`
48
+ + (why ? ` — ${why}` : ''));
49
+ err.code = 'ETIMEDOUT'; err.bin = bin; err.cause = e;
50
+ throw err;
51
+ }
52
+ throw e;
53
+ }
54
+ }
@@ -9,7 +9,7 @@
9
9
  // location pair is probed once (GA vs -preview, global vs us-central1) and
10
10
  // cached for the synth's lifetime.
11
11
 
12
- import { execFileSync } from 'node:child_process';
12
+ import { run, NETWORK_MS } from './exec.mjs';
13
13
 
14
14
  /**
15
15
  * GCP project ids: 6–30 chars, lowercase, leading letter, no trailing hyphen.
@@ -38,8 +38,8 @@ export const GEMINI_VOICES = [
38
38
  // ADC, not `gcloud auth login` — a separate credential store, and the one every
39
39
  // Google client library reads. Shared with the Chirp engine (tools/tts-engines.mjs).
40
40
  export function gcloudToken() {
41
- return execFileSync('gcloud', ['auth', 'application-default', 'print-access-token'],
42
- { encoding: 'utf8' }).trim();
41
+ return run('gcloud', ['auth', 'application-default', 'print-access-token'],
42
+ { encoding: 'utf8', timeout: NETWORK_MS, why: 'gcloud is waiting on a login that expired, or on the network — run: gcloud auth application-default login' }).trim();
43
43
  }
44
44
 
45
45
  /**
@@ -69,7 +69,7 @@ function estimateCost(model, usage) {
69
69
  /**
70
70
  * Wrap headerless 16-bit mono PCM in a RIFF/WAVE header. Every engine that
71
71
  * gets raw samples back lands here (Gemini's audio/L16, ElevenLabs' pcm_24000)
72
- * — WAV is what the deck's ⇧V stitching and the lip-sync bridge both read.
72
+ * — WAV is what the deck's recorder (V → Record this deck…) stitching and the lip-sync bridge both read.
73
73
  */
74
74
  export function wavFromPcm(pcm, rate) {
75
75
  const h = Buffer.alloc(44);
@@ -31,6 +31,8 @@
31
31
  // and the player's 10-sentence lookahead only ever pays for new sentences.
32
32
 
33
33
  import { createServer } from 'node:http';
34
+ import { createInterface } from 'node:readline/promises';
35
+ import { canBind, resolvePortConflict } from '../cli/port-conflict.mjs';
34
36
  import { createHash } from 'node:crypto';
35
37
  import { execFile } from 'node:child_process';
36
38
  import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, copyFileSync } from 'node:fs';
@@ -41,6 +43,7 @@ import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
41
43
  import { argReader, isMain } from './args.mjs';
42
44
  import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
43
45
  import { corsHeaders, readBody } from './bridge.mjs';
46
+ import { readyLine } from '../cli/banner.mjs';
44
47
 
45
48
  const run = promisify(execFile);
46
49
 
@@ -58,7 +61,37 @@ function makeQueue(width) {
58
61
  return (fn) => new Promise((res, rej) => { waiting.push({ fn, res, rej }); next(); });
59
62
  }
60
63
 
64
+ /** One line from the terminal, for the taken-port question. Closed straight after. */
65
+ async function askLine(prompt) {
66
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
67
+ // EOF ANSWERS THE SAFE WAY. `rl.question` never settles if the input closes
68
+ // first (a Ctrl-D, a terminal whose stdin is a spent pipe), and an unsettled
69
+ // promise here aborted the bridge through the top-level handler — reported to
70
+ // the user as "this one is a bug, please report it", over a question about a
71
+ // port. An empty answer is the declining answer everywhere it is read.
72
+ try {
73
+ return await new Promise((resolve) => {
74
+ // `line` is registered FIRST and readline emits it before `close`, so a
75
+ // key that was actually typed always beats the EOF that follows it. The
76
+ // two racing as promises did not: a piped `k\n` lost to the close and
77
+ // read as a decline, which is a terrible way to lose a keystroke.
78
+ let answered = false;
79
+ const done = (v) => { if (!answered) { answered = true; resolve(v); } };
80
+ rl.once('line', done);
81
+ rl.once('close', () => done(''));
82
+ rl.setPrompt(prompt);
83
+ rl.prompt();
84
+ });
85
+ } finally { rl.close(); }
86
+ }
87
+
61
88
  export async function lipsyncMain(args) {
89
+ // A clean exit on SIGTERM, not the default abrupt one. Invisible in
90
+ // production, decisive under test: V8 writes a process's coverage only when
91
+ // it exits through process.exit, so a bridge the suite stops with SIGKILL —
92
+ // or an unhandled SIGTERM — reports NOTHING of the handler it ran. The edit
93
+ // and present servers already do this; voiceover-server does now too.
94
+ process.on('SIGTERM', () => process.exit(0));
62
95
  if (args.includes('--help')) {
63
96
  console.log(`usage: decklight lipsync [--port 8789] [--rhubarb <bin>]
64
97
  [--portrait <name=img.png>]... portraits offered for video mode (first = default)
@@ -275,9 +308,44 @@ photo puts the face lower in Veo's 9:16 frame — chin off the bottom. Nudge
275
308
  res.end();
276
309
  });
277
310
 
278
- server.listen(port, '127.0.0.1', () => {
311
+ // A TAKEN PORT IS NOT A CRASH. Without this the bind threw EADDRINUSE as an
312
+ // unhandled 'error' event: a raw Node stack trace in the middle of author's
313
+ // startup output, which reads as decklight falling over when the truth is
314
+ // that something else has the port. The edit server has resolved conflicts
315
+ // for a long time (cli/port-conflict.mjs) — the bridges simply never called
316
+ // it, so they were the one place the deck could still look broken.
317
+ //
318
+ // On a TTY it names the occupant and offers a choice; anywhere else — and
319
+ // author spawns these with a piped stdin, so that is the usual case — it
320
+ // moves to the next free port and says so. The player finds the bridge by
321
+ // probing, so a moved port costs nothing.
322
+ // `canBind`, NOT `isPortOpen`: this file's own note says why, and getting it
323
+ // wrong the first time proved the point. `isPortOpen` CONNECTS, answering "is
324
+ // somebody there" — a listener that never accepts (backlog full, or a socket
325
+ // opened and ignored) refuses the connect and reads as free, and then the
326
+ // bind fails anyway. "May I have this port" is a different question and only
327
+ // a trial bind answers it.
328
+ //
329
+ // `--port 0` is "let the OS pick", which cannot conflict — resolving it would
330
+ // turn a deliberate 0 into port 1. Only a REAL port that is taken gets the
331
+ // question; everything else binds exactly as before.
332
+ const asked = port && !(await canBind(port))
333
+ ? await resolvePortConflict(port, {
334
+ kind: 'bridge',
335
+ ask: process.stdin.isTTY && process.stdout.isTTY ? askLine : undefined,
336
+ log: console.log,
337
+ })
338
+ : port;
339
+ // null is "stand down" — either a bridge is already serving this port, or
340
+ // somebody else holds it and this one cannot move (the deck only ever calls
341
+ // the one number). Exiting is the honest outcome: author prints "carrying on
342
+ // without it" and the deck degrades where you can see it, instead of a
343
+ // bridge running somewhere nothing will ever knock.
344
+ if (asked === null) process.exit(0);
345
+ server.listen(asked, '127.0.0.1', () => {
279
346
  const what = [visemeOk && 'visemes (rhubarb)', ...videoEngines.map((e) => `video (${e})`)].filter(Boolean).join(' · ');
280
- console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
347
+ if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key: 'lips', text: `${what} — on :${port}` }));
348
+ else console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
281
349
  if (veo) {
282
350
  console.log(`veo: ${veo.model} · ${veo.seconds}s — each portrait is animated ONCE (billed), `
283
351
  + 'then wav2lip re-syncs that clip locally for every sentence');
package/tools/lipsync.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Lip-sync generator for RECORDED narration: sidecar files for every
3
3
  // slide-NN audio clip in a voiceover directory (tools/voiceover.mjs or a
4
- // ⇧V-recorded set), so a deck plays back with an animated character and no
4
+ // deck-recorded set — V → Record this deck…), so a deck plays back with an animated character and no
5
5
  // bridge running. Fully offline, like everything else here.
6
6
  //
7
7
  // node tools/lipsync.mjs <voiceover-dir> [--visemes] [--video]
@@ -15,7 +15,7 @@
15
15
  // --video — slide-NN.mp4 (muted talking head)
16
16
  //
17
17
  // Rhubarb wants WAV: slide-NN.wav is used when present (voiceover.mjs
18
- // --keep-wav, or a ⇧V set); otherwise the .m4a is decoded on the fly with
18
+ // --keep-wav, or a set the deck recorded); otherwise the .m4a is decoded on the fly with
19
19
  // ffmpeg (afconvert fallback on macOS). The transcript slide-NN.txt, when
20
20
  // present, markedly improves cue accuracy. For batch video SadTalker is the
21
21
  // default engine — per-slide clips are long enough that its natural head
@@ -27,11 +27,11 @@
27
27
 
28
28
  import { readFileSync, writeFileSync, existsSync, readdirSync, rmSync, renameSync } from 'node:fs';
29
29
  import { createHash } from 'node:crypto';
30
- import { execFileSync } from 'node:child_process';
31
30
  import { resolve, join, basename } from 'node:path';
32
31
  import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
33
32
  import { argReader } from './args.mjs';
34
33
  import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
34
+ import { run, PROBE_MS, CODEC_MS } from './exec.mjs';
35
35
 
36
36
  const args = process.argv.slice(2);
37
37
  const dirArg = args.find((a) => !a.startsWith('-'));
@@ -68,7 +68,7 @@ const veo = veoOn ? createVeo({
68
68
  }) : null;
69
69
 
70
70
  const have = (bin, flags = ['--version']) => {
71
- try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
71
+ try { run(bin, flags, { stdio: 'ignore', timeout: PROBE_MS }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
72
72
  };
73
73
  if (doVisemes && !have(rhubarb)) {
74
74
  console.error(`rhubarb not found — install https://github.com/DanielSWolf/rhubarb-lip-sync or pass --rhubarb <bin>`);
@@ -81,12 +81,23 @@ if (doVideo) {
81
81
  }
82
82
  const ffmpegOk = have('ffmpeg', ['-version']);
83
83
 
84
- // every slide-NN with audio, wav preferred over m4a
85
- const slides = [...new Set(readdirSync(dir)
86
- .map((f) => f.match(/^slide-(\d+)\.(wav|m4a)$/)?.[1])
84
+ // Every stem with audio, wav preferred over m4a: slide-NN, and slide-NN-KK for
85
+ // a track whose ⟨CLICK⟩ beats were recorded separately.
86
+ //
87
+ // A beat needs its OWN sidecar. The player plays one beat's audio at a time on
88
+ // a beat-paced track (PRESENTING), so a timeline cut for the whole slide starts
89
+ // at zero against every one of them — right for the first beat and
90
+ // progressively wronger after it. Cutting one per beat is the fix, and it costs
91
+ // only Rhubarb passes: they are seconds each, and incremental like everything
92
+ // else here.
93
+ const stems = [...new Set(readdirSync(dir)
94
+ .map((f) => f.match(/^(slide-\d+(?:-\d+)?)\.(wav|m4a)$/)?.[1])
87
95
  .filter(Boolean))].sort();
88
- if (!slides.length) { console.error(`${dir}: no slide-NN.wav/.m4a files`); process.exit(1); }
89
- console.log(`${basename(dir)}: ${slides.length} slides with audio`);
96
+ const slides = stems.filter((st) => !/-\d+-\d+$/.test(st));
97
+ const beats = stems.filter((st) => /-\d+-\d+$/.test(st));
98
+ if (!stems.length) { console.error(`${dir}: no slide-NN.wav/.m4a files`); process.exit(1); }
99
+ console.log(`${basename(dir)}: ${slides.length} slides with audio`
100
+ + (beats.length ? ` · ${beats.length} ⟨CLICK⟩ beats` : ''));
90
101
 
91
102
  // incremental state — its own file so voiceover.mjs reruns can't clobber it
92
103
  const statePath = join(dir, 'lipsync.json');
@@ -99,13 +110,13 @@ const sha = (...parts) => {
99
110
  return h.digest('hex').slice(0, 16);
100
111
  };
101
112
 
102
- function toWav(nn) {
103
- const wav = join(dir, `slide-${nn}.wav`);
113
+ function toWav(stem) {
114
+ const wav = join(dir, `${stem}.wav`);
104
115
  if (existsSync(wav)) return { path: wav, tmp: false };
105
- const m4a = join(dir, `slide-${nn}.m4a`);
106
- const tmp = join(dir, `slide-${nn}.tmp.wav`);
107
- if (ffmpegOk) execFileSync('ffmpeg', ['-y', '-i', m4a, tmp], { stdio: 'ignore' });
108
- else execFileSync('afconvert', ['-f', 'WAVE', '-d', 'LEI16', m4a, tmp]);
116
+ const m4a = join(dir, `${stem}.m4a`);
117
+ const tmp = join(dir, `${stem}.tmp.wav`);
118
+ if (ffmpegOk) run('ffmpeg', ['-y', '-i', m4a, tmp], { stdio: 'ignore', timeout: CODEC_MS, why: 'the encoder is stuck on this file — check it plays, then retry' });
119
+ else run('afconvert', ['-f', 'WAVE', '-d', 'LEI16', m4a, tmp], { timeout: CODEC_MS, why: 'the encoder is stuck on this file — check it plays, then retry' });
109
120
  return { path: tmp, tmp: true };
110
121
  }
111
122
 
@@ -115,40 +126,45 @@ function toWav(nn) {
115
126
  const face = veo && engine === 'wav2lip' ? await veo.motionFor(portrait) : portrait;
116
127
 
117
128
  let made = 0, kept = 0;
118
- for (const nn of slides) {
119
- const audioFile = ['wav', 'm4a'].map((e) => join(dir, `slide-${nn}.${e}`)).find(existsSync);
129
+ for (const stem of stems) {
130
+ // A beat gets visemes only. A talking head is minutes of GPU time per clip,
131
+ // and the player's video element mirrors the audio's transport rather than
132
+ // seeking a timeline — so cutting video per beat would cost a great deal to
133
+ // fix a smaller error than the visemes had.
134
+ const isBeat = /-\d+-\d+$/.test(stem);
135
+ const audioFile = ['wav', 'm4a'].map((e) => join(dir, `${stem}.${e}`)).find(existsSync);
120
136
  const audioBytes = readFileSync(audioFile);
121
- const txtPath = join(dir, `slide-${nn}.txt`);
137
+ const txtPath = join(dir, `${stem}.txt`);
122
138
  const text = existsSync(txtPath) ? readFileSync(txtPath, 'utf8').trim() : '';
123
- const st = (state[nn] ??= {});
139
+ const st = (state[stem] ??= {});
124
140
  const jobs = [];
125
141
  if (doVisemes) jobs.push('visemes');
126
- if (doVideo) jobs.push('video');
142
+ if (doVideo && !isBeat) jobs.push('video');
127
143
 
128
144
  for (const job of jobs) {
129
- const outFile = join(dir, job === 'visemes' ? `slide-${nn}.visemes.json` : `slide-${nn}.mp4`);
145
+ const outFile = join(dir, job === 'visemes' ? `${stem}.visemes.json` : `${stem}.mp4`);
130
146
  const hash = job === 'visemes'
131
147
  ? sha('visemes|', text, '|', audioBytes)
132
148
  : sha('video|', engine, '|', readFileSync(face), '|', audioBytes); // `face`, so --veo re-renders
133
149
  if (st[job] === hash && existsSync(outFile)) {
134
150
  kept++;
135
- console.log(` slide ${nn}: ${job} unchanged — kept`);
151
+ console.log(` ${stem}: ${job} unchanged — kept`);
136
152
  continue;
137
153
  }
138
- const wav = toWav(nn);
154
+ const wav = toWav(stem);
139
155
  try {
140
156
  const t0 = Date.now();
141
157
  if (job === 'visemes') {
142
- const tmpOut = join(dir, `slide-${nn}.tmp.visemes.json`);
158
+ const tmpOut = join(dir, `${stem}.tmp.visemes.json`);
143
159
  let dialogFile;
144
- if (text) { dialogFile = join(dir, `slide-${nn}.tmp.txt`); writeFileSync(dialogFile, text); }
160
+ if (text) { dialogFile = join(dir, `${stem}.tmp.txt`); writeFileSync(dialogFile, text); }
145
161
  const tl = await runRhubarb(rhubarb, { wav: wav.path, dialogFile, out: tmpOut });
146
162
  writeFileSync(outFile, JSON.stringify(tl));
147
163
  rmSync(tmpOut, { force: true });
148
- rmSync(join(dir, `slide-${nn}.tmp.txt`), { force: true });
149
- console.log(` slide ${nn}: ${tl.cues.length} cues → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
164
+ rmSync(join(dir, `${stem}.tmp.txt`), { force: true });
165
+ console.log(` ${stem}: ${tl.cues.length} cues → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
150
166
  } else {
151
- const tmpMp4 = join(dir, `slide-${nn}.tmp.mp4`);
167
+ const tmpMp4 = join(dir, `${stem}.tmp.mp4`);
152
168
  if (engine === 'wav2lip') {
153
169
  // a --veo clip is hundreds of frames to detect faces in, not one:
154
170
  // batch small or an 8GB card dies with "Image too big to run face
@@ -156,7 +172,7 @@ for (const nn of slides) {
156
172
  await runWav2lip(python, { dir: wav2lipDir, checkpoint: wav2lipCkpt, face,
157
173
  wav: wav.path, out: tmpMp4, smallBatches: face !== portrait, inherit: true });
158
174
  } else {
159
- const resDir = join(dir, `slide-${nn}.tmp.d`);
175
+ const resDir = join(dir, `${stem}.tmp.d`);
160
176
  await runSadtalker(python, { dir: sadtalkerDir, still: portrait,
161
177
  wav: wav.path, out: tmpMp4, resultDir: resDir, inherit: true });
162
178
  rmSync(resDir, { recursive: true, force: true });
@@ -166,7 +182,7 @@ for (const nn of slides) {
166
182
  await muteFaststart(tmpMp4, outFile);
167
183
  rmSync(tmpMp4, { force: true });
168
184
  } else renameSync(tmpMp4, outFile);
169
- console.log(` slide ${nn}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
185
+ console.log(` ${stem}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
170
186
  }
171
187
  st[job] = hash;
172
188
  made++;