decklight 0.1.0 → 0.2.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 (87) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +61 -177
  3. package/SPEC.md +20 -8
  4. package/cli/agents.mjs +102 -0
  5. package/cli/bundle.mjs +37 -0
  6. package/cli/decklight.mjs +18 -0
  7. package/cli/dev.mjs +266 -0
  8. package/cli/edit.mjs +230 -17
  9. package/cli/init.mjs +58 -19
  10. package/cli/rec.mjs +7 -0
  11. package/dist/decklight.css +241 -51
  12. package/dist/decklight.js +120 -76
  13. package/dist/decklight.js.map +4 -4
  14. package/package.json +6 -4
  15. package/themes/aliens.css +3 -0
  16. package/themes/apple2.css +3 -0
  17. package/themes/aurora.css +3 -0
  18. package/themes/berry.css +3 -0
  19. package/themes/blade-runner.css +3 -0
  20. package/themes/c64.css +3 -0
  21. package/themes/carbon.css +3 -0
  22. package/themes/citrus.css +3 -0
  23. package/themes/coastal.css +3 -0
  24. package/themes/cosmos.css +3 -0
  25. package/themes/dune.css +3 -0
  26. package/themes/eclipse.css +3 -0
  27. package/themes/ember.css +3 -0
  28. package/themes/fjord.css +3 -0
  29. package/themes/friends.css +3 -0
  30. package/themes/gameboy.css +3 -0
  31. package/themes/genesis.css +3 -0
  32. package/themes/glacier.css +3 -0
  33. package/themes/godfather.css +3 -0
  34. package/themes/graphite.css +3 -0
  35. package/themes/harvest.css +3 -0
  36. package/themes/ibm-modern.css +3 -0
  37. package/themes/ibm-oldschool.css +3 -0
  38. package/themes/ink.css +3 -0
  39. package/themes/latte.css +3 -0
  40. package/themes/linen.css +3 -0
  41. package/themes/meadow.css +3 -0
  42. package/themes/metropolis.css +3 -0
  43. package/themes/miami-vice.css +3 -0
  44. package/themes/midnight.css +3 -0
  45. package/themes/mint.css +3 -0
  46. package/themes/moss.css +3 -0
  47. package/themes/obsidian.css +3 -0
  48. package/themes/orchid.css +3 -0
  49. package/themes/packs.json +2 -1
  50. package/themes/paper.css +3 -0
  51. package/themes/peony.css +3 -0
  52. package/themes/porcelain.css +3 -0
  53. package/themes/pulp-fiction.css +3 -0
  54. package/themes/reveal-beige.css +3 -0
  55. package/themes/reveal-black.css +3 -0
  56. package/themes/reveal-blood.css +3 -0
  57. package/themes/reveal-dracula.css +3 -0
  58. package/themes/reveal-league.css +3 -0
  59. package/themes/reveal-moon.css +3 -0
  60. package/themes/reveal-night.css +3 -0
  61. package/themes/reveal-serif.css +3 -0
  62. package/themes/reveal-simple.css +3 -0
  63. package/themes/reveal-sky.css +3 -0
  64. package/themes/reveal-solarized.css +3 -0
  65. package/themes/reveal-white.css +3 -0
  66. package/themes/sepia.css +3 -0
  67. package/themes/seriph.css +3 -0
  68. package/themes/severance.css +3 -0
  69. package/themes/slate.css +3 -0
  70. package/themes/snes.css +3 -0
  71. package/themes/star-wars.css +3 -0
  72. package/themes/storm.css +3 -0
  73. package/themes/stranger-things.css +3 -0
  74. package/themes/synthwave.css +3 -0
  75. package/themes/terminator.css +3 -0
  76. package/themes/velvet.css +3 -0
  77. package/themes/yamabuki.css +120 -0
  78. package/tools/chrome.mjs +43 -0
  79. package/tools/gemini-tts.mjs +19 -1
  80. package/tools/lipsync-server.mjs +249 -0
  81. package/tools/lipsync.mjs +166 -0
  82. package/tools/publish-site-voices.mjs +3 -0
  83. package/tools/shot.mjs +85 -0
  84. package/tools/tts-engines.mjs +226 -0
  85. package/tools/visemes.mjs +26 -0
  86. package/tools/voiceover-server.mjs +0 -0
  87. package/tools/voiceover.mjs +51 -34
package/SPEC.md CHANGED
@@ -306,30 +306,39 @@ absent — no compatibility break in either direction.
306
306
 
307
307
  ## 8. Presenting & output
308
308
 
