decklight 0.8.0 → 0.9.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 (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +71 -26
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +35 -2
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +19 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/cli/open.mjs ADDED
@@ -0,0 +1,943 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight <deck> — THE command: open a deck. One server (edit.mjs), two
6
+ // modes: write mode, the default, brings it up as a child plus whichever
7
+ // optional bridges this machine can actually run; --no-trust runs the same
8
+ // server in this process, in no-trust mode, with no bridge beside it.
9
+ //
10
+ // decklight <deck.html | url> [--no-trust] [--port 8788] [--tts-port 8787] [--lipsync-port 8789]
11
+ // [--project <id>] [--rhubarb <bin>] [--portrait <name=img.png|clip.mp4>]…
12
+ // [--no-tts] [--no-lipsync] [--remote]
13
+ //
14
+ // The bridges keep their OWN PROCESSES on their own ports, exactly as if you
15
+ // had started them by hand — `open` only owns their lifetime, so one Ctrl-C
16
+ // stops everything. That split is the point: the deck server needs nothing (no
17
+ // credentials, no cost), tts holds Google credentials and spends money per
18
+ // call, lipsync pins a GPU. Folding them into one process would let a Wav2Lip
19
+ // crash or an expired token take down the server you are editing through.
20
+ //
21
+ // A bridge whose prerequisites are missing is SKIPPED with the reason and the
22
+ // fix, never a hard failure: `decklight deck.html` on a bare machine
23
+ // still gives you live reload and notes editing, and the player degrades on
24
+ // its own (each bridge is probed via /ping).
25
+
26
+ import { spawn } from 'node:child_process';
27
+ import { existsSync, readFileSync, realpathSync, mkdirSync, writeFileSync } from 'node:fs';
28
+ import { fileURLToPath } from 'node:url';
29
+ import { createInterface } from 'node:readline/promises';
30
+ import { onPath, detectAgents, AGENTS } from './agents.mjs';
31
+ import { validProjectId } from '../tools/gemini-tts.mjs';
32
+ import {
33
+ ENGINES as TTS_ENGINES, PIPER_DEFAULT_VOICE, piperModelDir, engineStatus,
34
+ piperDownloadCmd, piperDownloadLine,
35
+ } from '../tools/tts-engines.mjs';
36
+ import { KEY_ENV as ELEVENLABS_KEY_ENV } from '../tools/elevenlabs-tts.mjs';
37
+ import { loadTtsConfig } from '../tools/tts-setup.mjs';
38
+ import { detectLocalVoice } from '../tools/local-voice.mjs';
39
+ import { relative } from 'node:path';
40
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
41
+ import { deckFromUrl } from './clone-deck.mjs';
42
+ import { runMain } from './util.mjs';
43
+ import { openUrl } from './open-browser.mjs';
44
+ import { loadLipsyncConfig, SETUP_HINT } from '../tools/lipsync-config.mjs';
45
+ import { isPortOpen, resolvePortConflict, describePortOutcome, identifyBridge, identifyStranger, canBind } from './port-conflict.mjs';
46
+ import { leashEnv } from './supervise.mjs';
47
+ import { bannerRow, nextFlushDelay, parseReady, renderBanner } from './banner.mjs';
48
+ import { auditDeck, formatLabel } from './audit.mjs';
49
+ import { scriptHash, isTrusted, remember } from './trust.mjs';
50
+ import { staleSkills, refreshSkills, display as displayPath } from './skills.mjs';
51
+ import { configHome } from './marketplace.mjs';
52
+ import { PKG } from './skill-content.mjs';
53
+ import { selfCommand } from './pkg.mjs';
54
+ import { resolve as resolvePath } from 'node:path';
55
+
56
+ const CLI = fileURLToPath(new URL('./decklight.mjs', import.meta.url));
57
+ // The deck server's entry since `edit` stopped being a command: its module,
58
+ // run directly. The dispatcher would refuse `edit` out loud.
59
+ const EDIT = fileURLToPath(new URL('./edit.mjs', import.meta.url));
60
+
61
+ const USAGE = `usage: decklight <deck.html | git url> [--no-trust | --trust] [--open] [--port 8788]
62
+ [--git | --no-git] [--agent <name>] [--remote] [--no-tts] [--no-lipsync]
63
+ brings up the deck server plus every bridge this machine can run, under one Ctrl-C
64
+
65
+ A git URL clones the repository into ./<repo> and opens the deck inside it.
66
+ Nothing is ever pushed.
67
+
68
+ --open open the deck in your browser once the server is up
69
+ --port N the deck server [8788]
70
+ --git / --no-git keep the deck in git (snapshots, K commits) / never touch git
71
+ (no repository and no flag: decklight asks whether to create one)
72
+ --agent <name> preferred AI agent for A (default: first detected)
73
+ --no-plugins play without your presenter plugins (decklight library add plugin)
74
+ --remote also listen on the LAN for the phone remote
75
+ --no-tts don't start the voice bridge
76
+ --no-lipsync don't start the lip-sync bridge
77
+
78
+ --no-trust open a deck you did not write: served under a
79
+ Content-Security-Policy, every edit route refuses, no bridge
80
+ (decklight <deck> --no-trust --help for that mode's flags)
81
+ --trust open a deck that runs code of its own without the question
82
+
83
+ The voice and the face are set up once and remembered: decklight setup voice,
84
+ decklight setup face. --tts-engine E picks an engine for one session.
85
+
86
+ decklight <deck> --help --all every flag: cloning, ports, commit cadence,
87
+ agent-written commit subjects, voice, lip-sync`;
88
+
89
+ const USAGE_ALL = `usage: decklight <deck.html | git url> [--no-trust] [--port 8788] [--tts-port 8787] [--lipsync-port 8789]
90
+ [--tts-engine gemini|chirp|piper|elevenlabs] [--project <id>] [--no-tts]
91
+ [--git | --no-git] [--commit-every <s>] [--agent <name>]
92
+ brings up the deck server plus every bridge this machine can run, under one Ctrl-C
93
+
94
+ A git URL clones the repository (in full — its history is the deck's) into
95
+ ./<repo>, finds the deck in it, and opens that; a directory already cloned
96
+ from the same remote is opened as it is. A GitHub link to the deck file
97
+ itself (…/blob/<branch>/<path>) names branch and deck at once; so does
98
+ <url>#<path>. Nothing is ever pushed.
99
+ --branch <ref> the branch or tag to clone
100
+ --into <dir> where to clone (default: ./<repo name>)
101
+
102
+ --port N the deck server (live reload + edit write-back) [8788]
103
+ (taken already? decklight offers to take over that session
104
+ on a TTY, or moves to the next free port otherwise)
105
+ --tts-port N live voice bridge [8787]
106
+ --lipsync-port N lip-sync bridge (visemes + talking head) [8789]
107
+ --open open the deck in your browser once the server is up
108
+ --remote also listen on the LAN for the phone remote: off this machine
109
+ only /deck/remote/* answers, with the per-run token the QR carries
110
+ --host A the address --remote binds [0.0.0.0]
111
+ --no-tts don't start the voice bridge
112
+ --no-lipsync don't start the lip-sync bridge
113
+ --git / --no-git keep the deck in git (snapshot + K commits) / never touch git
114
+ --git-mode M when to commit: agent (one per agent edit, and whenever you
115
+ press K), timer (the old five-minute cadence), off [agent]
116
+ (no repo + no flag: decklight ASKS whether to create one)
117
+ --commit-every N cadence in seconds, timer mode only [300]
118
+ --commit-messages an agent writes EVERY commit subject instead of the generic
119
+ "autosave" — reads each commit's diff and amends the subject
120
+ afterwards — and K drafts one as it opens. Without it, K's
121
+ "write them for me" asks only when you press it
122
+ --no-commit-messages no agent-written subjects at all this session. Either
123
+ way the deck's changes go to the agent installed on this
124
+ machine, which may pass them to its provider
125
+ --agent <name> preferred AI agent for A (default: first detected)
126
+
127
+ --no-trust the same server in no-trust mode: the deck is served from
128
+ its own directory under a Content-Security-Policy header,
129
+ the ingredients label runs first, every edit route refuses,
130
+ and no bridge is started. The way to open a deck you did
131
+ not write; --strict, --audit and --root apply here
132
+ (decklight <deck> --no-trust --help for that mode's flags)
133
+ --trust a deck that runs code of its own is opened in write mode
134
+ without the question. Without a flag, the ingredients
135
+ label runs first: a deck with nothing to account for opens
136
+ in write mode; one with script or executable attributes
137
+ names them, in yellow, and ASKS whether you trust its
138
+ source — yes is remembered against those bytes (so a
139
+ changed script asks again), no opens it without trust; off a
140
+ terminal, without trust
141
+ the server binds 127.0.0.1 unless --remote asks for the LAN
142
+
143
+ --tts-engine E gemini Vertex AI, best delivery, honors a style — no free tier [default]
144
+ chirp Cloud TTS Chirp 3: HD — same voices, ~1s, 1M chars/month free
145
+ piper local, offline, unlimited, no project needed
146
+ elevenlabs your own account's voices, the ones you cloned first
147
+ in the picker — needs $ELEVENLABS_API_KEY
148
+ (nothing configured? decklight asks nothing at startup: the
149
+ banner and the deck's V panel name decklight setup voice)
150
+
151
+ the voice and the face are saved settings, not flags: decklight setup voice
152
+ (--engine, --voice, --project, --model, --location, --lang, --format,
153
+ --stability, --data-dir) and decklight setup face (--portrait, the models,
154
+ --cache-dir, --veo …) write them once, and every deck opened after uses them`;
155
+
156
+ // flags that take a value (so the deck argument can be found past them)
157
+ const VALUE_FLAGS = new Set([
158
+ '--port', '--tts-port', '--lipsync-port', '--tts-engine', '--commit-every', '--agent', '--git-mode',
159
+ '--branch', '--into', '--host',
160
+ ]);
161
+
162
+ /**
163
+ * The voice, lip-sync and Veo flags `decklight <deck>` no longer takes, and
164
+ * where each went (ROADMAP section 1). They were passed straight through to
165
+ * the bridges every run; every one is now saved once (`decklight setup voice
166
+ * --model …`, `decklight setup face --veo …`) or picked in the deck. Refused
167
+ * by name, never ignored: a flag that silently did nothing would be worse.
168
+ */
169
+ export const MOVED_FLAGS = {
170
+ '--project': 'setup voice --project <id> (or $GOOGLE_CLOUD_PROJECT)',
171
+ '--tts-model': 'setup voice --model <model>',
172
+ '--location': 'setup voice --location <region>',
173
+ '--voice': 'setup voice --voice <name> (or V → Live voice in the deck)',
174
+ '--data-dir': 'setup voice --data-dir <dir>',
175
+ '--lang': 'setup voice --lang <code>',
176
+ '--tts-format': 'setup voice --format pcm|mp3',
177
+ '--tts-stability': 'setup voice --stability creative|natural|robust',
178
+ '--rhubarb': 'setup face --rhubarb <bin>',
179
+ '--portrait': 'setup face --portrait <name=photo>',
180
+ '--wav2lip-dir': 'setup face --wav2lip-dir <checkout>',
181
+ '--wav2lip-ckpt': 'setup face --wav2lip-ckpt <checkpoint>',
182
+ '--sadtalker-dir': 'setup face --sadtalker-dir <checkout>',
183
+ '--python': 'setup face --python <python>',
184
+ '--cache-dir': 'setup face --cache-dir <dir>',
185
+ '--veo': 'setup face --veo (billed once per portrait)',
186
+ '--veo-project': 'setup face --veo-project <id>',
187
+ '--veo-model': 'setup face --veo-model <model>',
188
+ '--veo-seconds': 'setup face --veo-seconds 4|6|8',
189
+ '--veo-prompt': 'setup face --veo-prompt "…"',
190
+ '--veo-location': 'setup face --veo-location <region>',
191
+ '--veo-face-y': 'setup face --veo-face-y <fraction>',
192
+ };
193
+
194
+ /** The moved flags present in `args`, as refusal lines; empty when none. Pure. */
195
+ export function movedFlagLines(args = []) {
196
+ return args.filter((a) => MOVED_FLAGS[a]).map((a) => ` ${a} moved: decklight ${MOVED_FLAGS[a]}`);
197
+ }
198
+
199
+ /**
200
+ * Decide what to bring up, WITHOUT starting anything — the whole capability
201
+ * policy in one pure function, so it can be tested without binding a port.
202
+ * `saved` is the machine-level tts config (~/.config/decklight/tts.json,
203
+ * written by the setup wizard) — injected, not read here, so the plan stays
204
+ * pure; precedence is flags > environment > saved config > built-in default.
205
+ * Returns { deck, run: [{name, tag, entry, args, url}], skip: [{name, why}],
206
+ * agents: [names the machine can run] } — `entry` is the script to spawn:
207
+ * the bridges go through the dispatcher, the edit server (no longer a
208
+ * command there) runs its own module.
209
+ */
210
+ export function planServices({
211
+ args = [], env = process.env, hasBin = onPath, saved = null, lipsync = null,
212
+ detect = detectLocalVoice, exists = existsSync,
213
+ } = {}) {
214
+ const { opt } = argReader(args);
215
+ const has = (flag) => args.includes(flag);
216
+ const pass = (flag) => (opt(flag) !== undefined ? [flag, opt(flag)] : []);
217
+
218
+ // first bare token is the deck — past the flags that consume a value, so
219
+ // `author --port 8788 deck.html` doesn't mistake "8788" for the deck
220
+ const deck = firstPositional(args, VALUE_FLAGS);
221
+
222
+ const run = [];
223
+ const skip = [];
224
+
225
+ const editPort = opt('--port', '8788');
226
+ run.push({
227
+ name: 'edit',
228
+ tag: 'deck',
229
+ entry: EDIT,
230
+ args: [deck, '--port', editPort,
231
+ ...(has('--git') ? ['--git'] : []), ...(has('--no-git') ? ['--no-git'] : []),
232
+ ...pass('--commit-every'), ...pass('--agent'), ...pass('--git-mode'),
233
+ // the deck reaches both bridges on the edit server's own origin (#520):
234
+ // `/tts` and `/lipsync/*` are proxied to the ports the bridges below take
235
+ ...pass('--tts-port'), ...pass('--lipsync-port'),
236
+ // BOTH directions travel: the first-run question can answer no, and a no
237
+ // that did not reach the server would be a question asked and ignored.
238
+ ...(has('--commit-messages') ? ['--commit-messages'] : []),
239
+ ...(has('--no-commit-messages') ? ['--no-commit-messages'] : []),
240
+ // the phone remote (NO_TRUST#REMOTE) is the server's, in either mode
241
+ ...(has('--remote') ? ['--remote'] : []), ...pass('--host'),
242
+ // the presenter's chrome loads in write mode too; this turns it off
243
+ ...(has('--no-plugins') ? ['--no-plugins'] : [])],
244
+ url: `http://127.0.0.1:${editPort}/${deck ?? ''}`,
245
+ });
246
+
247
+ // live voice — an engine that would exit for want of a credential should not
248
+ // be started at all: the Google ones need a project, ElevenLabs needs a key,
249
+ // and piper needs neither, only the binary
250
+ const ttsPort = opt('--tts-port', '8787');
251
+ const project = env.GOOGLE_CLOUD_PROJECT ?? saved?.project;
252
+
253
+ // Nothing chosen, nothing saved, no cloud credential: rather than default to
254
+ // an engine that will be skipped for want of a project, ask the machine what
255
+ // it can already say. Every desktop OS ships a synthesizer, and on current
256
+ // ones it is neural — free, offline, and nothing to download. An explicit
257
+ // --tts-engine, a saved engine, or a project all win over this: flags decide,
258
+ // detection only fills a vacuum.
259
+ const chosen = opt('--tts-engine', saved?.engine);
260
+ const native = chosen || project ? null : detect({ lang: saved?.lang });
261
+ // Only a NATIVE voice is claimed automatically. It is the one engine that
262
+ // needs no setup at all — no install, no download, no credential — so using
263
+ // it silently costs the presenter nothing. piper is deliberately NOT picked
264
+ // here even when it is on PATH: it needs a toolchain and a ~120 MB model, and
265
+ // choosing it behind the user's back would skip the first-run wizard that
266
+ // exists to make (and save) exactly that choice.
267
+ const ttsEngine = chosen ?? native?.engine ?? 'gemini';
268
+ const cloudVoice = ttsEngine === 'gemini' || ttsEngine === 'chirp';
269
+ const ttsArgs = () => [
270
+ 'tts', '--port', ttsPort,
271
+ // also when DETECTION chose the engine: without this the bridge would be
272
+ // started with no --engine and fall back to its own default, so a machine
273
+ // picked for its system voice would try to reach Vertex AI instead
274
+ ...(has('--tts-engine') || saved?.engine || ttsEngine !== 'gemini' ? ['--engine', ttsEngine] : []),
275
+ ...(cloudVoice ? ['--project', project] : []),
276
+ // every other setting the bridge reads from the saved config itself
277
+ ];
278
+ // The SAME readiness check the bridge runs when the deck asks what it may
279
+ // switch to (SPEC NARRATION). Sharing the decision is the point: a picker
280
+ // that offered an engine `open` would have refused to start is a picker
281
+ // that lies. Only the phrasing differs — here there is a terminal, a
282
+ // presenter still setting things up, and room for the whole answer.
283
+ const ttsVoice = saved?.voice ?? PIPER_DEFAULT_VOICE;
284
+ const ttsData = saved?.dataDir ?? piperModelDir(env);
285
+ const status = engineStatus(ttsEngine, {
286
+ env, project, voice: ttsVoice, dataDir: ttsData, lang: saved?.lang,
287
+ // every probe threaded through, `detect` included: these are the injection
288
+ // points that let planServices be tested on any machine, and a readiness
289
+ // check reaching for the REAL PATH or the REAL synthesizer would decide a
290
+ // test's answer from the host it happened to run on
291
+ hasBin, exists, detect,
292
+ });
293
+ if (has('--no-tts')) {
294
+ skip.push({ name: 'voice', why: 'disabled with --no-tts' });
295
+ } else if (status.reason === 'unknown') {
296
+ skip.push({ name: 'voice', why: `unknown --tts-engine '${ttsEngine}' — use ${TTS_ENGINES.join(', ')}` });
297
+ } else if (status.reason === 'no-binary') {
298
+ skip.push({ name: 'voice', why: 'piper not on PATH — install it (uv tool install piper-tts)' });
299
+ } else if (status.reason === 'no-model') {
300
+ // piper is installed but has no voice to speak with. The bridge would come
301
+ // up looking healthy and fail on the first sentence — a keypress into
302
+ // silence — so it is caught here, where the fix can be offered instead.
303
+ const download = piperDownloadCmd(ttsVoice, ttsData, { hasBin: (b) => hasBin(b, env) });
304
+ skip.push({
305
+ name: 'voice',
306
+ why: `the piper voice ${ttsVoice} is not in ${ttsData} (~120 MB, one time)`
307
+ + ` — decklight setup voice fetches it, or: ${piperDownloadLine(download)}`,
308
+ download, // the command setup voice runs; nothing is ever pulled silently
309
+ });
310
+ } else if (status.reason === 'no-key') {
311
+ // The key never lands in the saved config, so the environment is the only
312
+ // place it can come from — say that, and where to make one.
313
+ skip.push({ name: 'voice', why: `elevenlabs needs $${ELEVENLABS_KEY_ENV} — create a key at https://elevenlabs.io/app/settings/api-keys and export it` });
314
+ } else if (status.reason === 'no-project') {
315
+ skip.push({
316
+ name: 'voice',
317
+ why: `${ttsEngine} needs a GCP project — decklight setup voice --project <id>, or set GOOGLE_CLOUD_PROJECT`
318
+ + (native?.why ? `\n this machine has no system voice either: ${native.why}` : '')
319
+ + (native?.suggest ? `\n ${native.suggest}` : ' — or use --tts-engine piper'),
320
+ });
321
+ } else if (status.reason === 'bad-project') {
322
+ // caught here rather than at the first narration: the bridge would start,
323
+ // look healthy, and only fail on a keypress — with a 403 naming a project
324
+ // nobody typed
325
+ skip.push({ name: 'voice', why: `not a GCP project id: ${JSON.stringify(project)} — stray punctuation from a copy-paste?` });
326
+ } else if (status.reason === 'no-native-voice') {
327
+ // New with the shared check: `--tts-engine say` on a machine whose OS has
328
+ // no synthesizer used to start a bridge that failed on the first keypress.
329
+ skip.push({ name: 'voice', why: `${ttsEngine}: ${status.why ?? 'no system voice on this machine'}` });
330
+ } else {
331
+ run.push({ name: 'tts', tag: 'voice', entry: CLI, args: ttsArgs(), url: `http://127.0.0.1:${ttsPort}` });
332
+ }
333
+
334
+ // lip-sync — starts degraded (it probes its own engines), so only bother when
335
+ // something it can actually use is present
336
+ const lipPort = opt('--lipsync-port', '8789');
337
+ // A talking head set up and saved once (`decklight setup face …`,
338
+ // lipsync.json) counts as configured: `open` starts the bridge for it with
339
+ // no flags, rhubarb or not. The bridge reads every setting (portraits,
340
+ // models, cache, Veo) from that same file.
341
+ const savedLips = lipsync;
342
+ const rhubarb = savedLips?.rhubarb ?? 'rhubarb';
343
+ const savedVideo = !!(savedLips?.wav2lipDir || savedLips?.sadtalkerDir);
344
+ const configured = savedVideo || !!savedLips?.rhubarb;
345
+ if (has('--no-lipsync')) {
346
+ skip.push({ name: 'lip-sync', why: 'disabled with --no-lipsync' });
347
+ } else if (!configured && !hasBin(rhubarb, env)) {
348
+ skip.push({ name: 'lip-sync', why: `rhubarb not on PATH, and no talking head set up — ${SETUP_HINT}` });
349
+ } else {
350
+ run.push({
351
+ name: 'lipsync',
352
+ tag: 'lips',
353
+ entry: CLI,
354
+ // every setting comes from lipsync.json; Veo, the one that spends
355
+ // money, only when `setup face --veo` asked for it there
356
+ args: ['lipsync', '--port', lipPort],
357
+ url: `http://127.0.0.1:${lipPort}`,
358
+ });
359
+ }
360
+
361
+ return { deck, run, skip, agents: detectAgents({ env, hasBin }).map((a) => a.name) };
362
+ }
363
+
364
+ /**
365
+ * Should author OFFER the tts setup wizard instead of just printing the skip
366
+ * line? Only when the skip is the fixable kind — no engine configured, no
367
+ * project to run the default cloud engine with — never when a flag chose the
368
+ * outcome (--no-tts, an unknown engine, a malformed --project: the user's
369
+ * hand is on the wheel, and the skip line already names the fix).
370
+ */
371
+ /** The voice is skipped only for want of a model, and we know how to fetch it. */
372
+ /** The banner's agents row when none is installed: what A would run, and where the list is. */
373
+ export const noAgentRow = (roster = AGENTS) =>
374
+ `none on PATH (${roster.slice(0, 3).map((a) => a.name).join(', ')}, … ${roster.length} known) · decklight doctor says how to install one`;
375
+
376
+ export const voiceModelOffer = (plan) => {
377
+ const s = plan.skip.find((x) => x.name === 'voice');
378
+ return s?.download ? s : null;
379
+ };
380
+
381
+ export const voiceSetupOffer = (plan) => {
382
+ const s = plan.skip.find((x) => x.name === 'voice');
383
+ return s && /needs a GCP project/.test(s.why) ? s : null;
384
+ };
385
+
386
+ // inGitRepo lives in git.mjs now; re-exported so importers (and the tests) keep
387
+ // finding it where dev grew it.
388
+ export { inGitRepo } from './git.mjs';
389
+ import { inGitRepo } from './git.mjs';
390
+
391
+ const COLORS = { deck: '\x1b[36m', voice: '\x1b[35m', lips: '\x1b[33m' };
392
+ const DIM = '\x1b[2m';
393
+ const RESET = '\x1b[0m';
394
+
395
+ export async function openMain(args) {
396
+ // --no-trust: the same command, the same server, in no-trust mode
397
+ // (PRESENTING). A .decklight container is without trust by nature — there is
398
+ // nothing in it to edit in place — so naming one is the same as the flag.
399
+ // It runs in THIS process: no-trust mode starts no bridge (a deck you were
400
+ // handed does not get a voice engine beside it), so there is nothing for a
401
+ // supervising parent to own, and the one thing the mode prints — the
402
+ // ingredients label — belongs on a bare terminal, not under a banner.
403
+ const named = args.find((a) => !a.startsWith('-') && /\.decklight$/i.test(a));
404
+ const noTrust = args.includes('--no-trust') || Boolean(named);
405
+ if (noTrust && args.includes('--help')) return (await import('./edit.mjs')).editMain(args.includes('--no-trust') ? args : [...args, '--no-trust']);
406
+ if (args.includes('--help') || args.includes('-h')) { console.log(args.includes('--all') ? USAGE_ALL : USAGE); return; }
407
+ // a voice, lip-sync or Veo flag from before they were saved settings: say where it went
408
+ const moved = movedFlagLines(args);
409
+ if (moved.length) {
410
+ console.error(`decklight <deck> no longer takes these; set them once and every deck uses them:\n${moved.join('\n')}`);
411
+ return 1;
412
+ }
413
+
414
+ let plan = planServices({ args, saved: loadTtsConfig(), lipsync: loadLipsyncConfig() });
415
+ let deck = plan.deck;
416
+ if (!deck) {
417
+ console.error('decklight needs a deck: decklight <deck.html>\n');
418
+ console.error(USAGE);
419
+ process.exitCode = 1;
420
+ return;
421
+ }
422
+ // A git URL: clone it (or open the clone already here), find the deck in
423
+ // it, and carry on as `decklight <that path>` — in a repository, so
424
+ // `--git` is a fact rather than a question.
425
+ const { opt } = argReader(args);
426
+ let got = null;
427
+ try { got = deckFromUrl(deck, { branch: opt('--branch'), into: opt('--into') }); } catch (e) {
428
+ console.error(`decklight: ${e.message}`);
429
+ process.exitCode = 1;
430
+ return;
431
+ }
432
+ if (got) {
433
+ // The clone becomes the working directory. The edit server keeps its
434
+ // git in `process.cwd()` — so does every bridge it starts — and without
435
+ // this, `--git` created a fresh repository in the directory `open` was
436
+ // run from, with the clone nested inside it.
437
+ process.chdir(got.dir);
438
+ const local = relative(got.dir, got.deckPath);
439
+ args = args.map((a) => (a === deck ? local : a)).filter((a, i, all) => !(a === '--branch' || a === '--into' || all[i - 1] === '--branch' || all[i - 1] === '--into'));
440
+ // no-trust mode never commits the deck; the clone's git is what H reads
441
+ if (!noTrust && !args.includes('--no-git') && !args.includes('--git')) args.push('--git');
442
+ deck = local;
443
+ plan = planServices({ args, saved: loadTtsConfig(), lipsync: loadLipsyncConfig() });
444
+ }
445
+ // no-trust mode names a missing deck itself, the same way for a file, a
446
+ // container and a --check
447
+ if (!noTrust && !existsSync(deck)) {
448
+ console.error(`decklight: no such deck: ${deck}`);
449
+ process.exitCode = 1;
450
+ return;
451
+ }
452
+ // ── script in the deck: trust its source, or not (PRESENTING) ───────
453
+ // The ingredients label runs first, as it always did under --no-trust, and
454
+ // decides nothing: a deck with nothing to account for opens in write mode
455
+ // (that is your own deck, and any deck that is data); one that runs code of
456
+ // its own names it and asks. The answer is yours, because the label cannot
457
+ // tell your script from a stranger's — only you know where the file came
458
+ // from. Yes is remembered against the bytes of that code (cli/trust.mjs), so
459
+ // the question is asked once per script, not once per start; no is
460
+ // without trust, strict. Off a terminal nobody can answer, and no trust is the
461
+ // answer that costs nothing: --trust says yes on the command line.
462
+ let untrusted = false;
463
+ if (!noTrust) {
464
+ // the real path, so a deck under a symlinked folder (/var → /private/var on a Mac) is one deck
465
+ let deckPath = resolvePath(deck);
466
+ try { deckPath = realpathSync(deckPath); } catch { /* resolved is as good as it gets */ }
467
+ const html = readFileSync(deckPath, 'utf8');
468
+ const report = auditDeck(html);
469
+ const findings = report.counts.unaccounted + report.counts.handlers;
470
+ if (findings) {
471
+ const hash = scriptHash(html, report);
472
+ const trustFlag = args.includes('--trust');
473
+ if (isTrusted(deckPath, hash)) {
474
+ console.log(` script: ${findings} finding${findings === 1 ? '' : 's'} in this deck, trusted before — write mode`);
475
+ } else if (trustFlag) {
476
+ remember(deckPath, hash);
477
+ console.log(` script: ${findings} finding${findings === 1 ? '' : 's'} in this deck, trusted (--trust) — write mode, remembered until the script changes`);
478
+ } else {
479
+ const Y = process.stdout.isTTY ? '\x1b[33m' : '', R = process.stdout.isTTY ? '\x1b[0m' : '';
480
+ console.log(`${Y} this deck runs code that is not the runtime:${R}`);
481
+ for (const line of formatLabel(report, { indent: '' })) {
482
+ // the findings, and the counts that are not zero — the zero lines are the label's, not the question's
483
+ if (/^\s+line\s+\d+/.test(line) || /^\s*[1-9]\d* (unaccounted|inline|executable)/.test(line)) console.log(`${Y} ${line.trim().replace(' — this file runs code that is not the runtime:', ':')}${R}`);
484
+ }
485
+ if (process.stdin.isTTY && process.stdout.isTTY) {
486
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
487
+ let answer = '';
488
+ try { answer = await rl.question(`${Y} do you trust where this deck came from? yes opens it in write mode, and is remembered until its script changes; no opens it without trust [y/N] ${R}`); }
489
+ finally { rl.close(); }
490
+ if (/^y/i.test(answer.trim())) {
491
+ remember(deckPath, hash);
492
+ console.log(' trusted — write mode; decklight trust forget <deck> takes it back');
493
+ } else {
494
+ untrusted = true;
495
+ console.log(' not trusted — without trust, with what could not be accounted for stripped (--trust next time says otherwise)');
496
+ }
497
+ } else {
498
+ untrusted = true;
499
+ console.log(' no terminal to ask on — opening without trust; --trust opens it in write mode');
500
+ }
501
+ }
502
+ }
503
+ }
504
+ if (noTrust || untrusted) {
505
+ if (named && !args.includes('--no-trust')) {
506
+ console.log(' a .decklight container is opened without trust by nature: nothing in it can be edited in place');
507
+ }
508
+ if (!args.includes('--no-trust')) args = [...args, '--no-trust'];
509
+ // The server, here. A number back is an exit code (--check, a refusal);
510
+ // the server object means it is listening and Ctrl-C is the way out.
511
+ const out = await (await import('./edit.mjs')).editMain(args);
512
+ return typeof out === 'number' ? out : 0;
513
+ }
514
+
515
+ // A skill older than this install, on this machine: offer to bring it up
516
+ // to date, here, where the banner would otherwise only name it. Write mode
517
+ // only, like the banner's row, and only on a terminal.
518
+ if (process.stdin.isTTY && process.stdout.isTTY) await offerSkillRefresh();
519
+
520
+ // No repo, no flag: offer one. A repo is where the regular autocommits go —
521
+ // the durable record behind the player's fast undo/redo loop. Only a TTY
522
+ // can be asked; headless runs stay git-less until --git says otherwise.
523
+ if (!args.includes('--git') && !args.includes('--no-git') && !inGitRepo(process.cwd())) {
524
+ if (process.stdin.isTTY && process.stdout.isTTY) {
525
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
526
+ const answer = await rl.question(' no git repository here — create one so every version of the deck is kept? [Y/n] ');
527
+ const yes = !/^n/i.test(answer.trim());
528
+ args = [...args, yes ? '--git' : '--no-git'];
529
+ // No follow-up about WHEN to commit: one per agent edit, and on K, is
530
+ // already the default (resolveGitMode), so the question it used to ask
531
+ // could only offer what was on. Init says so in a line; --git-mode
532
+ // timer is the way to the plain cadence.
533
+ rl.close();
534
+ plan = planServices({ args, saved: loadTtsConfig(), lipsync: loadLipsyncConfig() });
535
+ } else {
536
+ console.log(' git: no repository here — pass --git to create one and keep every version of the deck');
537
+ }
538
+ }
539
+ // The voice asks nothing at startup (ROADMAP section 1). A piper model to
540
+ // download or an engine to configure is named in the banner's skip row,
541
+ // with the one command that does it (`decklight setup voice`), and the
542
+ // deck's V panel says the same when the voice is not there. It used to ask
543
+ // two questions here, between the trust question and the deck, on every
544
+ // open of a machine with no voice set up.
545
+ // The edit port might already be held — often an earlier decklight session
546
+ // left running. Resolved here, with author's OWN stdin, because the edit
547
+ // child below is spawned with its stdin piped (not a terminal) and could
548
+ // never ask on its own.
549
+ const editSvc = plan.run.find((s) => s.name === 'edit');
550
+ let portRow = null; // the edit port was taken: a banner row says by whom and where this one went
551
+ if (editSvc) {
552
+ const portIdx = editSvc.args.indexOf('--port');
553
+ const editPort = Number(editSvc.args[portIdx + 1]);
554
+ if (await isPortOpen(editPort)) {
555
+ const askTty = process.stdin.isTTY && process.stdout.isTTY;
556
+ let rl;
557
+ const ask = askTty ? (q) => (rl ??= createInterface({ input: process.stdin, output: process.stdout })).question(q) : undefined;
558
+ // How it ended is a banner row (`! port 8788 has another decklight
559
+ // editing "deck.html" — this one is on 8790`), in the banner's own
560
+ // shape and place, rather than two loose lines above it. The question
561
+ // itself still prints live, since it is asked live.
562
+ const freshPort = await resolvePortConflict(editPort, {
563
+ ask, log: console.log,
564
+ outcome: (o) => { portRow = { text: describePortOutcome(o), mark: 'warn' }; },
565
+ });
566
+ rl?.close();
567
+ editSvc.args[portIdx + 1] = String(freshPort);
568
+ editSvc.url = `http://127.0.0.1:${freshPort}/${deck}`;
569
+ // Kept the port: the session that held it was taken over. Its edit
570
+ // server is gone, but its bridges are still on their way out (its
571
+ // `shutdown` gives them up to 500 ms), so wait for their ports before
572
+ // deciding who holds them, or this session's own bridge moves off a
573
+ // port that is about to be free and blames "another program" (#810).
574
+ if (freshPort === editPort) await waitForBridgePorts(plan);
575
+ }
576
+ }
577
+ // A bridge moved off a stranger's port: a row on the bridge's own line
578
+ // (joined with what the bridge then reports from the port it took).
579
+ const movedRows = (await moveBridgesOffStrangers(plan)).map((line) => {
580
+ const m = /^(voice|lip-sync): (.*)$/.exec(line);
581
+ return m ? { key: m[1] === 'voice' ? 'voice' : 'lips', text: m[2] } : { key: 'port', text: line };
582
+ });
583
+ const { run, skip, agents } = plan;
584
+
585
+ const tty = process.stdout.isTTY;
586
+ const paint = (tag) => (tty ? `${COLORS[tag] ?? ''}${tag.padEnd(5)}${RESET}` : `${tag.padEnd(5)}`);
587
+ const note = (s) => (tty ? `${DIM}${s}${RESET}` : s);
588
+
589
+ const children = new Map();
590
+ let shuttingDown = false;
591
+
592
+ // ── the startup banner ────────────────────────────────────────────────────
593
+ // Children report a row and `open` prints all of them at once, so the URL is
594
+ // last no matter which server woke up first (cli/banner.mjs says why).
595
+ //
596
+ // WHEN to print is the only hard part. Waiting for every service is wrong —
597
+ // one that never comes up would hold the URL hostage — and printing on the
598
+ // first fact is wrong too, since the rest arrive milliseconds later. So:
599
+ // settle after a short quiet gap, with a hard cap in case a child is slow or
600
+ // silent. The review check is the late one on purpose (edit.mjs fires it
601
+ // detached, after listening), and GRACE is sized for it; if it misses, it
602
+ // prints under the banner as its own row rather than delaying the URL.
603
+ // The cap is generous because it is the LAST resort, not the schedule: in the
604
+ // normal case every service reports and the banner goes out on the grace
605
+ // timer, well inside a second. The cap only matters when a child is silent,
606
+ // and then waiting is the right thing anyway — that row is missing from the
607
+ // banner either way, and a fast wrong banner is not better than a slow right
608
+ // one by four seconds.
609
+ const BANNER_CAP_MS = 5000;
610
+ const BANNER_GRACE_MS = 350;
611
+ const banner = {
612
+ done: false, held: [], rows: new Map(),
613
+ url: editSvc?.url ?? null, keys: null, timer: null, start: Date.now(),
614
+ // Who still owes us a row. The voice bridge enumerates the machine's
615
+ // voices before it can say what it is, which takes longer than any grace
616
+ // window worth having — so the banner waits on NAMES, not on a clock.
617
+ waiting: new Set(run.map((svc) => svc.tag)),
618
+ };
619
+ if (portRow) banner.rows.set('port', portRow);
620
+ for (const r of movedRows) banner.rows.set(r.key, { text: r.text, mark: 'warn' });
621
+
622
+ /**
623
+ * A line from `open` itself. Held while the banner is still being assembled,
624
+ * so nothing — an error included — can land above the URL; printed straight
625
+ * away once it is out.
626
+ */
627
+ function say(line) {
628
+ // Never a caller's choice. It was one, and the caller that passed its own
629
+ // answer got it wrong in the one case that mattered: the LAST service to
630
+ // exit computed "nobody is waiting" and printed straight away, while the
631
+ // flush timer it had just armed was still mid-flight — so its line landed
632
+ // above the banner it was supposed to sit under.
633
+ if (banner.done) process.stderr.write(`${line}\n`);
634
+ else banner.held.push(line);
635
+ }
636
+
637
+ function flushBanner() {
638
+ if (banner.done) return;
639
+ banner.done = true;
640
+ clearTimeout(banner.timer);
641
+ // Held output goes FIRST, and the banner closes. Everything in here is a
642
+ // child explaining itself — a bridge saying why it stood aside, a service
643
+ // saying why it exited — and an explanation belongs before the summary it
644
+ // explains. It also keeps the promise that matters: whatever was said on
645
+ // the way up, the deck's url is still the last line on screen.
646
+ for (const l of banner.held) process.stdout.write(`${l}\n`);
647
+ banner.held.length = 0;
648
+ if (banner.url) {
649
+ const rows = [...banner.rows].map(([key, row]) => ({ key, ...row }));
650
+ // the deck's name on a line of its own is for debugging: the url says it
651
+ const header = process.env.DECKLIGHT_DEBUG ? deck : undefined;
652
+ for (const l of renderBanner({ deck: header, url: banner.url, keys: banner.keys, rows, color: tty })) {
653
+ process.stdout.write(`${l}\n`);
654
+ }
655
+ // after the banner, so the URL is on screen before the browser takes the
656
+ // focus — and a machine that cannot launch one gets its dim line here
657
+ if (args.includes('--open')) openUrl(banner.url, { what: 'the deck' }).catch(() => {});
658
+ }
659
+ }
660
+
661
+ /**
662
+ * A service has said its piece. Print once nobody is still owed, and keep a
663
+ * short grace after that for the genuinely late — the review check fires
664
+ * detached, after the deck server is already listening.
665
+ */
666
+ function settle(tag) {
667
+ banner.waiting.delete(tag);
668
+ const delay = nextFlushDelay({
669
+ waiting: banner.waiting.size,
670
+ elapsed: Date.now() - banner.start,
671
+ cap: BANNER_CAP_MS,
672
+ grace: BANNER_GRACE_MS,
673
+ });
674
+ if (delay === null) return;
675
+ clearTimeout(banner.timer);
676
+ banner.timer = setTimeout(flushBanner, delay);
677
+ banner.timer.unref?.();
678
+ }
679
+
680
+ function collect(tag, fact) {
681
+ if (fact.url) banner.url = fact.url;
682
+ if (fact.keys) banner.keys = fact.keys;
683
+ if (!fact.key || !fact.text) { if (fact.url) settle(tag); return; }
684
+ if (banner.done) {
685
+ // Arrived after the banner went out — still worth saying, in the shape
686
+ // it would have had, rather than swallowed for being late.
687
+ process.stdout.write(`${bannerRow(fact, { color: tty })}\n`);
688
+ return;
689
+ }
690
+ // Two facts can share a key — `git` is both "snapshots on decklight/wip" and
691
+ // "subjects by claude", reported by different parts of the child.
692
+ // They join into one row rather than the later one erasing the earlier.
693
+ // A warning in either makes the joined row a warning.
694
+ const had = banner.rows.get(fact.key);
695
+ const text = had && had.text !== fact.text ? `${had.text} · ${fact.text}` : fact.text;
696
+ const mark = had?.mark === 'warn' || fact.mark === 'warn' ? 'warn' : (fact.mark ?? had?.mark);
697
+ banner.rows.set(fact.key, { text, mark });
698
+ settle(tag);
699
+ }
700
+ // Even if no child ever reports, the URL must still appear.
701
+ banner.timer = setTimeout(flushBanner, BANNER_CAP_MS);
702
+ banner.timer.unref?.();
703
+
704
+ // Children write their own startup/progress lines; prefix each so three
705
+ // servers in one terminal stay readable.
706
+ const pipe = (stream, tag, out) => {
707
+ let buf = '';
708
+ stream.setEncoding('utf8');
709
+ stream.on('data', (chunk) => {
710
+ buf += chunk;
711
+ const lines = buf.split('\n');
712
+ buf = lines.pop() ?? '';
713
+ for (const line of lines) {
714
+ // A startup FACT is for the banner, never for the terminal — it is the
715
+ // child saying "here is my row", not "here is a line to show someone".
716
+ const fact = parseReady(line);
717
+ if (fact) { collect(tag, fact); continue; }
718
+ // Anything else is ordinary output. Before the banner it is held back
719
+ // so nothing lands above the URL; after, it streams as it always did.
720
+ if (!banner.done) banner.held.push(`${paint(tag)} ${line}`);
721
+ else out.write(`${paint(tag)} ${line}\n`);
722
+ }
723
+ });
724
+ };
725
+
726
+ for (const svc of run) {
727
+ // stdin is a pipe `open` never writes to — it is the leash (see supervise.mjs).
728
+ // Holding it open is what tells the child we are still here; losing it is
729
+ // how the child finds out we are not, even when we were SIGKILLed and
730
+ // never reached shutdown() below.
731
+ const child = spawn(process.execPath, [svc.entry, ...svc.args], {
732
+ stdio: ['pipe', 'pipe', 'pipe'],
733
+ // DECKLIGHT_BANNER is how a child knows its startup lines belong to
734
+ // somebody else's banner. Unset — `decklight edit`, `decklight tts` run
735
+ // straight — and it prints exactly what it always printed.
736
+ env: { ...leashEnv(), DECKLIGHT_BANNER: '1' },
737
+ });
738
+ children.set(svc.name, child);
739
+ pipe(child.stdout, svc.tag, process.stdout);
740
+ pipe(child.stderr, svc.tag, process.stderr);
741
+
742
+ child.on('exit', (code) => {
743
+ children.delete(svc.name);
744
+ if (shuttingDown) return;
745
+ // It owes no row now — a dead process is never going to report one, and
746
+ // the banner must not sit on the URL waiting for it. This is the common
747
+ // case, not a pathological one: a voice bridge that stands aside because
748
+ // another already serves its port exits 0, seconds into startup.
749
+ if (svc.name === 'edit') {
750
+ // the deck server is the one service `open` cannot run without
751
+ say(`${paint(svc.tag)} exited (${code}) — stopping decklight`);
752
+ flushBanner();
753
+ shutdown(code ?? 1);
754
+ } else {
755
+ // A bridge that stood aside because its port already has one exits 0
756
+ // on purpose, and its row says so (✓ voice the say voice bridge is
757
+ // already on :8787 — using it): nothing to add. Anything else is a
758
+ // red row in the banner's own shape, not a loose line above it.
759
+ if (!(code === 0 && banner.rows.has(svc.tag))) {
760
+ const row = { text: `exited (${code}) — carrying on without it; the deck degrades on its own`, mark: 'fail' };
761
+ if (banner.done) process.stderr.write(`${bannerRow({ key: svc.tag, ...row }, { color: tty })}\n`);
762
+ else banner.rows.set(svc.tag, row);
763
+ }
764
+ settle(svc.tag); // settle() does the delete and the "is anyone left" itself
765
+ }
766
+ });
767
+ }
768
+
769
+ // author's own facts join the children's rather than printing above them.
770
+ // `Ctrl-C stops everything` is gone: the banner's key line already says it,
771
+ // and saying it twice was most of why this block read as a wall.
772
+ if (skip.length) banner.rows.set('skipped', { text: skip.map((s) => `${s.name} — ${s.why}`).join(' · ') });
773
+ // Only when there are none — otherwise the edit child names them, and its
774
+ // row (which knows which is preferred and which is installed) wins.
775
+ // The roster, not three names typed here: the row used to name claude, codex
776
+ // and bob after the roster had grown to ten.
777
+ if (!agents.length) banner.rows.set('agents', { text: noAgentRow() });
778
+
779
+ function shutdown(code = 0) {
780
+ if (shuttingDown) return;
781
+ shuttingDown = true;
782
+ for (const child of children.values()) child.kill('SIGTERM');
783
+ // give them a beat to close their listeners, then go
784
+ setTimeout(() => {
785
+ for (const child of children.values()) child.kill('SIGKILL');
786
+ process.exit(code);
787
+ }, 500).unref();
788
+ }
789
+
790
+ process.on('SIGINT', () => shutdown(0));
791
+ process.on('SIGTERM', () => shutdown(0));
792
+ }
793
+
794
+ if (isMain(import.meta.url)) {
795
+ // openMain sets process.exitCode itself; only a throw runMain caught lands here
796
+ if (await runMain('open', () => openMain(process.argv.slice(2))) === 1) process.exitCode = 1;
797
+ }
798
+
799
+ /**
800
+ * A bridge's port held by something that is NOT a decklight bridge — another
801
+ * project's dev server on 8787 is the usual case. Alone, a bridge may not move
802
+ * (port-conflict.mjs: a file:// deck assumes its literal port). Under `open` it
803
+ * may, and should: the deck is served by author and reaches the bridges on ITS
804
+ * origin (/tts, /lipsync — #520), so the bridge takes the next free port that
805
+ * no other service of this run will use, and the edit server is told where to
806
+ * forward. A decklight bridge already on its port is left alone — the bridge
807
+ * reuses it itself. Mutates `plan`; returns one line per move, to print.
808
+ */
809
+ /**
810
+ * The skill, offered up to date at startup (PRESENTING).
811
+ *
812
+ * The banner names a project skill older than this install and says to run
813
+ * `decklight skills`; an agent reading it reads an old contract. A row that
814
+ * only names the fix is a fix nobody runs, and the moment you are already
815
+ * at the terminal is the moment to make it one key: the stale files are
816
+ * listed, project and global alike (`staleSkills`), and ⏎ refreshes them
817
+ * with the same writers as the command. **No is remembered for this
818
+ * version** (`skill-prompt-declined` in the config home): the question
819
+ * comes back when decklight does, never at the next start.
820
+ *
821
+ * `ask` answers the question (a terminal by default); `log` prints. Nothing
822
+ * is asked, and nothing printed, when every skill is current or none is
823
+ * installed.
824
+ */
825
+ export async function offerSkillRefresh({
826
+ dir = process.cwd(), env = process.env,
827
+ ask = null, log = console.log,
828
+ } = {}) {
829
+ const stale = staleSkills({ dir, env });
830
+ if (!stale.length) return { stale, refreshed: false };
831
+ const declinedAt = resolvePath(configHome(env), 'skill-prompt-declined');
832
+ let declined = '';
833
+ try { declined = readFileSync(declinedAt, 'utf8').trim(); } catch { /* never declined */ }
834
+ if (declined === PKG.version) return { stale, refreshed: false, declined: true };
835
+ const named = stale.map((s) => `${displayPath(s.file)} ${s.version ? `v${s.version}` : 'before 0.9.0'}`).join(', ');
836
+ log(` skill: ${named} — older than this install (${PKG.version}): an agent reads an old contract`);
837
+ let answer = '';
838
+ if (ask) answer = await ask(' update it now? [Y/n] ');
839
+ else {
840
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
841
+ try { answer = await rl.question(' update it now? [Y/n] '); } finally { rl.close(); }
842
+ }
843
+ if (/^n/i.test(String(answer).trim())) {
844
+ try {
845
+ mkdirSync(configHome(env), { recursive: true });
846
+ writeFileSync(declinedAt, PKG.version + '\n');
847
+ } catch { /* not remembered: asked again next start */ }
848
+ log(` kept as it is — ${selfCommand()} skills refreshes it; not asked again for ${PKG.version}`);
849
+ return { stale, refreshed: false };
850
+ }
851
+ const written = refreshSkills(stale, { dir, env });
852
+ log(` installed the Decklight skill (v${PKG.version})`);
853
+ for (const w of written) log(` ${w}`);
854
+ return { stale, refreshed: true, written };
855
+ }
856
+
857
+ const nap = (ms) => new Promise((r) => setTimeout(r, ms));
858
+
859
+ /**
860
+ * After a takeover, wait for the bridge ports this run is about to use to
861
+ * close: the killed session's bridges sit on the same default ports and are
862
+ * still exiting when its edit port frees up. Bounded (about 3 s in all) and
863
+ * silent: a port still open at the end is left to `moveBridgesOffStrangers`,
864
+ * which says who holds it. A holder `lsof` names as something other than node
865
+ * is a real stranger, not a bridge on its way out, so the wait stops there.
866
+ * Returns the ports still open.
867
+ */
868
+ export async function waitForBridgePorts(plan, {
869
+ isOpen = isPortOpen, stranger = identifyStranger, sleep = nap, timeoutMs = 3000, stepMs = 100,
870
+ } = {}) {
871
+ const ports = plan.run
872
+ .filter((s) => (s.name === 'tts' || s.name === 'lipsync') && s.args.includes('--port'))
873
+ .map((s) => Number(s.args[s.args.indexOf('--port') + 1]));
874
+ const open = new Set();
875
+ for (const port of ports) if (await isOpen(port)) open.add(port);
876
+ const waiting = new Set(open); // open, and possibly a bridge on its way out
877
+ for (let waited = 0; waiting.size && waited < timeoutMs; waited += stepMs) {
878
+ for (const port of waiting) {
879
+ const who = stranger(port);
880
+ if (who && !/^node/i.test(who.command)) waiting.delete(port);
881
+ }
882
+ if (!waiting.size) break;
883
+ await sleep(stepMs);
884
+ for (const port of [...waiting]) if (!(await isOpen(port))) { waiting.delete(port); open.delete(port); }
885
+ }
886
+ return ports.filter((p) => open.has(p));
887
+ }
888
+
889
+ export async function moveBridgesOffStrangers(plan, {
890
+ isOpen = isPortOpen, isBridge = identifyBridge, bindable = canBind, stranger = identifyStranger,
891
+ sleep = nap, reprobes = 5, reprobeMs = 100,
892
+ } = {}) {
893
+ const lines = [];
894
+ const editSvc = plan.run.find((s) => s.name === 'edit');
895
+ if (!editSvc) return lines;
896
+ const portOf = (svc) => Number(svc.args[svc.args.indexOf('--port') + 1]);
897
+ // every port this run will listen on — a moved bridge must not land on the
898
+ // next one's (8787 held → not 8788, the edit server's, nor 8789, lip-sync's)
899
+ const spoken = new Set(plan.run.filter((s) => s.args.includes('--port')).map(portOf));
900
+ const freeFrom = async (port) => {
901
+ for (let p = port; p < port + 64 && p <= 65535; p++) if (!spoken.has(p) && await bindable(p)) return p;
902
+ return null;
903
+ };
904
+ for (const [name, flag] of [['tts', '--tts-port'], ['lipsync', '--lipsync-port']]) {
905
+ const svc = plan.run.find((s) => s.name === name);
906
+ if (!svc) continue;
907
+ const at = svc.args.indexOf('--port');
908
+ const port = Number(svc.args[at + 1]);
909
+ if (!(await isOpen(port))) continue;
910
+ // ours only if it is the SAME kind: a voice bridge that moved to 8789 is
911
+ // not the lip-sync bridge, and "reusing" it would send /lipsync to /tts
912
+ let there = await isBridge(port);
913
+ let who = there ? null : stranger(port);
914
+ // Open, yet nobody answers and lsof names no listener: a bridge exiting,
915
+ // or a socket closing. Ask again for a moment before calling it a
916
+ // stranger's (#810).
917
+ let closed = false;
918
+ for (let i = 0; !there && !who && i < reprobes; i++) {
919
+ await sleep(reprobeMs);
920
+ if (!(await isOpen(port))) { closed = true; break; }
921
+ there = await isBridge(port);
922
+ who = there ? null : stranger(port);
923
+ }
924
+ if (closed) continue;
925
+ const sameKind = there && (name === 'tts' ? typeof there.engine === 'string' : typeof there.engines === 'object');
926
+ if (sameKind) continue;
927
+ const fresh = await freeFrom(port + 1);
928
+ if (!fresh) continue; // nothing free nearby: the bridge refuses with its own message, as before
929
+ spoken.add(fresh);
930
+ svc.args[at + 1] = String(fresh);
931
+ svc.url = `http://127.0.0.1:${fresh}`;
932
+ const e = editSvc.args.indexOf(flag);
933
+ if (e >= 0) editSvc.args[e + 1] = String(fresh); else editSvc.args.push(flag, String(fresh));
934
+ const label = name === 'tts' ? 'voice' : 'lip-sync';
935
+ const tail = `so the bridge takes ${fresh}; the deck reaches it through this server`;
936
+ // "not decklight" only when something was actually named; an unnamed
937
+ // holder is said to be unnamed, not asserted to be somebody else's
938
+ if (!there && !who) lines.push(`${label}: port ${port} is held by a process decklight could not identify, ${tail}`);
939
+ else lines.push(`${label}: port ${port} is held by ${there ? there.name ?? 'another decklight bridge' : `${who.command} (pid ${who.pid})`}`
940
+ + ` — ${there ? 'not this bridge' : 'not decklight'} — ${tail}`);
941
+ }
942
+ return lines;
943
+ }