309
- - Keyboard: `→/←/Space` steps+slides, `Home/End`, `O` overview grid, `B` blackout, `F` fullscreen, `T` theme picker (`,`/`.` cycle the theme, `[`/`]` cycle the font), `/` command palette, `V` narration (`N` picks track / live voice / tone; `P` pauses/resumes; `<`/`>` change the voice speed in 0.25× steps, 0.25–2×, persisted per deck — YouTube's shortcut), `C` captions, `D` debug log, `G` slide finder (deliberately not `⌘F` — browser find stays untouched), `?` help overlay.
309
+ - Keyboard: `→/←/Space` steps+slides, `Home/End`, `O` overview grid, `B` blackout, `F` fullscreen, `T` theme picker (`,`/`.` cycle the theme, `[`/`]` cycle the font), `L`/`⇧L` cycle the current slide's layout (dev mode — a persisted deck edit), `Z`/`⇧Z` undo/redo deck edits (dev mode), `A` ask an AI agent to edit the deck (dev mode), `/` command palette, `V` narration (`N` picks track / live voice / tone; `P` pauses/resumes; `<`/`>` change the voice speed in 0.25× steps, 0.25–2×, persisted per deck — YouTube's shortcut), `C` captions, `K` presenter clock, `H` progress bar, `D` debug log, `` ` `` messages, `G` slide/module finder (deliberately not `⌘F` — browser find stays untouched), `?` help overlay.
310
310
  - **Captions** (`C`): a YouTube-style bar at the bottom showing the current notes segment — the same ⟨CLICK⟩-segmented text the live voice speaks — synced to slide/step, with narration on or off. Slides/steps without notes show no bar. Persists per deck in localStorage.
311
+ - **Presenter clock** (`K`): the wall-clock time (HH:MM) and the elapsed talk time, directly below the slide number — positioned so it never covers the slide number, the message window, or the default logo/controls corners. The elapsed count starts at the deck's **first advance after load**, not at page load — a deck idling on its title slide while the room fills is not a talk yet. Off by default, persists per deck in localStorage, never rendered in `?print`. `instance.toggleClock()` programmatically.
312
+ - **Progress bar** (`H`): a hairline along the bottom edge of the deck whose width tracks the position through the deck (slide plus build step, slide 1 empty → last slide full), updated on every navigation — keys, `G`, `Home`/`End`, deep links. A passive readout of the deck state: it never drives navigation or auto-advance. Sits at the very bottom edge, below the captions bar, the character overlay and the corner chrome, so it covers none of them. Off by default, persists per deck in localStorage, never rendered in `?print`. `instance.toggleProgress()` programmatically.
311
313
  - **Transcript** (palette → Transcript…): the deck's full spoken script — every slide's notes segments in order, slide titles jump on click — with export to plain text or markdown (`<deck>-transcript.txt|.md`). Also programmatic: `instance.transcript.text()` / `.markdown()` / `.open()`.
312
- - **Edit mode** (`E`): with the deck served by `decklight edit <deck.html>` (localhost; `GET /edit/ping`, SSE `GET /edit/events`, `POST /edit/notes {slide, text}`), E opens a notes editor — ⟨CLICK⟩-separated plain text — whose Save rewrites the slide's `<aside class="notes">` in the file (one `<p>` per segment, HTML-escaped; the aside is inserted if the slide had none). The server watches the deck file and broadcasts a reload to every connected browser on ANY change — the player's edits and external editors alike — and the `#/slide/step` hash restores the position. Markdown-authored slides decline the editor (their notes live in the template). `file://`-opened decks probe the server at its default localhost port (CORS-open endpoints, like the tts bridge) so the printed URL and a double-clicked file both work; `config.edit.url` overrides, and a basename guard refuses a server that's editing a different deck.
314
+ - **Dev mode (edit server)**: `decklight edit <deck.html>` (or the umbrella `decklight dev`) serves the deck over localhost with live reload and accepts persisted edits from the player. Endpoints: `GET /edit/ping` (capabilities: deck name, undo/redo depths, git state, detected agents, `agentBusy`), SSE `GET /edit/events` (`reload` on any file change; named `agent` events for job status), `POST /edit/notes {slide, text}`, `POST /edit/layout {slide, layout}` (writes `data-layout` into the slide's `<section>` tag; `auto` removes it; a no-change write is skipped), `POST /edit/undo` / `POST /edit/redo`, and `POST /edit/agent {prompt, agent?}`.
315
+ - **Undo/redo** (`Z`/`⇧Z`): the server keeps ONE in-memory edit history — whole-file snapshots, capped at 200 — fed by every mutation it performs (layout picks, notes saves, agent runs). Undo/redo rewrites the deck file; the watcher's reload shows the result (the hash keeps the position). The history is deliberately **independent of git**: commits never consume or reset it, and undoing never touches the repository. A file edited externally between an edit and its undo isn't lost — the current content rides the opposite stack. Empty stacks answer 409, and the player toasts the remaining depths.
316
+ - **Git autocommit**: with `--git` (or automatically when the deck already sits inside a repository; `--no-git` opts out) the server commits the deck on a regular basis — every `--commit-every` seconds (default 300) when it actually changed, plus an opening commit and a final one on Ctrl-C. `--git` creates the repository when none exists; `decklight dev` ASKS first on a TTY ("no git repository here — create one and auto-commit?"). Only the deck file is staged (`git add -- <deck>`), and a machine with no git identity gets a per-commit `-c user.name/user.email` fallback rather than a silent failure.
317
+ - **Ask an agent** (`A`): dev mode drives whichever AI coding agent CLIs the dev machine has installed — the roster (`cli/agents.mjs`) covers **Claude Code** (`claude -p … --permission-mode acceptEdits`), **Codex CLI** (`codex exec --full-auto …`), and **IBM Bob** (`bob -p … --accept-license`), plus Gemini CLI, GitHub Copilot CLI, OpenCode, Goose, Aider, Cursor CLI, and Qwen Code — each as a headless one-shot invocation, detected by probing `$PATH`. A opens a prompt overlay (agent picker when several are detected; `--agent` sets the default); the server snapshots the deck, spawns the agent in the serving directory with the instruction wrapped in deck context, and streams start/done status over SSE (toasts in the player; 10-minute timeout; strictly one job at a time — `agentBusy` survives reloads via ping). If the agent changed the file, the watcher reloads every browser and `Z` takes the edit back like any other.
318
+ - **Notes editor** (`E`): E opens a notes editor — ⟨CLICK⟩-separated plain text — whose Save rewrites the slide's `<aside class="notes">` in the file (one `<p>` per segment, HTML-escaped; the aside is inserted if the slide had none). The server watches the deck file and broadcasts a reload to every connected browser on ANY change — the player's edits and external editors alike — and the `#/slide/step` hash restores the position. Markdown-authored slides decline the editor (their notes live in the template). `file://`-opened decks probe the server at its default localhost port (CORS-open endpoints, like the tts bridge) so the printed URL and a double-clicked file both work; `config.edit.url` overrides, and a basename guard refuses a server that's editing a different deck.
319
+ - **Messages** (`` ` `` — the key left of `1`, matched on `code` so it is the same physical key on every layout; or the palette's "Messages"): the deck talks back in the **top-left corner** — 20px, high-contrast, stacked newest-last (at most 4 at a time), each fading after a few seconds. Every message is also KEPT: that key opens the log — the full history with arrival times — because a message that explains why the voice stopped is worthless if it faded while you were looking at the slide. The shortcut is handled BEFORE the typing guard, so `` ⌃` ``/`` ⌥` `` reach you even while the notes editor (`E`) has focus and owns every bare keystroke; the bare key works whenever you are not typing. `instance.messages()` returns `[{ at, text }]`, `instance.toggleMessages()` opens the log.
313
320
  - **Debug log** (`D`): a passive monospace panel over the deck (keys keep driving the presentation) showing a timestamped event stream — ready/slide/build with direction, theme and font applies, narration on/off and config changes, every TTS call with its duration and estimated cost (`slide 3 seg 1 · Alnilam · 214 chars → 2.4s · ~$0.0041`, previews included) and failures, and window `error` events — plus a live state line (slide/step/theme/narration incl. the active voice · tone or track, the voice rate, and the running TTS spend). Cost is an ESTIMATE: the Gemini API returns token counts (`usageMetadata`), never dollars; the bridge prices them at published Vertex list rates, sends `x-tts-cost` on each fresh synthesis (0 on cache replays), and prints a per-call line plus session total on its console. Events ring-buffer (last 200) from init, so the panel shows history from before it was opened.
314
321
  - **Font cycling**: `[`/`]` walk a curated list of offline-safe system stacks (sans, rounded, humanist, geometric, two serifs, slab, mono; entry 0 = the theme's own type) applied to `--font-body` + `--font-heading` as inline root properties — they win over any theme and survive theme switches. The choice persists per deck path in localStorage and is restored before the first layout pass; every change re-measures pinned titles and re-runs the overflow guardrail (type metrics differ). `instance.cycleFont(±1)` programmatically.
322
+ - **Slide layout cycling** (dev mode only): `L`/`⇧L` walk the CURRENT slide through the layout ring — `auto` (deck default: the `pinTitles` config, **on by default**, + the pinnable heuristic — so out of the box a pinnable slide pins) → `centered` (title in flow, content vertically centered) → `pinned` (title pinned at the pin Y) → `top` (everything flows from the top of the slide) → `split` → `split-flip`. Ring entries that cannot change the slide's look are SKIPPED so every press shows something new: `pinned` when `auto` already pins, `split-flip` when there aren't two content blocks to swap sides. **Split layouts**: the content blocks — everything after the title + subtitle header (which spans the full width, pinned or in flow) — become ~half-width sides in a wrapping flex row, first block left and the rest right; `split-flip` mirrors (bullets left · diagram right ⇄ diagram left · bullets right). A slide whose ONLY content block is a list can't take sides — the engine marks it `.split-columns` and the list itself splits across two CSS columns (`break-inside: avoid` per item). The pick lands on the section as a `data-layout` attribute — the same attribute an author can write in the file, and headless probes can assert on — and it wins over `data-pin` (`pinned` forces the pin, a numeric `data-pin` still sets the Y; `centered`/`top` lay out in flow; the split pair keeps the deck's auto pin resolution for its header). `auto` removes the attribute. A layout pick is a PERSISTED deck edit, so cycling requires dev mode: the pick applies to the DOM instantly and is written back into the file through the edit server (debounced ~600ms, so a cycling burst costs one write/reload, and a pick pending when the slide changes is flushed, not dropped) — the file is the ONLY persistence (no localStorage). Without the server, L toasts what it needs and changes nothing — a presenter can't silently fork the deck from what's on disk. Every change re-measures pinned titles and re-runs the overflow guardrail. `instance.cycleLayout(±1)` programmatically (same gate); `instance.layoutRing(n)` exposes a slide's ring — skips included — so headless probes can assert the skip logic without a server; also in the `/` palette ("Cycle slide layout").
315
323
  - Touch: swipe navigation.
316
324
  - URL: `#/<slide>[/<step>]`; back/forward supported. `?theme=<name>` loads any theme at startup.
317
325
  - **Theme switching**: the theme is the stylesheet link into `themes/`; the engine swaps its href in place, so every token cascades and the deck restyles live. `T` opens the **theme picker**: the theme list (config `themes: [...]`, defaulting to the shipped set baked in at build time) beside a live preview of the *current slide at the current step* — a real embedded deck (`?embedded&theme=<name>#/<slide>/<step>`). `↑/↓`/hover browse (debounced), `Enter`/click applies, `Esc` closes. **Packs** (themes/packs.json, baked in at build; the build fails if a shipped theme is missing from the manifest): the picker opens on the pack list (name + count; the active theme's pack is marked), `Enter` drills in, the `← packs` row or `Esc` goes back, `✳ all themes` flattens; saved-custom and generated themes form dynamic packs at the end. An active filter always searches globally and tags each hit with its pack. **Pack-aware cycling**: `,`/`.` walk the pack-grouped order; a step that would cross into another pack pends instead of applying — a toast names the pack and target theme, the same key confirms, the opposite key or `Esc` cancels, and the pending step times out after 4s. **Quick filter**: printable keys type into a filter bar that narrows the list (substring match; the generate row hides while a filter is active); `Backspace` edits, `Esc` clears the filter first and closes on the second press. Because keystrokes feed the filter, the picker has no letter shortcuts (`⌃T` re-rolls the generate-row candidate; the former `R`/`T` bindings are gone). The applied choice persists per deck path in `localStorage`; **embedded instances never persist** (previews can't pollute the saved choice).
318
326
  - **Inline-theme mode** (bundled single-file decks): when `<style data-theme="name">` blocks exist, they replace the link — `applyTheme` toggles which block applies (via `media="not all"`; the HTML `disabled` attribute on `<style>` is non-functional per spec, and the engine normalizes either form at init). The picker lists the embedded names (config `themes` narrows), `?theme=` works, and everything else is unchanged.
319
327
  - **Theme generator**: `⌃T` generates a brand-new contract-complete theme (§5 note) and applies it instantly — press again to re-roll. The roll lives as a `<style data-theme data-generated>` block appended last in `<head>` (wins the cascade over the link/inline base); cycling `<`/`>` or picking another theme deactivates it but keeps it in the theme list under its autoname (`gen-<word>-<hex4>`) until the next roll replaces it. The picker's first row is **“✨ Generate new…”**: selecting it rolls a candidate and previews it live like any other theme (`⌃T` re-rolls while selected; `Enter` applies). Previews for generated and saved-custom themes carry their tokens in the URL — `?gen=<base64url {name, tokens}>` — which the engine applies statelessly at init (works on `file://` and inside bundles). The preview deck loads **once per picker session**; subsequent selections are postMessage'd into the embedded instance (`{__decklightPreview: {theme|gen}}`, parent-origin-guarded) and applied in place — no document reload per candidate, which matters in bundles where each reload would re-parse the whole payload. `⌃⇧T` **saves** the applied generated theme: prompts for a name (sanitized `[a-z0-9-]{1,40}`, `custom-` prefixed on collision with a shipped name), persists `{name → tokens}` into `localStorage['decklight-custom-themes']`, and downloads `<name>.css` (a normal theme file). Saved customs appear in the theme list and picker (tagged “custom”), survive reload, and apply via the same inline-style mechanism — but localStorage is per-origin/per-browser: **the downloaded .css is the portable artifact** (drop it into `themes/` and commit). Unsaved generated autonames are never persisted as the deck's theme choice.
320
328
  - **Brand logo**: `init({ logo: { onLight, onDark, src?, height?, position? } })` renders a mark as chrome on every slide (default `bottom-left`; also `top-left|top-right|bottom-right`; default height 30px). `onLight`/`onDark` are the variants for light/dark canvases: the engine reads the applied theme's real background luminance (first gradient stop for gradient canvases), sets `data-canvas="dark|light"` on the root, and the matching variant shows — following theme cycling, the picker, and generated themes ( `src` alone shows always). Refs resolve as `'#id'` (clones an inline element — bundle- and `file://`-safe, the `data-cast-inline` idiom), `'<svg…'` raw markup, or an `<img>` URL. In `?print`, every slide gets its own copy. **Hero variant**: `data-logo` on a section prepends a larger in-flow copy of the mark above the slide's content (default 96 design px; `data-logo="128"` overrides) — module openers and cover slides. Hero slides hide the corner chrome (and skip the print copy), the mark doesn't count as pinnable content, and the same on-light/on-dark variant switching applies.
321
- - **Narration**: `V` toggles voice-over; `N` opens the picker (persisted per deck). Two sources. **Recorded**: pre-rendered per-slide audio (`<dir>/slide-NN.m4a`, 1-based like `state.slide`), synced to slide changes; the deck configures `narration: { files: '<dir>' }` or `[{ label, dir }, …]` for several takes. **Live voice**: the player synthesizes each slide's notes on the fly through the local bridge (`decklight tts`, default `http://127.0.0.1:8787/tts`, override via `narration.liveUrl`) — the picker drills tracks → Gemini voice (30 prebuilt, flavor-tagged) → tone (six presets or a custom typed instruction, sent as an in-prompt delivery-style prefix). Every voice row carries a ▶ **preview** that speaks an editable test sentence (default "Hey, this is Decklight", input at the top of the voices view, ↺ restores the default) through the bridge in that voice; tone rows preview the drafted voice in that delivery style, and the custom-tone input has a ▶ to audition a typed instruction before committing it. After a preview plays, the rest of its roster prefetches sequentially in the background (all voices neutrally, or all tones for the drafted voice). Two preview caches: the default sentence's cache is permanent once built; the custom sentence's cache holds exactly one sentence and is swapped (old audio freed) when the text changes. **Build-synced auto-advance**: the ⟨CLICK⟩ markers that segment the notes for the speaker view segment the audio too — segment k is synthesized as its own clip and narrates build step k (0 = arrival); when a clip ends the deck reveals the next build, and after the last segment it moves to the next slide, so a deck with well-segmented notes presents itself beat by beat. A segment with no words advances after a short beat; a slide with no notes is skipped; manual navigation mid-clip wins over the pending advance and re-syncs the voice to the new step. **`data-narration="hold"`** on a section marks it interactive (quiz, exercise, live demo): narration plays whatever notes it has and builds still sync, but the deck never auto-advances *off* it — the presenter moves on manually and narration resumes on the next slide. The spoken unit is a **sentence**: each ⟨CLICK⟩ segment splits into sentences, every sentence is its own TTS call and cache entry (slide, segment, sentence, voice, style), playback chains them and advances only after the segment's last one — so first audio arrives after one short synthesis, never a whole paragraph. While narration is on, a **lookahead buffer** keeps the next 10 sentences synthesized in the background (a few parallel low-priority workers, window re-derived from the current position, results landing in the same cache); an unreachable bridge toasts once and pauses the buffer until the next event. `⇧V` downloads per-slide `slide-NN.wav` files **stitched from this same sentence cache** (short silences joining sentences and builds) — already-heard clips cost nothing, only unheard sentences synthesize. **`P` pauses/resumes** narration — audio freezes mid-sentence and resumes exactly there, and auto-advance holds while paused. Captions (`C`) follow the voice **sentence by sentence** during live narration (segment-level when narration is off). With nothing configured, `V` opens the picker instead of failing. Files are generated by `tools/voiceover.mjs`: notes → optional local-LLM rewrite → `--engine piper` (local neural TTS; `--voice` = piper model name) or `--engine gemini` (gemini-2.5-pro-tts on Vertex AI; `--voice` = prebuilt voice name). The built-in speech-synthesis voices were removed — not good enough. `?voiceover` starts narration on the first user gesture. `instance.toggleNarration()` programmatically.
329
+ - **Narration**: `V` toggles voice-over; `N` opens the picker (persisted per deck). Two sources. **Recorded**: pre-rendered per-slide audio (`<dir>/slide-NN.m4a`, 1-based like `state.slide`), synced to slide changes; the deck configures `narration: { files: '<dir>' }` or `[{ label, dir }, …]` for several takes. **Live voice**: the player synthesizes each slide's notes on the fly through the local bridge (`decklight tts`, default `http://127.0.0.1:8787/tts`, override via `narration.liveUrl`). The bridge speaks with one of three engines (`--engine`, tools/tts-engines.mjs): **gemini** (gemini-2.5-{pro,flash}-tts on Vertex AI — the only engine that honors a delivery style; no free tier, and a fresh project's per-minute quota 429s under the lookahead's bursts), **chirp** (Chirp 3: HD on the Cloud Text-to-Speech API — the same 30 star-named voices, ~1s a sentence, 1M characters a month free, no style channel), or **piper** (a local neural model — offline, unlimited, free, no credentials; one voice per installed model, and the process is held RESIDENT because piper reloads its ~120 MB model on every start). `GET /ping` reports `{engine, model, voices, stylable}` and the picker offers exactly those voices, skipping the tone step when the engine cannot be told how to speak — a roster the bridge cannot pronounce would be a silent lie. **The voice is the clock**: auto-advance is driven by narration finishing, so when the voice CANNOT be played — a quota 429, an unreachable bridge, a browser that blocked autoplay, a recorded track with no file for this slide — the deck **stops advancing** rather than walking the talk past slides nobody has heard, and says why in a message (`I`) naming the cause and the way out (`--tts-engine chirp` for a 429, `decklight tts` for a dead bridge, one click for blocked audio). Narration switches itself off; `V` retries — the picker drills tracks → Gemini voice (30 prebuilt, flavor-tagged) → tone (six presets or a custom typed instruction, sent as an in-prompt delivery-style prefix). Every voice row carries a ▶ **preview** that speaks an editable test sentence (default "Hey, this is Decklight", input at the top of the voices view, ↺ restores the default) through the bridge in that voice; tone rows preview the drafted voice in that delivery style, and the custom-tone input has a ▶ to audition a typed instruction before committing it. After a preview plays, the rest of its roster prefetches sequentially in the background (all voices neutrally, or all tones for the drafted voice). Two preview caches: the default sentence's cache is permanent once built; the custom sentence's cache holds exactly one sentence and is swapped (old audio freed) when the text changes. **Build-synced auto-advance**: the ⟨CLICK⟩ markers that segment the notes for the speaker view segment the audio too — segment k is synthesized as its own clip and narrates build step k (0 = arrival); when a clip ends the deck reveals the next build, and after the last segment it moves to the next slide, so a deck with well-segmented notes presents itself beat by beat. A segment with no words advances after a short beat; a slide with no notes is skipped; manual navigation mid-clip wins over the pending advance and re-syncs the voice to the new step. **`data-narration="hold"`** on a section marks it interactive (quiz, exercise, live demo): narration plays whatever notes it has and builds still sync, but the deck never auto-advances *off* it — the presenter moves on manually and narration resumes on the next slide. The spoken unit is a **sentence**: each ⟨CLICK⟩ segment splits into sentences, every sentence is its own TTS call and cache entry (slide, segment, sentence, voice, style), playback chains them and advances only after the segment's last one — so first audio arrives after one short synthesis, never a whole paragraph. While narration is on, a **lookahead buffer** keeps the next 10 sentences synthesized in the background (a few parallel low-priority workers, window re-derived from the current position, results landing in the same cache); an unreachable bridge toasts once and pauses the buffer until the next event. `⇧V` downloads per-slide `slide-NN.wav` files **stitched from this same sentence cache** (short silences joining sentences and builds) — already-heard clips cost nothing, only unheard sentences synthesize. **`P` pauses/resumes** narration — audio freezes mid-sentence and resumes exactly there, and auto-advance holds while paused. Captions (`C`) follow the voice **sentence by sentence** during live narration (segment-level when narration is off). With nothing configured, `V` opens the picker instead of failing. Files are generated by `tools/voiceover.mjs`: notes → optional local-LLM rewrite → `--engine piper` (local neural TTS; `--voice` = piper model name) or `--engine gemini` (gemini-2.5-pro-tts on Vertex AI; `--voice` = prebuilt voice name). The built-in speech-synthesis voices were removed — not good enough. `?voiceover` starts narration on the first user gesture. `instance.toggleNarration()` programmatically.
330
+ - **Character** (`N` → Character…, or palette → Character…): an animated narrator in a stage corner whose lips sync to the narration — fully offline, no cloud service. Two render modes behind one overlay (`.decklight-character`, persisted per deck): **🎭 2D character** — a layered SVG bust (theme-aware clothing/backdrop, blink, idle sway) with one mouth group per Rhubarb shape (`A–H` + `X` rest); a 30 Hz loop maps `narrAudio.currentTime` onto a **viseme timeline** and shows the matching `[data-mouth]` group, so pause (`P`) and voice speed (`<`/`>`) sync for free. **🎥 Neural video** — a muted picture-in-picture `<video>` talking head (audio always comes from the narration element; muted video is immune to autoplay policy) generated by Wav2Lip or SadTalker on the presenter's own GPU, drift-corrected against the audio clock (±150 ms) and mirroring its play/pause/rate. Timelines and clips come from the **lipsync bridge** (`decklight lipsync`, default `http://127.0.0.1:8789`, override via `narration.character.bridgeUrl`; CORS-open, 127.0.0.1-only, disk-cached in `~/.cache/decklight/lipsync` keyed by audio+params hash): `GET /ping` reports which engines actually resolve (the picker greys out the rest), `POST /viseme?text=` (raw WAV body → timeline JSON v1: `{v, duration, cues: [{t, v}]}` — start-time cues, each shape holds until the next), `POST /video?engine=&portrait=` (raw WAV → muted faststart MP4; strictly serial GPU queue). In **live voice** mode the sentence is the unit here too: the lookahead buffer that keeps 10 sentences of audio warm hands each synthesized sentence's WAV to the bridge, so lip-sync data prefetches through the same window, workers, and promise-cache dedup as the voice — and playback NEVER waits on lip-sync (a late timeline lands mid-sentence; until then the **fallback** animates: `amplitude` (default) drives a coarse 4-shape mouth from a WebAudio analyser, `hide` shows the idle face). In **recorded** mode the overlay loads per-slide sidecars from the track's dir — `slide-NN.visemes.json` / `slide-NN.mp4`, generated by `tools/lipsync.mjs` (rhubarb + optional SadTalker/Wav2Lip batch, hash-incremental like voiceover.mjs) — preferring an inline `<script type="application/json" data-decklight-visemes="slide-NN">` block when present (`decklight bundle` inlines viseme JSONs; fetch is blocked on `file://`). `⇧V` exports `slide-NN.visemes.json` alongside each stitched WAV (same sentence cache, same silence gaps) so a recorded set is character-ready with zero extra synthesis. **Solo** (`N` → Character… → Solo, or palette → "Character solo"): the narrator takes the stage — the slide content, progress bar and slide number step aside (`visibility: hidden` on `.decklight-stage`, which the overlay is a sibling of) and the character centers, sized to the stage (`--character-solo-size`, default `min(74vh, 74vw)`). A talking-head slide with nothing else on it, without authoring one. Works with either render mode, persists per deck alongside `mode`, and is a *presentation* state, not a layout: the root's `decklight-solo` class is only ever set while the character is actually on screen, so turning the character off — or stopping the narration — can never leave a blank stage behind. Turning solo ON shows the character immediately (idling, blinking) rather than waiting for `V`. Config (`narration.character`, all optional): `mode: 'off'|'viseme'|'video'` (picker overrides, persisted), `solo: boolean` (default false; picker overrides, persisted), `bridgeUrl`, `position: 'br'|'bl'|'tr'|'tl'`, `size` (design px, default 220), `svg` (custom art: inline markup, `'#id'` ref, or URL — contract: `[data-mouth="A"…"X"]` groups; optional `[data-eyelid]`/`[data-idle]` get the blink/sway), `sprites: {A: url, …}` (image frames instead), `engine`/`portrait` (video mode; Wav2Lip suits live — static pose, seamless per-sentence cuts; SadTalker suits batch clips), `fallback: 'amplitude'|'hide'`. Bundles: viseme JSONs inline (1–4 KB/slide); per-slide MP4s stay external with a CLI notice — video cannot inline sanely.
322
331
  - **Command palette**: `/` opens a Claude-style palette — every command with its shortcut, type-to-filter, `Enter` runs, `Esc` clears then closes. Argument commands (Theme…, Font…, Narration voice…, Module…, Find slide…) drill into their pickers; contextual commands appear only when applicable (Save generated theme, Module). Inline arguments work: `goto 27` — or just typing `27` — surfaces a “Go to slide 27 / N” row (clamped to the deck), and selecting the bare “Go to slide…” command keeps the palette open with `goto ` prefilled. Text matching no command falls back to a “Search slides for …” row that opens the finder with the query prefilled.
323
332
  - **Slide finder**: reached from the palette (`/` → Enter, or the search fallback) — a find-a-slide overlay with the picker's anatomy — a query bar and result list on the left, a live preview of the selected slide on the right. Typing filters as an AND over the query's words against each slide's text; slides whose **title** contains every word rank first, body-only matches follow, and every match is listed as `<slide number> · <title>` (slides without a heading fall back to their leading text). `↑/↓`/hover browse (the preview swaps live), `Enter`/click jumps to the slide, `Backspace` edits, `Esc` clears the query then closes. The preview reuses the picker's lazy embedded-deck mechanism — the iframe boots once (carrying the active theme, generated/custom included via `?gen=`), then selections postMessage `{__decklightPreview: {goto: [slide, step]}}` into it; no reload per candidate.
324
- - **Playlist (multi-deck navigation)**: `Decklight.init({ playlist: { modules: [{title, href}…], index: n } })`. Advancing past the last build of the last slide navigates to the next module (`href#/1/0`); reversing before slide 1 goes to the previous module's end (`href#/999/999` — oversized hashes clamp to the last slide/step). `M` opens the **module menu** (list overlay, current module ✓, `↑/↓` + `Enter` navigates, `Esc`/`M` closes; the slide-number chrome shows the module title and opens the menu on click). Works on `file://` with relative hrefs; embedded instances never chain.
333
+ - **Playlist (multi-deck navigation)**: `Decklight.init({ playlist: { modules: [{title, href}…], index: n } })`. Advancing past the last build of the last slide navigates to the next module (`href#/1/0`); reversing before slide 1 goes to the previous module's end (`href#/999/999` — oversized hashes clamp to the last slide/step). The other modules appear as rows in the **slide finder** (`G`) — marked `▸ <title> — module`, previewed like any slide, and `Enter` loads that file; the slide-number chrome shows the module title and opens the finder on click. There is no separate module menu: "go somewhere" is one question with one answer. Works on `file://` with relative hrefs; embedded instances never chain.
325
334
  - **Speaker view**: `S` opens a popup (synced via BroadcastChannel): current + next slide thumbnails, notes (with `⟨CLICK⟩` markers highlighted as the matching build lands), elapsed timer, build step list (provider labels). **Rehearse mode**: pressing `S` again (in the deck or in the popup; the header badge also toggles) swaps the prose notes for the slide's `aside.rehearse` cue cards (§1) — rendered large and bold, one cue per segment, same said/now/next highlighting. Slides without rehearse notes fall back to the full prose. `S` in the deck only opens a new popup when none is connected; while one is open it toggles the mode.
326
335
  - **Print/PDF**: `?print` renders all slides sequentially, every build complete, terminal casts fully expanded, one slide per page (`@media print` CSS). No JS needed after layout.
327
336
  - **Overflow guardrail**: content that exceeds the slide flex-shrinks into a scroll box and reads as clipped. The engine warns (`console.warn`) and marks the section with a `data-overflow` attribute — on each slide activation, and for the whole deck in `?print` — so authoring agents can assert `[data-overflow]` is absent in their headless verification.
328
- - **Pinned titles**: `pinTitles: false | true | <px>` keeps slide titles at one vertical position instead of drifting with content height. `true` pins at **99px** from the stage top (design coordinates — the natural title position of the course's "The Single-Agent Limit" diagram slide, the chosen reference); a number pins at that Y. The leading `h1`/`h2` of each **pinnable** section is absolutely positioned at the pin Y; the section reserves `pin Y + measured title height + 18px` of top padding so the remaining content centers below. Pinnable = has a leading `h1`/`h2` AND content beyond it (`ul, ol, svg, pre, table, .terminal, img, .columns` outside the notes) — title cards and quote/statement slides stay centered. Per-slide: `data-pin` forces a pin (even when the config is off), `data-pin="none"` opts out, `data-pin="<px>"` overrides the Y. Titles are re-measured on `sync()` and when webfonts finish loading; print uses the same layout. A detected **subtitle** (§1) joins the pinned header block — absolutely positioned directly beneath the title (6px gap) and included in the reserved padding, so content centers below title + subtitle.
337
+ - **Pinned titles**: `pinTitles: true | false | <px>` keeps slide titles at one vertical position instead of drifting with content height. **On by default** (`true`); `pinTitles: false` restores the drift-with-content centering deck-wide. `true` pins at **99px** from the stage top (design coordinates — the natural title position of the course's "The Single-Agent Limit" diagram slide, the chosen reference); a number pins at that Y. The leading `h1`/`h2` of each **pinnable** section is absolutely positioned at the pin Y; the section reserves `pin Y + measured title height + 18px` of top padding so the remaining content centers below. Pinnable = has a leading `h1`/`h2` AND content beyond it (`ul, ol, svg, pre, table, .terminal, img, .columns` outside the notes) — title cards and quote/statement slides stay centered. Per-slide: `data-pin` forces a pin (even when the config is off), `data-pin="none"` opts out, `data-pin="<px>"` overrides the Y. Titles are re-measured on `sync()` and when webfonts finish loading; print uses the same layout. A detected **subtitle** (§1) joins the pinned header block — absolutely positioned directly beneath the title (6px gap) and included in the reserved padding, so content centers below title + subtitle.
329
338
  - **Terminal footprint**: a terminal's screen area has a stable size — a **16:9 aspect floor** (width-driven) clamped by the `data-rows` cap as the max — so the box arrives full-size before anything plays and never resizes as steps stream in (output beyond the box scrolls). Real print expands casts fully.
330
- - `Decklight.init(config)` options: `transition`, `hash` (default true), `controls` (default true: prev/next chevrons + progress bar), `slideNumber` (default `false | 'n' | 'n/N'`), `width/height` design resolution (default 1280×720, scaled to fit), `themes` (array of theme names for the picker/cycle; default: all shipped themes), `playlist` (multi-deck navigation, above), `pinTitles` (pinned titles, above), `concepts` (diagram concept-color pinning, §3), `logo` (brand mark, above).
339
+ - `Decklight.init(config)` options: `transition`, `hash` (default true), `controls` (default true: prev/next chevrons; the progress bar is the `H` toggle, above), `slideNumber` (default `false | 'n' | 'n/N'`), `width/height` design resolution (default 1280×720, scaled to fit), `themes` (array of theme names for the picker/cycle; default: all shipped themes), `playlist` (multi-deck navigation, above), `pinTitles` (pinned titles, above), `concepts` (diagram concept-color pinning, §3), `logo` (brand mark, above).
331
340
  - **Single-file bundling**: `decklight bundle <deck.html> [-o out.html] [--themes current|all|a,b,…]` flattens a deck into one self-contained HTML — runtime and structure CSS inlined, selected themes embedded as inline-theme blocks, `data-cast` terminals converted to `data-cast-inline`, images to data: URIs. Playlist links can't resolve inside a single file; the CLI lists them as a notice.
332
- - **Merged single-file presentation**: `decklight bundle <deck.html> --all [--title "…"]` follows the deck's playlist and concatenates EVERY module's sections into one deck (explicit form: `decklight bundle a.html b.html … -o one.html`). Each module's first section is marked `data-module="<title>"`; embedded cast ids are prefixed per module to stay unique; relative asset refs are rebased onto the first deck's directory; the per-module `playlist` config is stripped. **In-file module navigation**: when sections carry `data-module`, the `M` menu lists those markers and Enter/click `goto()`s the marker's slide (no page loads), and the chrome module tag shows the module of the current slide (nearest preceding marker). Marker mode takes precedence over `config.playlist`.
341
+ - **Merged single-file presentation**: `decklight bundle <deck.html> --all [--title "…"]` follows the deck's playlist and concatenates EVERY module's sections into one deck (explicit form: `decklight bundle a.html b.html … -o one.html`). Each module's first section is marked `data-module="<title>"`; embedded cast ids are prefixed per module to stay unique; relative asset refs are rebased onto the first deck's directory; the per-module `playlist` config is stripped. **In-file module navigation**: `data-module` sections are ordinary slides, so the finder (`G`) already finds them by title or body text and `goto()`s them with no page load; the chrome module tag shows the module of the current slide (nearest preceding marker).
333
342
 
334
343
  ## 9. Public JS API
335
344
 
@@ -344,6 +353,8 @@ instance.theme(name) // switch theme programmatically
344
353
  instance.themePicker.open() / .close()
345
354
  instance.generateTheme() // ⌃T programmatically; returns the autoname
346
355
  instance.cycleFont(dir) // [ / ] programmatically (±1)
356
+ instance.cycleLayout(dir) // L / ⇧L programmatically (±1; dev mode only)
357
+ instance.layoutRing(slide?) // the layout ring a slide would cycle (skips applied)
347
358
  instance.toggleNarration() // V programmatically
348
359
  instance.saveGeneratedTheme(name?) // ⌃⇧T; a name argument skips the prompt
349
360
  ```
@@ -357,7 +368,8 @@ decklight/
357
368
  src/md/ markdown slide support (marked)
358
369
  src/code/ highlight bundling + line stepping provider
359
370
  src/terminal/ ansi.mjs (parser), player.mjs (provider + modes)
360
- cli/ decklight.mjs (dispatcher: rec/refresh/export/bundle) + rec.mjs, bundle.mjs
371
+ cli/ decklight.mjs (dispatcher: rec/refresh/export/bundle/tts/lipsync/edit/dev) + rec.mjs, bundle.mjs, edit.mjs, dev.mjs, agents.mjs (AI-agent roster)
372
+ tools/ voiceover.mjs (batch TTS) + voiceover-server.mjs (tts bridge), lipsync.mjs (batch visemes/video) + lipsync-server.mjs (lipsync bridge), visemes.mjs (timeline v1)
361
373
  themes/ 30 × <name>.css + gallery.html
362
374
  dist/ decklight.js (IIFE, global Decklight), decklight.css
363
375
  demo/ kitchen-sink.html + casts/
package/cli/agents.mjs ADDED
@@ -0,0 +1,102 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The AI-agent roster for `decklight dev` — which coding agents this machine
5
+ // can run, and how to hand one a single editing task without a TTY.
6
+ //
7
+ // Every entry is a one-shot, non-interactive invocation: the agent gets the
8
+ // instruction, edits the deck file in place, and exits. The dev server's file
9
+ // watcher then reloads every connected browser, and the pre-run snapshot goes
10
+ // on the same undo stack as the player's own edits — Z takes an agent's edit
11
+ // back exactly like a layout change.
12
+ //
13
+ // The roster is data: adding an agent is one entry (bin to probe + the args
14
+ // of its headless mode). Order is preference order — the first detected
15
+ // agent is the default when the player doesn't name one.
16
+
17
+ import { existsSync } from 'node:fs';
18
+ import { delimiter, join } from 'node:path';
19
+
20
+ export const AGENTS = [
21
+ {
22
+ name: 'claude', label: 'Claude Code', bin: 'claude',
23
+ // -p is print (headless) mode; acceptEdits lets it write the deck file
24
+ // without an interactive approval it has no TTY to ask on.
25
+ args: (prompt) => ['-p', prompt, '--permission-mode', 'acceptEdits'],
26
+ },
27
+ {
28
+ name: 'codex', label: 'Codex CLI', bin: 'codex',
29
+ // exec is the non-interactive subcommand; --full-auto keeps it inside
30
+ // the workspace sandbox while allowing file writes.
31
+ args: (prompt) => ['exec', '--full-auto', prompt],
32
+ },
33
+ {
34
+ name: 'bob', label: 'IBM Bob', bin: 'bob',
35
+ // -p is Bob Shell's non-interactive prompt mode; --accept-license keeps
36
+ // it from hanging on the license prompt when there is no TTY.
37
+ args: (prompt) => ['-p', prompt, '--accept-license'],
38
+ },
39
+ {
40
+ name: 'gemini', label: 'Gemini CLI', bin: 'gemini',
41
+ args: (prompt) => ['--yolo', '-p', prompt],
42
+ },
43
+ {
44
+ name: 'copilot', label: 'GitHub Copilot CLI', bin: 'copilot',
45
+ args: (prompt) => ['-p', prompt, '--allow-all-tools'],
46
+ },
47
+ {
48
+ name: 'opencode', label: 'OpenCode', bin: 'opencode',
49
+ args: (prompt) => ['run', prompt],
50
+ },
51
+ {
52
+ name: 'goose', label: 'Goose', bin: 'goose',
53
+ args: (prompt) => ['run', '-t', prompt],
54
+ },
55
+ {
56
+ name: 'aider', label: 'Aider', bin: 'aider',
57
+ // aider wants the file on the command line; --no-auto-commits because
58
+ // dev's own autocommit (and the undo stack) owns history here.
59
+ args: (prompt, deck) => ['--yes-always', '--no-auto-commits', '--message', prompt, deck],
60
+ },
61
+ {
62
+ name: 'cursor', label: 'Cursor CLI', bin: 'cursor-agent',
63
+ args: (prompt) => ['-p', prompt, '--force'],
64
+ },
65
+ {
66
+ name: 'qwen', label: 'Qwen Code', bin: 'qwen',
67
+ args: (prompt) => ['--yolo', '-p', prompt],
68
+ },
69
+ ];
70
+
71
+ /** Is `bin` runnable — an explicit path that exists, or a name on $PATH? */
72
+ export function onPath(bin, env = process.env) {
73
+ if (!bin) return false;
74
+ if (bin.includes('/')) return existsSync(bin);
75
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
76
+ for (const dir of (env.PATH || '').split(delimiter)) {
77
+ if (!dir) continue;
78
+ for (const ext of exts) if (existsSync(join(dir, bin + ext))) return true;
79
+ }
80
+ return false;
81
+ }
82
+
83
+ /** The subset of AGENTS this machine can actually run, in preference order. */
84
+ export function detectAgents({ env = process.env, hasBin = onPath } = {}) {
85
+ return AGENTS.filter((a) => hasBin(a.bin, env));
86
+ }
87
+
88
+ /**
89
+ * The exact spawn for one editing task: `name` picks the agent (or the first
90
+ * detected one when omitted), `instruction` is the user's ask, `deck` the
91
+ * file it should edit. Returns { bin, args, label } or null when the agent
92
+ * isn't available.
93
+ */
94
+ export function agentCommand(name, instruction, deck, { env = process.env, hasBin = onPath } = {}) {
95
+ const roster = detectAgents({ env, hasBin });
96
+ const agent = name ? roster.find((a) => a.name === name) : roster[0];
97
+ if (!agent) return null;
98
+ const prompt = `Edit the Decklight deck file "${deck}" — a single-file HTML presentation ` +
99
+ '(one top-level <section> per slide; see SPEC.md or the decklight skill if present). ' +
100
+ `Apply this change, editing the file in place: ${instruction}`;
101
+ return { bin: agent.bin, args: agent.args(prompt, deck), label: agent.label, name: agent.name };
102
+ }
package/cli/bundle.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
2
5
  /**
3
6
  * decklight bundle — flatten Decklight decks into ONE self-contained HTML file
4
7
  * (send it to anyone; opens from disk, no server, no sibling files).
@@ -356,6 +359,40 @@ html = html.replace(
356
359
  return tag.replace(m[0], `data-cast-inline="#${id}"`);
357
360
  });
358
361
 
362
+ // ---------------------------------------------- narration lip-sync sidecars
363
+
364
+ // slide-NN.visemes.json next to a narration track (tools/lipsync.mjs, or the
365
+ // ⇧V export) inlines as a data-decklight-visemes block — fetch() is blocked
366
+ // on file:// and a bundle should not depend on a sidecar folder. Per-slide
367
+ // MP4s stay external: video cannot inline sanely (a deck's worth is
368
+ // 50–150 MB), same posture as playlist links.
369
+ {
370
+ const seen = new Set();
371
+ const narrDirs = [...new Set(
372
+ [...html.matchAll(/\b(?:dir|files)\s*:\s*['"]([^'"]+)['"]/g)].map((m) => m[1]))];
373
+ for (const d of narrDirs) {
374
+ const abs = path.resolve(deckDir, d);
375
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) continue;
376
+ let mp4s = 0;
377
+ for (const f of fs.readdirSync(abs).sort()) {
378
+ const vm = f.match(/^slide-(\d+)\.visemes\.json$/);
379
+ if (vm) {
380
+ if (seen.has(vm[1])) {
381
+ notices.push(`character visemes: ${d}/${f} skipped — slide ${vm[1]} already inlined from another track`);
382
+ continue;
383
+ }
384
+ seen.add(vm[1]);
385
+ embeds.push(`<script type="application/json" data-decklight-visemes="slide-${vm[1]}">\n`
386
+ + `${jsonSafe(fs.readFileSync(path.join(abs, f), 'utf8'))}\n</script>`);
387
+ } else if (/^slide-\d+\.mp4$/.test(f)) mp4s++;
388
+ }
389
+ if (mp4s) {
390
+ notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ stay external — ship the folder next to the bundle`);
391
+ }
392
+ }
393
+ if (seen.size) notices.push(`character visemes: inlined ${seen.size} slide timeline(s)`);
394
+ }
395
+
359
396
  // -------------------------------------------------------------- assemble
360
397
 
361
398
  // Anchor to the LAST </body>: the inlined runtime contains the speaker-view
package/cli/decklight.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
2
5
  /**
3
6
  * decklight — the Decklight command line.
4
7
  *
@@ -7,6 +10,7 @@
7
10
  * decklight export convert a cast to asciicast v2
8
11
  * decklight bundle flatten a deck into one self-contained HTML file
9
12
  * decklight tts serve the live voice bridge (on-the-fly Gemini narration)
13
+ * decklight lipsync serve the lip-sync bridge (character visemes + talking-head video)
10
14
  *
11
15
  * The subcommand implementations live in rec.mjs and
12
16
  * bundle.mjs (importable modules; direct execution still works but
@@ -32,8 +36,12 @@ Commands:
32
36
  EXAMPLE: decklight bundle deck.html --all --title "My Course" (merge the whole playlist into one file)
33
37
  tts serve the live voice bridge — the player synthesizes narration on the fly through it
34
38
  EXAMPLE: decklight tts (then pick "Live voice…" in the deck's / palette)
39
+ lipsync serve the lip-sync bridge — offline visemes (rhubarb) + talking-head video (local GPU)
40
+ EXAMPLE: decklight lipsync (then pick "Character…" in the deck's / palette)
35
41
  edit serve the deck with live reload; E in the player edits speaker notes back into the file
36
42
  EXAMPLE: decklight edit demo/showcase.html (then open the printed URL)
43
+ dev one command for the whole loop: edit + every bridge this machine can run, one Ctrl-C
44
+ EXAMPLE: decklight dev demo/showcase.html (bridges without prerequisites are skipped)
37
45
  help show this help, or a command's help: decklight help bundle
38
46
  `;
39
47
 
@@ -84,11 +92,21 @@ switch (cmd) {
84
92
  await ttsMain(rest);
85
93
  break;
86
94
  }
95
+ case 'lipsync': {
96
+ const { lipsyncMain } = await import('../tools/lipsync-server.mjs');
97
+ await lipsyncMain(rest);
98
+ break;
99
+ }
87
100
  case 'edit': {
88
101
  const { editMain } = await import('./edit.mjs');
89
102
  await editMain(rest);
90
103
  break;
91
104
  }
105
+ case 'dev': {
106
+ const { devMain } = await import('./dev.mjs');
107
+ await devMain(rest);
108
+ break;
109
+ }
92
110
  default:
93
111
  process.stderr.write(`decklight: unknown command "${cmd}"\n\n`);
94
112
  globalHelp(1);
package/cli/dev.mjs ADDED
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight dev — one command for the whole authoring loop: the edit server
6
+ // plus whichever optional bridges this machine can actually run.
7
+ //
8
+ // decklight dev <deck.html> [--port 8788] [--tts-port 8787] [--lipsync-port 8789]
9
+ // [--project <id>] [--rhubarb <bin>] [--portrait <name=img.png>]…
10
+ // [--no-tts] [--no-lipsync]
11
+ //
12
+ // The bridges keep their OWN PROCESSES on their own ports, exactly as if you
13
+ // had started them by hand — dev only owns their lifetime, so one Ctrl-C
14
+ // stops everything. That split is the point: edit needs nothing (no
15
+ // credentials, no cost), tts holds Google credentials and spends money per
16
+ // call, lipsync pins a GPU. Folding them into one process would let a Wav2Lip
17
+ // crash or an expired token take down the server you are editing through.
18
+ //
19
+ // A bridge whose prerequisites are missing is SKIPPED with the reason and the
20
+ // fix, never a hard failure: `decklight dev deck.html` on a bare machine still
21
+ // gives you live reload and notes editing, and the player degrades on its own
22
+ // (each bridge is probed via /ping).
23
+
24
+ import { spawn, execFileSync } from 'node:child_process';
25
+ import { existsSync } from 'node:fs';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { createInterface } from 'node:readline/promises';
28
+ import { onPath, detectAgents } from './agents.mjs';
29
+ import { validProjectId } from '../tools/gemini-tts.mjs';
30
+ import { ENGINES as TTS_ENGINES } from '../tools/tts-engines.mjs';
31
+
32
+ export { onPath }; // historical home — dev grew it, agents.mjs owns it now
33
+
34
+ const CLI = fileURLToPath(new URL('./decklight.mjs', import.meta.url));
35
+
36
+ const USAGE = `usage: decklight dev <deck.html> [--port 8788] [--tts-port 8787] [--lipsync-port 8789]
37
+ [--tts-engine gemini|chirp|piper] [--project <id>] [--no-tts] [--no-lipsync]
38
+ [--git | --no-git] [--commit-every <s>] [--agent <name>]
39
+ brings up the edit server plus every bridge this machine can run, under one Ctrl-C
40
+
41
+ --port N edit server (live reload + edit write-back) [8788]
42
+ --tts-port N live voice bridge [8787]
43
+ --lipsync-port N lip-sync bridge (visemes + talking head) [8789]
44
+ --no-tts don't start the voice bridge
45
+ --no-lipsync don't start the lip-sync bridge
46
+ --git / --no-git auto-commit the deck on a cadence / never touch git
47
+ (no repo + no flag: dev ASKS whether to create one)
48
+ --commit-every N autocommit cadence in seconds [300]
49
+ --agent <name> preferred AI agent for A (default: first detected)
50
+
51
+ --tts-engine E gemini Vertex AI, best delivery, honors a style — no free tier [default]
52
+ chirp Cloud TTS Chirp 3: HD — same voices, ~1s, 1M chars/month free
53
+ piper local, offline, unlimited, no project needed
54
+
55
+ tts flags --project <id> (or $GOOGLE_CLOUD_PROJECT; gemini/chirp only),
56
+ --tts-model, --location, --voice, --data-dir, --lang
57
+ lipsync flags --rhubarb <bin>, --portrait <name=img.png>…, --wav2lip-dir,
58
+ --wav2lip-ckpt, --sadtalker-dir, --python, --cache-dir
59
+ (all passed straight through — see decklight tts --help / lipsync --help)`;
60
+
61
+ // flags that take a value (so the deck argument can be found past them)
62
+ const VALUE_FLAGS = new Set([
63
+ '--port', '--tts-port', '--lipsync-port', '--tts-engine', '--project', '--tts-model',
64
+ '--location', '--voice', '--data-dir', '--lang',
65
+ '--rhubarb', '--portrait', '--wav2lip-dir', '--wav2lip-ckpt', '--sadtalker-dir',
66
+ '--python', '--cache-dir', '--commit-every', '--agent',
67
+ ]);
68
+
69
+ /**
70
+ * Decide what to bring up, WITHOUT starting anything — the whole capability
71
+ * policy in one pure function, so it can be tested without binding a port.
72
+ * Returns { deck, run: [{name, tag, args, url}], skip: [{name, why}],
73
+ * agents: [names the machine can run] }.
74
+ */
75
+ export function planServices({ args = [], env = process.env, hasBin = onPath } = {}) {
76
+ const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
77
+ const opts = (flag) => args.flatMap((a, i) => (a === flag ? [args[i + 1]] : []));
78
+ const has = (flag) => args.includes(flag);
79
+ const pass = (flag) => (opt(flag) !== undefined ? [flag, opt(flag)] : []);
80
+
81
+ // first bare token is the deck — step over flags that consume a value, so
82
+ // `dev --port 8788 deck.html` doesn't mistake "8788" for the deck
83
+ let deck;
84
+ for (let i = 0; i < args.length; i++) {
85
+ const a = args[i];
86
+ if (a.startsWith('-')) { if (VALUE_FLAGS.has(a)) i++; continue; }
87
+ deck = a;
88
+ break;
89
+ }
90
+
91
+ const run = [];
92
+ const skip = [];
93
+
94
+ const editPort = opt('--port', '8788');
95
+ run.push({
96
+ name: 'edit',
97
+ tag: 'deck',
98
+ args: ['edit', deck, '--port', editPort,
99
+ ...(has('--git') ? ['--git'] : []), ...(has('--no-git') ? ['--no-git'] : []),
100
+ ...pass('--commit-every'), ...pass('--agent')],
101
+ url: `http://127.0.0.1:${editPort}/${deck ?? ''}`,
102
+ });
103
+
104
+ // live voice — the cloud engines exit without a GCP project, so don't even
105
+ // start them; piper needs no credentials at all, only the binary
106
+ const ttsPort = opt('--tts-port', '8787');
107
+ const ttsEngine = opt('--tts-engine', 'gemini');
108
+ const project = opt('--project', env.GOOGLE_CLOUD_PROJECT);
109
+ const cloudVoice = ttsEngine === 'gemini' || ttsEngine === 'chirp';
110
+ const ttsArgs = () => [
111
+ 'tts', '--port', ttsPort,
112
+ ...(has('--tts-engine') ? ['--engine', ttsEngine] : []),
113
+ ...(cloudVoice ? ['--project', project] : []),
114
+ ...pass('--tts-model'), ...pass('--location'),
115
+ ...pass('--voice'), ...pass('--data-dir'), ...pass('--lang'),
116
+ ];
117
+ if (has('--no-tts')) {
118
+ skip.push({ name: 'voice', why: 'disabled with --no-tts' });
119
+ } else if (!TTS_ENGINES.includes(ttsEngine)) {
120
+ skip.push({ name: 'voice', why: `unknown --tts-engine '${ttsEngine}' — use ${TTS_ENGINES.join(', ')}` });
121
+ } else if (ttsEngine === 'piper' && !hasBin('piper', env)) {
122
+ skip.push({ name: 'voice', why: 'piper not on PATH — install it (uv tool install piper-tts)' });
123
+ } else if (cloudVoice && !project) {
124
+ skip.push({ name: 'voice', why: `${ttsEngine} needs a GCP project — pass --project <id>, set GOOGLE_CLOUD_PROJECT, or use --tts-engine piper` });
125
+ } else if (cloudVoice && !validProjectId(project)) {
126
+ // caught here rather than at the first narration: the bridge would start,
127
+ // look healthy, and only fail on a keypress — with a 403 naming a project
128
+ // nobody typed
129
+ skip.push({ name: 'voice', why: `not a GCP project id: ${JSON.stringify(project)} — stray punctuation from a copy-paste?` });
130
+ } else {
131
+ run.push({ name: 'tts', tag: 'voice', args: ttsArgs(), url: `http://127.0.0.1:${ttsPort}` });
132
+ }
133
+
134
+ // lip-sync — starts degraded (it probes its own engines), so only bother when
135
+ // something it can actually use is present
136
+ const lipPort = opt('--lipsync-port', '8789');
137
+ const rhubarb = opt('--rhubarb', 'rhubarb');
138
+ const configured = has('--rhubarb') || has('--portrait') || has('--wav2lip-dir') || has('--sadtalker-dir');
139
+ if (has('--no-lipsync')) {
140
+ skip.push({ name: 'lip-sync', why: 'disabled with --no-lipsync' });
141
+ } else if (!configured && !hasBin(rhubarb, env)) {
142
+ skip.push({ name: 'lip-sync', why: 'rhubarb not on PATH — install it, or pass --rhubarb/--portrait' });
143
+ } else {
144
+ run.push({
145
+ name: 'lipsync',
146
+ tag: 'lips',
147
+ args: [
148
+ 'lipsync', '--port', lipPort,
149
+ ...(has('--rhubarb') ? ['--rhubarb', rhubarb] : []),
150
+ ...opts('--portrait').flatMap((p) => ['--portrait', p]),
151
+ ...pass('--wav2lip-dir'), ...pass('--wav2lip-ckpt'),
152
+ ...pass('--sadtalker-dir'), ...pass('--python'), ...pass('--cache-dir'),
153
+ ],
154
+ url: `http://127.0.0.1:${lipPort}`,
155
+ });
156
+ }
157
+
158
+ return { deck, run, skip, agents: detectAgents({ env, hasBin }).map((a) => a.name) };
159
+ }
160
+
161
+ /** Is `dir` inside a git work tree? (execFile injectable for tests) */
162
+ export function inGitRepo(dir, exec = execFileSync) {
163
+ try {
164
+ return exec('git', ['rev-parse', '--is-inside-work-tree'],
165
+ { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() === 'true';
166
+ } catch { return false; }
167
+ }
168
+
169
+ const COLORS = { deck: '\x1b[36m', voice: '\x1b[35m', lips: '\x1b[33m' };
170
+ const DIM = '\x1b[2m';
171
+ const RESET = '\x1b[0m';
172
+
173
+ export async function devMain(args) {
174
+ if (args.includes('--help') || args.includes('-h')) { console.log(USAGE); return; }
175
+
176
+ let plan = planServices({ args });
177
+ const deck = plan.deck;
178
+ if (!deck) {
179
+ console.error('decklight dev needs a deck: decklight dev <deck.html>\n');
180
+ console.error(USAGE);
181
+ process.exitCode = 1;
182
+ return;
183
+ }
184
+ if (!existsSync(deck)) {
185
+ console.error(`decklight dev: no such deck: ${deck}`);
186
+ process.exitCode = 1;
187
+ return;
188
+ }
189
+
190
+ // No repo, no flag: offer one. A repo is where the regular autocommits go —
191
+ // the durable record behind the player's fast undo/redo loop. Only a TTY
192
+ // can be asked; headless runs stay git-less until --git says otherwise.
193
+ if (!args.includes('--git') && !args.includes('--no-git') && !inGitRepo(process.cwd())) {
194
+ if (process.stdin.isTTY && process.stdout.isTTY) {
195
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
196
+ const answer = await rl.question(' no git repository here — create one and auto-commit the deck as you edit? [Y/n] ');
197
+ rl.close();
198
+ if (!/^n/i.test(answer.trim())) plan = planServices({ args: [...args, '--git'] });
199
+ else plan = planServices({ args: [...args, '--no-git'] });
200
+ } else {
201
+ console.log(' git: no repository here — pass --git to create one and auto-commit the deck');
202
+ }
203
+ }
204
+ const { run, skip, agents } = plan;
205
+
206
+ const tty = process.stdout.isTTY;
207
+ const paint = (tag) => (tty ? `${COLORS[tag] ?? ''}${tag.padEnd(5)}${RESET}` : `${tag.padEnd(5)}`);
208
+ const note = (s) => (tty ? `${DIM}${s}${RESET}` : s);
209
+
210
+ const children = new Map();
211
+ let shuttingDown = false;
212
+
213
+ // Children write their own startup/progress lines; prefix each so three
214
+ // servers in one terminal stay readable.
215
+ const pipe = (stream, tag, out) => {
216
+ let buf = '';
217
+ stream.setEncoding('utf8');
218
+ stream.on('data', (chunk) => {
219
+ buf += chunk;
220
+ const lines = buf.split('\n');
221
+ buf = lines.pop() ?? '';
222
+ for (const line of lines) out.write(`${paint(tag)} ${line}\n`);
223
+ });
224
+ };
225
+
226
+ for (const svc of run) {
227
+ const child = spawn(process.execPath, [CLI, ...svc.args], {
228
+ stdio: ['ignore', 'pipe', 'pipe'],
229
+ });
230
+ children.set(svc.name, child);
231
+ pipe(child.stdout, svc.tag, process.stdout);
232
+ pipe(child.stderr, svc.tag, process.stderr);
233
+
234
+ child.on('exit', (code) => {
235
+ children.delete(svc.name);
236
+ if (shuttingDown) return;
237
+ if (svc.name === 'edit') {
238
+ // the deck server is the one service dev cannot run without
239
+ console.error(`${paint(svc.tag)} exited (${code}) — stopping decklight dev`);
240
+ shutdown(code ?? 1);
241
+ } else {
242
+ console.error(`${paint(svc.tag)} exited (${code}) — carrying on without it; the deck degrades on its own`);
243
+ }
244
+ });
245
+ }
246
+
247
+ for (const s of skip) console.log(note(` ${s.name.padEnd(8)} skipped — ${s.why}`));
248
+ if (!agents.length) console.log(note(' agents none detected — install claude, codex, or bob to ask an agent from the deck (A)'));
249
+ console.log(note(' Ctrl-C stops everything.\n'));
250
+
251
+ function shutdown(code = 0) {
252
+ if (shuttingDown) return;
253
+ shuttingDown = true;
254
+ for (const child of children.values()) child.kill('SIGTERM');
255
+ // give them a beat to close their listeners, then go
256
+ setTimeout(() => {
257
+ for (const child of children.values()) child.kill('SIGKILL');
258
+ process.exit(code);
259
+ }, 500).unref();
260
+ }
261
+
262
+ process.on('SIGINT', () => shutdown(0));
263
+ process.on('SIGTERM', () => shutdown(0));
264
+ }
265
+
266
+ if (import.meta.url === `file://${process.argv[1]}`) devMain(process.argv.slice(2));