decklight 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
package/cli/edit.mjs CHANGED
@@ -1,44 +1,83 @@
1
1
  #!/usr/bin/env node
2
- // decklight edit — the live-editing dev server (SPEC §8 edit mode).
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // The live-editing deck server behind `decklight author` (SPEC PRESENTING
6
+ // author mode). Not a command of its own anymore — the dispatcher refuses
7
+ // `edit` out loud — author spawns this module directly:
8
+ //
9
+ // node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
10
+ // [--commit-every <seconds>] [--agent <name>]
3
11
  //
4
- // decklight edit <deck.html> [--port 8788]
12
+ // It binds 127.0.0.1 and nothing else. The phone remote used to be here behind
13
+ // `--remote`, which meant a clicker cost you an editing server on the LAN;
14
+ // `decklight present --remote` hosts it now, with no edit surface to widen
15
+ // (PRESENT#REMOTE). Both flags are refused out loud rather than ignored.
5
16
  //
6
17
  // Serves the current working directory over localhost (so decks that
7
18
  // reference ../dist and ../themes just work), watches the deck file, and:
8
19
  //
9
- // GET /edit/ping → { ok, deck } (player probes availability)
10
- // GET /edit/events → SSE; a `reload` event fires when the deck changes
11
- // POST /edit/notes → { slide, text } rewrite that slide's notes
20
+ // GET /edit/ping → { ok, deck, undo, redo, git, agents, agentBusy, wizards }
21
+ // GET /edit/events → SSE; `reload` on deck change, `agent` job status
22
+ // POST /edit/notes → { slide, text } rewrite that slide's notes
23
+ // POST /edit/layout → { slide, layout } write data-layout to the file
24
+ // GET /edit/element/source → ?slide=&index= an element's outerHTML, fresh from the file
25
+ // POST /edit/element/remove → { slide, index } delete that element
26
+ // POST /edit/element/content → { slide, index, html } replace its outerHTML
27
+ // POST /edit/element/effect → { slide, index, effect } write data-build (null strips it)
28
+ // POST /edit/undo → step the deck file back through the edit history
29
+ // POST /edit/redo → step it forward again
30
+ // POST /edit/agent → { prompt, agent? } one-shot AI agent edit
31
+ // POST /edit/shutdown → final autocommit, then exit — same as Ctrl-C, so a
32
+ // port conflict can take over an old session cleanly
33
+ //
34
+ // Every mutation goes through ONE undo history — snapshots of the whole
35
+ // file, held in memory, capped. Undo/redo is deliberately independent of
36
+ // git: git commits (below) are the durable record, the history is the
37
+ // second-to-second "that ring entry was worse" loop, and neither consumes
38
+ // the other. An agent run snapshots before it starts, so Z takes an
39
+ // agent's edit back exactly like the player's own.
12
40
  //
13
- // The player's E editor posts ⟨CLICK⟩-separated plain text; the server
14
- // rebuilds the <aside class="notes"> (one <p> per segment, escaped) and
15
- // writes the file — the watcher then tells every connected browser to
16
- // reload, and the #/slide/step hash restores the position.
41
+ // Git: with --git (or when the deck already sits in a repository and
42
+ // --no-git wasn't passed) the server auto-commits the deck on a regular
43
+ // basis — every --commit-every seconds when it actually changed, plus a
44
+ // final commit on Ctrl-C. --git also creates the repository when none
45
+ // exists — seeded with a starter .gitignore (createRepo, below).
46
+ // `decklight author` asks interactively before passing --git down.
17
47
 
18
48
  import { createServer } from 'node:http';
19
- import { readFileSync, writeFileSync, watch, existsSync, statSync } from 'node:fs';
20
- import { resolve, extname, sep, basename } from 'node:path';
21
-
22
- // file://-opened decks probe http://127.0.0.1:8788 directly (origin "null"),
23
- // exactly like the tts bridge — so the endpoints are CORS-open. The server
24
- // still binds 127.0.0.1 only.
25
- const CORS = {
26
- 'access-control-allow-origin': '*',
49
+ import { readFileSync, writeFileSync, watch, existsSync } from 'node:fs';
50
+ import { resolve, sep, basename } from 'node:path';
51
+ import { spawn } from 'node:child_process';
52
+ import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent } from './agents.mjs';
53
+ import { exitWhenOrphaned } from './supervise.mjs';
54
+ import { argReader, isMain } from '../tools/args.mjs';
55
+ import { NOTES_ASIDE, locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
56
+ import { deckHistory, restoreDeck, deckAt, withBaseHref } from './restore.mjs';
57
+ import { escapeHtml, sseChannel, staticFiles, listenTakingOverIfNeeded, allowEditRequest } from './serve.mjs';
58
+ import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
59
+
60
+ // The `/edit/*` surface answers loopback only — but "loopback" is the wrong
61
+ // boundary for the threat (#222). The dangerous caller is not off-machine: it
62
+ // is the user's own browser, where any open tab can `fetch()` this port. Binding
63
+ // 127.0.0.1 does nothing about that, and a wildcard `access-control-allow-origin`
64
+ // actively invites it. So every request is gated by `allowEditRequest` on its
65
+ // `Origin` (below), and CORS is echoed per request rather than granted to `*` —
66
+ // a foreign site's `fetch` never reaches a handler. The one origin still let
67
+ // through besides loopback is `null`: a file://-opened deck probes this server
68
+ // directly, and the SPEC keeps that double-click path (PRESENTING).
69
+ const corsHeadersFor = (origin) => ({
70
+ ...(origin !== undefined ? { 'access-control-allow-origin': origin } : {}),
27
71
  'access-control-allow-methods': 'GET, POST, OPTIONS',
28
72
  'access-control-allow-headers': 'content-type',
29
- };
30
-
31
- const MIME = {
32
- '.html': 'text/html; charset=utf-8',
33
- '.js': 'text/javascript', '.mjs': 'text/javascript',
34
- '.css': 'text/css', '.json': 'application/json',
35
- '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg',
36
- '.gif': 'image/gif', '.ico': 'image/x-icon', '.webp': 'image/webp',
37
- '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.mp3': 'audio/mpeg',
38
- '.woff': 'font/woff', '.woff2': 'font/woff2', '.map': 'application/json',
39
- };
73
+ vary: 'Origin',
74
+ });
40
75
 
41
- const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
76
+ // ── remote access & static serving: extracted to serve.mjs / remote.mjs ────
77
+ // (PRESENT_SERVER in MARKETPLACE.md: `decklight present` reuses the same core
78
+ // with the /edit/* routes ABSENT, not merely refused.) Re-exported here so
79
+ // existing importers — the tests, init.mjs — and SPEC citations keep working.
80
+ export { isLoopback, lanAddress, escapeHtml } from './serve.mjs';
42
81
 
43
82
  /** ⟨CLICK⟩-separated plain text → the aside's inner HTML (one <p> per segment). */
44
83
  export function notesTextToAside(text) {
@@ -53,78 +92,704 @@ export function notesTextToAside(text) {
53
92
 
54
93
  /** Replace (or insert) slide N's <aside class="notes"> in the deck html. */
55
94
  export function setSlideNotes(html, slide, asideInner) {
56
- // top-level sections can't nest, so splitting on the open tag is exact
57
- const parts = html.split(/(<section\b)/);
58
- const idx = 2 * slide; // parts[0] preamble, then [tag, content] pairs
59
- if (!parts[idx]) throw new Error(`no slide ${slide} (deck has ${(parts.length - 1) / 2})`);
95
+ const { parts, idx } = locateSlide(html, slide);
60
96
  const aside = `<aside class="notes">\n ${asideInner}\n </aside>`;
61
97
  const seg = parts[idx];
62
- parts[idx] = /<aside class="notes">[\s\S]*?<\/aside>/.test(seg)
63
- ? seg.replace(/<aside class="notes">[\s\S]*?<\/aside>/, aside)
98
+ parts[idx] = NOTES_ASIDE.test(seg)
99
+ ? seg.replace(NOTES_ASIDE, aside)
64
100
  : seg.replace(/<\/section>/, ` ${aside}\n </section>`);
65
101
  return parts.join('');
66
102
  }
67
103
 
104
+ // the same ring the player cycles — the file is the source of truth now
105
+ export const LAYOUTS = ['auto', 'centered', 'pinned', 'top', 'split', 'split-flip'];
106
+
107
+ /** Set (or, for 'auto', remove) slide N's data-layout attribute in the deck html. */
108
+ export function setSlideLayout(html, slide, name) {
109
+ if (!LAYOUTS.includes(name)) throw new Error(`unknown layout "${name}"`);
110
+ const { parts, idx } = locateSlide(html, slide);
111
+ const seg = parts[idx];
112
+ const gt = seg.indexOf('>');
113
+ if (gt < 0) throw new Error(`slide ${slide}: malformed <section> tag`);
114
+ let head = seg.slice(0, gt).replace(/\s+data-layout=("[^"]*"|'[^']*')/, '');
115
+ if (name !== 'auto') head += ` data-layout="${name}"`;
116
+ parts[idx] = head + seg.slice(gt);
117
+ return parts.join('');
118
+ }
119
+
120
+ /** Look up element `index` (raw child position) on slide `slide`, or throw. */
121
+ function locateElement(html, slide, index) {
122
+ const { parts, idx } = locateSlide(html, slide);
123
+ const seg = parts[idx];
124
+ const ranges = sectionChildRanges(seg);
125
+ const r = ranges[index];
126
+ if (!r) throw new Error(`slide ${slide}: no element at index ${index} (has ${ranges.length})`);
127
+ return { parts, idx, seg, r };
128
+ }
129
+
130
+ /** Remove slide N's element at raw child index `index` (title included). */
131
+ export function removeSlideElement(html, slide, index) {
132
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
133
+ parts[idx] = seg.slice(0, r.start) + seg.slice(r.end);
134
+ return parts.join('');
135
+ }
136
+
137
+ /** Replace slide N's element at raw child index `index` with `outerHtml` verbatim. */
138
+ export function setSlideElementHtml(html, slide, index, outerHtml) {
139
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
140
+ parts[idx] = seg.slice(0, r.start) + outerHtml + seg.slice(r.end);
141
+ return parts.join('');
142
+ }
143
+
144
+ // The spec's 7 entrance styles (MOTION), plus 'none' — an explicit, instant
145
+ // build step, distinct from having no data-build attribute at all: one more
146
+ // advance still reveals the element, it just has no animation.
147
+ export const BUILD_EFFECTS = ['fade', 'fade-up', 'fade-down', 'zoom', 'pop', 'draw', 'highlight', 'none'];
148
+
149
+ /**
150
+ * Set slide N's element `index`'s build/entrance effect, or — when `effect`
151
+ * is `null` — strip `data-build` entirely (the menu's separate "remove
152
+ * effect" action).
153
+ */
154
+ export function setSlideElementBuild(html, slide, index, effect) {
155
+ if (effect !== null && !BUILD_EFFECTS.includes(effect)) throw new Error(`unknown build effect "${effect}"`);
156
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
157
+ const el = seg.slice(r.start, r.end);
158
+ const gt = el.indexOf('>');
159
+ if (gt < 0) throw new Error(`slide ${slide}: malformed element at index ${index}`);
160
+ let head = el.slice(0, gt).replace(/\s+data-build=("[^"]*"|'[^']*')/, '');
161
+ if (effect !== null) head += ` data-build="${effect}"`;
162
+ parts[idx] = seg.slice(0, r.start) + head + el.slice(gt) + seg.slice(r.end);
163
+ return parts.join('');
164
+ }
165
+
166
+ /**
167
+ * The edit history: whole-file snapshots, in memory, capped. record() the
168
+ * content a mutation is about to replace; undo()/redo() take the CURRENT
169
+ * file content (which may include edits made outside the server — those
170
+ * land on the opposite stack, so nothing is silently lost) and return what
171
+ * to write, or null when the stack is empty.
172
+ */
173
+ export function createHistory(limit = 200) {
174
+ const past = [];
175
+ const future = [];
176
+ return {
177
+ record(before) {
178
+ past.push(before);
179
+ if (past.length > limit) past.shift();
180
+ future.length = 0;
181
+ },
182
+ undo(current) {
183
+ if (!past.length) return null;
184
+ future.push(current);
185
+ return past.pop();
186
+ },
187
+ redo(current) {
188
+ if (!future.length) return null;
189
+ past.push(current);
190
+ return future.pop();
191
+ },
192
+ counts() { return { undo: past.length, redo: future.length }; },
193
+ };
194
+ }
195
+
196
+ // ── git: the durable record (the history above is the fast loop) ──────────
197
+ // The plumbing lives in git.mjs now; imported for editMain's use below and
198
+ // re-exported so long-standing importers (init, the tests) keep finding it
199
+ // where edit grew it.
200
+ import { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit, resolveGitMode, shouldCommit, commitSubject, oneline } from './git.mjs';
201
+ export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
202
+
68
203
  export async function editMain(args) {
69
204
  if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
70
- console.log('usage: decklight edit <deck.html> [--port 8788]\n serves the cwd, live-reloads the deck on change, and accepts notes edits from the player (E)');
205
+ console.log(`usage: node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
206
+ [--commit-every <seconds>] [--agent <name>]
207
+ serves the cwd, live-reloads the deck on change, and accepts edits from the
208
+ player: notes (right-click a slide's background), per-slide layout (L/⇧L),
209
+ element edit mode (E, then right-click an element), undo/redo (Z/⇧Z), agent asks (A)
210
+ a taken --port offers to take over that session (on a TTY) or moves on to
211
+ the next free one
212
+ --git auto-commit the deck on a regular basis (creates the repo if needed)
213
+ --no-git never touch git (default outside a repository)
214
+ --commit-every N autocommit cadence in seconds (timer mode) [300]
215
+ --git-mode M when to commit: timer (a cadence), agent (one commit per
216
+ agent edit, with the agent's own message), off [timer]
217
+ --agent <name> preferred AI agent for A (default: first one detected)
218
+ the server binds 127.0.0.1 only; for a phone remote use decklight present`);
71
219
  return;
72
220
  }
73
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
221
+ const { opt } = argReader(args);
74
222
  const port = Number(opt('--port', 8788));
223
+ // Refused out loud, not ignored (PRESENT#REMOTE). Someone typing --remote
224
+ // wants a clicker; silently binding loopback would leave them holding a phone
225
+ // that never connects and no idea why. `present` is where the remote went,
226
+ // and the reason it went is worth saying at the moment it is asked for.
227
+ const gone = ['--remote', '--host'].filter((f) => args.some((a) => a === f || a.startsWith(f + '=')));
228
+ if (gone.length) {
229
+ console.error(`author no longer takes ${gone.join(' or ')} — the phone remote moved to \`decklight present\`.`);
230
+ console.error(' A clicker used to cost you an editing server on the LAN: /edit/notes, /edit/layout and');
231
+ console.error(' /edit/agent were reachable from the same run you were not watching. present has no edit');
232
+ console.error(' surface to widen, so that is where it lives.');
233
+ console.error(`\n decklight present ${args.find((a) => !a.startsWith('-')) ?? '<deck.html>'} --remote`);
234
+ process.exitCode = 2;
235
+ return;
236
+ }
237
+ const host = '127.0.0.1';
75
238
  const root = process.cwd();
76
239
  const deckPath = resolve(root, args.find((a) => !a.startsWith('-')));
77
240
  if (!existsSync(deckPath)) { console.error(`deck not found: ${deckPath}`); process.exitCode = 1; return; }
78
241
  if (!deckPath.startsWith(root + sep)) { console.error('deck must live under the current directory'); process.exitCode = 1; return; }
79
242
  const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
243
+ const deckRel = deckUrl.slice(1);
244
+
245
+ const history = createHistory();
246
+ const readDeck = () => readFileSync(deckPath, 'utf8');
247
+ // one door for every mutation: snapshot, then write — so Z always works
248
+ const applyEdit = (next, before = readDeck()) => {
249
+ if (next === before) return false;
250
+ history.record(before);
251
+ writeFileSync(deckPath, next);
252
+ return true;
253
+ };
254
+
255
+ // Declared before the git block below, which reads it to hold the cadence
256
+ // back while a job is in flight.
257
+ let agentJob = null; // { name, prompt, startedAt } — strictly one at a time
258
+
259
+ // ── git autocommit — the durable record, independent of undo/redo ──────
260
+ const noGit = args.includes('--no-git');
261
+ const wantGit = args.includes('--git');
262
+ const commitEvery = Math.max(5, Number(opt('--commit-every', 300)) || 300);
263
+ // timer (default, unchanged) · agent (one commit per agent edit) · off
264
+ const gitMode = resolveGitMode(args);
265
+ let gitOn = false;
266
+ if (!noGit && (wantGit || inGitRepo(root))) {
267
+ if (!inGitRepo(root)) {
268
+ try {
269
+ const wroteIgnore = createRepo(root);
270
+ console.log(` git: initialized a repository in ${root}${wroteIgnore ? ' (with a starter .gitignore)' : ''}`);
271
+ } catch (e) {
272
+ console.error(` git init failed: ${String(e.stderr || e.message || e).slice(0, 160)}`);
273
+ }
274
+ }
275
+ if (inGitRepo(root)) {
276
+ gitOn = true;
277
+ gitAutocommit(deckPath, root, `decklight: start editing ${basename(deckPath)}`);
278
+ // The cadence is the backstop, and it runs in agent mode too: an agent
279
+ // job only ever sees edits IT made, so hand edits — and any agent driven
280
+ // from outside the A flow — would otherwise reach git only via the
281
+ // Ctrl-C bookend, which a crash skips. It is held back while a job is in
282
+ // flight so nothing commits a half-finished agent run.
283
+ setInterval(() => {
284
+ if (shouldCommit(gitMode, { kind: 'timer', agentBusy: !!agentJob })) gitAutocommit(deckPath, root);
285
+ }, commitEvery * 1000).unref();
286
+ console.log(gitMode === 'agent'
287
+ ? ` git: committing ${deckRel} once per agent edit with the agent's own message, every ${commitEvery}s otherwise (and on Ctrl-C)`
288
+ : ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`);
289
+ }
290
+ }
291
+ const finalCommit = () => { if (gitOn) gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`); };
292
+ process.on('SIGINT', () => { finalCommit(); process.exit(0); });
293
+ process.on('SIGTERM', () => { finalCommit(); process.exit(0); });
294
+
295
+ // ── AI agents — one-shot editing tasks from the player (A) ─────────────
296
+ // Precedence, like every other saved choice: the flag wins, then what was
297
+ // remembered (#125), then the first detected agent.
298
+ let agentPref = opt('--agent') ?? preferredAgent();
299
+ const agents = detectAgents();
300
+ if (agents.length) {
301
+ const mark = (a) => a.name + (a.name === agentPref ? ' (preferred)' : '') + (a.installed ? ' (installed)' : '');
302
+ console.log(` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`);
303
+ }
304
+ // A remembered agent that is not on this machine is said ONCE, at startup,
305
+ // rather than discovered at the moment someone presses A mid-talk.
306
+ if (agentPref && !agents.some((a) => a.name === agentPref)) {
307
+ console.log(` agent: ${agentUnavailable(agentPref, agents)}`);
308
+ }
80
309
 
81
310
  // ── live reload: watch the deck, broadcast SSE (debounced — editors fire
82
311
  // multiple fs events per save) ─────────────────────────────────────────
83
- const clients = new Set();
312
+ const clients = sseChannel();
313
+ const broadcast = (event, data) => clients.broadcast(event, data);
314
+
315
+ // ── the catalogs, read from cache and never fetched ──────────────────────
316
+ const catalogMap = async () => {
317
+ const { loadRegistry, loadCatalog } = await import('./marketplace.mjs');
318
+ const out = {};
319
+ for (const name of Object.keys(loadRegistry().marketplaces ?? {})) {
320
+ const loaded = loadCatalog(name);
321
+ if (loaded?.ok) out[name] = loaded.manifest;
322
+ }
323
+ return out;
324
+ };
325
+ /** Every theme entry a registered marketplace offers, qualified. */
326
+ const browsableThemes = async () => {
327
+ const { loadRegistry, loadCatalog } = await import('./marketplace.mjs');
328
+ const registered = Object.keys(loadRegistry().marketplaces ?? {});
329
+ const themes = [];
330
+ // Registered-but-never-fetched is the FIRST-RUN state, not an error — the
331
+ // first-party marketplace is deliberately in it — so it is reported as
332
+ // something the presenter can act on (`marketplace update <name>`) rather
333
+ // than as an empty list that looks like an empty marketplace.
334
+ const stale = [];
335
+ for (const market of registered) {
336
+ const loaded = loadCatalog(market);
337
+ if (!loaded) { stale.push(market); continue; }
338
+ if (!loaded.ok) { stale.push(market); continue; }
339
+ for (const e of loaded.manifest.entries ?? []) {
340
+ if (e.type !== 'theme') continue;
341
+ themes.push({
342
+ name: e.name, marketplace: market, qualified: `${e.name}@${market}`,
343
+ description: e.description ?? '', source: e.source,
344
+ });
345
+ }
346
+ }
347
+ return { themes, stale };
348
+ };
349
+ /**
350
+ * Every entry a registered marketplace declares a wizard for, qualified.
351
+ * Advertised in /edit/ping beside the agents: the palette's Configure rows
352
+ * come from here, so a player never has to guess an engine name to ask
353
+ * /edit/wizard about (ENGINES#WIZARD).
354
+ */
355
+ const configurableEngines = async () => {
356
+ const { loadRegistry, loadCatalog } = await import('./marketplace.mjs');
357
+ const engines = [];
358
+ for (const market of Object.keys(loadRegistry().marketplaces ?? {})) {
359
+ const loaded = loadCatalog(market);
360
+ if (!loaded?.ok) continue;
361
+ for (const e of loaded.manifest.entries ?? []) {
362
+ if (!e.wizard) continue;
363
+ // The title is display-only; a malformed schema still gets listed, so
364
+ // opening it surfaces validateSchema's refusal instead of silence.
365
+ engines.push({
366
+ name: e.name, qualified: `${e.name}@${market}`,
367
+ title: typeof e.wizard.title === 'string' ? e.wizard.title : e.name,
368
+ });
369
+ }
370
+ }
371
+ return engines;
372
+ };
373
+
374
+ // ── the engine wizard: where a schema comes from, and who checks answers ─
375
+ // Both injected into configureEngine rather than reached for inside it: this
376
+ // server knows how catalogs are read, and cli/wizard.mjs has no business
377
+ // knowing — which is also what lets the framework be tested without a
378
+ // network or a real key.
379
+ const wizardEntry = async (engine) => {
380
+ const { resolveEntry, MarketplaceError } = await import('./marketplace.mjs');
381
+ // resolveEntry is the seam every install surface goes through — its docblock
382
+ // names the engine wizard as one of them — so `elevenlabs@voices` works, and
383
+ // a bare name that exists in two marketplaces is reported as ambiguous
384
+ // rather than silently resolved to whichever was registered first.
385
+ // loadCatalog returns the VALIDATION result, not the manifest — a cached
386
+ // catalog that no longer validates has no entries to offer, which is the
387
+ // right answer rather than a crash. catalogMap does that unwrapping once.
388
+ try {
389
+ const hit = resolveEntry(engine, await catalogMap());
390
+ // The whole hit, not just the entry: `qualified` is what the wizard's
391
+ // provenance line shows as the asker (#232), and it has to come from the
392
+ // registry rather than from anything the schema itself declares.
393
+ return hit.entry.wizard ? hit : null;
394
+ } catch (e) {
395
+ if (e instanceof MarketplaceError) return null;
396
+ throw e;
397
+ }
398
+ };
399
+ const wizardSchemaFor = async (engine) => {
400
+ const hit = await wizardEntry(engine);
401
+ if (!hit) throw new Error(`no wizard declared for "${engine}" in any registered marketplace`);
402
+ return hit.entry.wizard;
403
+ };
404
+ /**
405
+ * Ask the engine's own bridge whether the answers work.
406
+ *
407
+ * The plugin declares a PATH, never an origin — a schema that could name where
408
+ * to send a freshly pasted key would be a credential exfiltration primitive
409
+ * with a config file for a delivery mechanism. So the origin is this machine,
410
+ * and the plugin only chooses the path on it.
411
+ */
412
+ const wizardValidate = async (schema, answers) => {
413
+ if (!schema.validate) return true;
414
+ // BRIDGE_ADDR is shared with provenance() so the destination the player
415
+ // showed the presenter and the one this line posts to cannot drift apart.
416
+ const r = await fetch(`http://${BRIDGE_ADDR}${schema.validate}`, {
417
+ method: 'POST',
418
+ headers: { 'content-type': 'application/json' },
419
+ body: JSON.stringify({ engine: schema.engine, answers }),
420
+ signal: AbortSignal.timeout(8000),
421
+ });
422
+ if (!r.ok) return false;
423
+ const j = await r.json().catch(() => ({}));
424
+ return j?.ok === true;
425
+ };
426
+
84
427
  let pending = null;
85
428
  watch(deckPath, () => {
86
429
  clearTimeout(pending);
87
430
  pending = setTimeout(() => {
88
- for (const res of clients) res.write('data: reload\n\n');
431
+ clients.raw('data: reload\n\n');
89
432
  console.log(` changed → reload × ${clients.size}`);
90
433
  }, 150);
91
434
  });
92
435
 
436
+ function runAgent(prompt, name, message) {
437
+ const cmd = agentCommand(name || agentPref, prompt, deckRel);
438
+ if (!cmd) return null;
439
+ // Anything uncommitted at this moment is the PLAYER's work, not the
440
+ // agent's. Sweeping it into its own commit first is what keeps the agent's
441
+ // commit honest: otherwise a hand edit made just before pressing A lands
442
+ // under the agent's message, and a history that misattributes authorship is
443
+ // worse than one that only says "autosave".
444
+ if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
445
+ && gitAutocommit(deckPath, root, `decklight: save before ${cmd.name} edits ${basename(deckPath)}`)) {
446
+ console.log(' git: committed your outstanding changes first');
447
+ }
448
+ const before = readDeck();
449
+ agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: Date.now() };
450
+ broadcast('agent', { state: 'start', ...agentJob });
451
+ console.log(` agent: ${cmd.name} ← "${prompt.slice(0, 80)}"`);
452
+ const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
453
+ let tail = '';
454
+ const keep = (chunk) => { tail = (tail + chunk).slice(-4000); };
455
+ child.stdout.on('data', keep);
456
+ child.stderr.on('data', keep);
457
+ const timeout = setTimeout(() => child.kill('SIGTERM'), 10 * 60 * 1000);
458
+ child.on('error', (e) => {
459
+ clearTimeout(timeout);
460
+ agentJob = null;
461
+ broadcast('agent', { state: 'done', agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
462
+ });
463
+ child.on('exit', (code) => {
464
+ clearTimeout(timeout);
465
+ const after = readDeck();
466
+ const changed = after !== before;
467
+ if (changed) history.record(before); // Z takes the agent's edit back
468
+ // One commit per completed agent edit, carrying the agent's own summary
469
+ // — the boundary and the message both come from the work, not a clock.
470
+ // A failed run or one that changed nothing commits nothing.
471
+ if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
472
+ const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
473
+ if (gitAutocommit(deckPath, root, subject)) console.log(` git: committed "${subject}"`);
474
+ }
475
+ agentJob = null;
476
+ broadcast('agent', {
477
+ state: 'done', agent: cmd.name, ok: code === 0, changed, code,
478
+ tail: tail.trim().split('\n').slice(-6).join('\n').slice(-600),
479
+ });
480
+ console.log(` agent: ${cmd.name} exited (${code}) — deck ${changed ? 'changed' : 'unchanged'}`);
481
+ });
482
+ return cmd;
483
+ }
484
+
485
+ const files = staticFiles(root, { index: deckUrl });
93
486
  const server = createServer(async (req, res) => {
487
+ // The CSRF gate (#222), before anything runs. A same-machine browser tab is
488
+ // the threat, not an off-machine caller, so the check is the request's
489
+ // `Origin`, not its socket address. A foreign origin is refused here —
490
+ // before the body is read, before any file is written, before an agent is
491
+ // spawned — and refused WITHOUT permissive CORS, so the page cannot even
492
+ // read the refusal. Loopback origins, `null` (file://), and the header's
493
+ // absence (the CLI, the port-conflict probe, curl) pass.
494
+ const origin = req.headers.origin;
495
+ const CORS = corsHeadersFor(origin);
496
+ if (!allowEditRequest(req)) {
497
+ res.writeHead(403, { 'content-type': 'text/plain' });
498
+ res.end('forbidden: the author edit surface answers this machine only, and not a foreign web origin');
499
+ return;
500
+ }
94
501
  try {
95
502
  const url = new URL(req.url, 'http://x');
503
+ const json = (code, obj) => {
504
+ res.writeHead(code, { ...CORS, 'content-type': 'application/json' });
505
+ res.end(JSON.stringify(obj));
506
+ };
96
507
  if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
97
508
  if (req.method === 'GET' && url.pathname === '/edit/ping') {
98
- res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
99
- return res.end(JSON.stringify({ ok: true, deck: deckUrl, name: basename(deckPath) }));
509
+ return json(200, {
510
+ ok: true, deck: deckUrl, name: basename(deckPath),
511
+ ...history.counts(), git: gitOn,
512
+ agents: agents.map((a) => ({ name: a.name, label: a.label })),
513
+ // which one A reaches for, so the picker opens on it rather than
514
+ // defaulting to the first detected agent every session (#125)
515
+ preferredAgent: agentPref ?? null,
516
+ agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt },
517
+ wizards: await configurableEngines(),
518
+ });
100
519
  }
101
520
  if (req.method === 'GET' && url.pathname === '/edit/events') {
102
- res.writeHead(200, { ...CORS, 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
103
- res.write(': connected\n\n');
104
- clients.add(res);
105
- req.on('close', () => clients.delete(res));
521
+ clients.add(req, res, CORS);
106
522
  return;
107
523
  }
108
- if (req.method === 'POST' && url.pathname === '/edit/notes') {
109
- let body = '';
524
+ // ── the deck's durable history (#129): what the R overlay reads ────
525
+ // Loopback-only like every other /edit/* path: this serves arbitrary
526
+ // historical revisions of the deck, which is nobody else's business.
527
+ if (req.method === 'GET' && url.pathname === '/edit/history') {
528
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session — there is no history' });
529
+ try { return json(200, { ok: true, entries: deckHistory(deckPath, root) }); }
530
+ catch (e) { return json(500, { ok: false, error: oneline(e) }); }
531
+ }
532
+ if (req.method === 'GET' && url.pathname === '/edit/at') {
533
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
534
+ try {
535
+ // <base href="/"> because this is served from /edit/, not the root:
536
+ // without it every relative ../dist and ./casts path in the deck
537
+ // would resolve one directory too deep and the preview would be bare.
538
+ const html = withBaseHref(deckAt(deckPath, url.searchParams.get('ref') || '', root));
539
+ res.writeHead(200, { ...CORS, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
540
+ return res.end(html);
541
+ } catch {
542
+ res.writeHead(404, { ...CORS, 'content-type': 'text/plain' });
543
+ return res.end('no such revision of this deck');
544
+ }
545
+ }
546
+ // ── element edit mode (E, right-click a slide element) — #112 ─────
547
+ // Reads the element's outerHTML fresh from the FILE, never the live
548
+ // DOM: the engine mutates elements in place (pinned-title classes,
549
+ // namespaced SVG ids, chart/code/math subtree replacement), so the DOM
550
+ // the player sees is not what a Save should write back over.
551
+ if (req.method === 'GET' && url.pathname === '/edit/element/source') {
552
+ const slide = Number(url.searchParams.get('slide'));
553
+ const index = Number(url.searchParams.get('index'));
554
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) {
555
+ return json(400, { ok: false, error: 'bad payload' });
556
+ }
557
+ try {
558
+ const { parts, idx, r } = locateElement(readDeck(), slide, index);
559
+ return json(200, { ok: true, html: parts[idx].slice(r.start, r.end) });
560
+ } catch (e) {
561
+ return json(404, { ok: false, error: oneline(e) });
562
+ }
563
+ }
564
+
565
+ if (req.method === 'POST' && url.pathname === '/edit/shutdown') {
566
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
567
+ res.end(JSON.stringify({ ok: true }));
568
+ // same shutdown a Ctrl-C takes — final autocommit, then actually exit —
569
+ // once the response has cleared the socket, so the asker sees it land
570
+ res.once('finish', () => { finalCommit(); process.exit(0); });
571
+ return;
572
+ }
573
+ if (req.method === 'POST' && /^\/edit\/(undo|redo)$/.test(url.pathname)) {
574
+ const dir = url.pathname.endsWith('undo') ? 'undo' : 'redo';
575
+ const cur = readDeck();
576
+ const content = history[dir](cur);
577
+ if (content === null) return json(409, { ok: false, error: `nothing to ${dir}`, ...history.counts() });
578
+ writeFileSync(deckPath, content);
579
+ console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
580
+ return json(200, { ok: true, ...history.counts() });
581
+ }
582
+ let body = '';
583
+ if (req.method === 'POST') {
110
584
  for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
585
+ }
586
+ if (req.method === 'POST' && url.pathname === '/edit/restore') {
587
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
588
+ const { ref } = JSON.parse(body || '{}');
589
+ if (typeof ref !== 'string' || !ref.trim()) throw new Error('bad payload');
590
+ const before = readDeck();
591
+ let result;
592
+ try { result = restoreDeck(deckPath, ref.trim(), root); }
593
+ catch (e) { return json(400, { ok: false, error: oneline(e) }); }
594
+ // Z takes a restore back like any other edit — the git-level move and
595
+ // the keystroke-level stack stay in step rather than disagreeing.
596
+ if (result.changed) history.record(before);
597
+ console.log(` restored ${basename(deckPath)} to ${result.short}`);
598
+ return json(200, { ok: true, ...result, ...history.counts() });
599
+ }
600
+ // An intermediate commit point: a multi-step agent calls this when IT
601
+ // decides one logical change is finished, so the boundaries follow the
602
+ // work instead of a clock. The message is the agent's, and untrusted.
603
+ if (req.method === 'POST' && url.pathname === '/edit/commit') {
604
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
605
+ const { message } = JSON.parse(body || '{}');
606
+ const subject = commitSubject(message, `decklight: autosave ${basename(deckPath)}`);
607
+ const committed = gitAutocommit(deckPath, root, subject);
608
+ if (committed) console.log(` git: committed "${subject}"`);
609
+ return json(200, { ok: true, committed, subject });
610
+ }
611
+ // ── theme Browse (THEME_BROWSE#UI) ─────────────────────────────────
612
+ // What the picker's Browse entry lists. Cache-only by construction: this
613
+ // reads the catalogs `marketplace update` already fetched and never
614
+ // fetches one itself, so a deck on a plane lists what it has and says so
615
+ // rather than hanging on a network that is not there.
616
+ if (req.method === 'GET' && url.pathname === '/edit/theme/browse') {
617
+ const { themes, stale } = await browsableThemes();
618
+ return json(200, { ok: true, themes, stale, cacheOnly: true });
619
+ }
620
+ // Installing goes through `theme add`'s own functions — validation, the
621
+ // WCAG gates, the block shape — so a theme refused on the command line is
622
+ // refused here, by the same code, for the same reason.
623
+ if (req.method === 'POST' && url.pathname === '/edit/theme/add') {
624
+ const { ref, name: asName } = JSON.parse(body || '{}');
625
+ if (typeof ref !== 'string' || !ref.trim()) return json(400, { ok: false, error: 'which theme?' });
626
+ const { resolveEntry, MarketplaceError } = await import('./marketplace.mjs');
627
+ const { fetchTheme, installTheme, resolveSource } = await import('./theme.mjs');
628
+ const { validateTheme, themeNameFrom, validThemeName } = await import('../tools/theme-check.mjs');
629
+
630
+ let hit;
631
+ try { hit = resolveEntry(ref.trim(), await catalogMap()); }
632
+ catch (e) {
633
+ if (e instanceof MarketplaceError) return json(404, { ok: false, error: e.message });
634
+ throw e;
635
+ }
636
+ if (hit.entry.type !== 'theme') {
637
+ return json(400, { ok: false, error: `"${hit.qualified}" is a ${hit.entry.type}, not a theme` });
638
+ }
639
+ const name = asName || hit.entry.name;
640
+ if (!validThemeName(name)) return json(400, { ok: false, error: `not a usable theme name: "${name}"` });
641
+
642
+ // A manifest's `source` is relative to its MARKETPLACE, not to whoever
643
+ // is installing — resolveSource is where that is worked out, and it lives
644
+ // in theme.mjs because fetching an artifact and fetching a catalog are
645
+ // different permissions on this path.
646
+ const { loadRegistry } = await import('./marketplace.mjs');
647
+ const market = loadRegistry().marketplaces?.[hit.marketplace];
648
+ const src = resolveSource(hit.entry.source, market?.source);
649
+ let css;
650
+ try { css = await fetchTheme(src); }
651
+ catch (e) { return json(502, { ok: false, error: `could not read ${src}: ${oneline(e)}` }); }
652
+
653
+ const check = validateTheme(css);
654
+ if (!check.ok) {
655
+ // The deck is left byte-for-byte unchanged: a picker that could leave
656
+ // a deck carrying a broken theme would be worse than no picker.
657
+ return json(400, { ok: false, error: `${name} fails the theme contract`, problems: check.errors ?? [] });
658
+ }
659
+ const before = readDeck();
660
+ const out = installTheme(before, name, css);
661
+ if (!out.html) return json(500, { ok: false, error: 'the deck has no </head> to install into' });
662
+ history.record(before); // Z takes an install back like any other edit
663
+ writeFileSync(deckPath, out.html);
664
+ console.log(` theme: ${out.replaced ? 'replaced' : 'installed'} ${name} from ${hit.qualified}`);
665
+ return json(200, { ok: true, name, from: hit.qualified, replaced: out.replaced, ...history.counts() });
666
+ }
667
+ // ── the engine wizard (ENGINES#WIZARD) ─────────────────────────────
668
+ // The schema the player renders. Validated on the way OUT as well as on
669
+ // the way in: a catalog is a file someone else wrote, and handing the
670
+ // renderer a schema core has not vetted is how "core renders, a plugin
671
+ // declares" becomes "core renders whatever a plugin sent".
672
+ if (req.method === 'GET' && url.pathname === '/edit/wizard') {
673
+ const engine = url.searchParams.get('engine') ?? '';
674
+ const hit = await wizardEntry(engine);
675
+ if (!hit) return json(404, { ok: false, error: `no wizard declared for "${engine}"` });
676
+ try {
677
+ const schema = validateSchema(hit.entry.wizard);
678
+ // Provenance rides BESIDE the schema, never inside it (#232): `from`
679
+ // is the registry's name for the entry and the sentence pair is
680
+ // derived here from the vetted schema, so the card can say who is
681
+ // asking and where the answer goes in words the plugin did not write.
682
+ return json(200, { ok: true, schema, from: hit.qualified, provenance: provenance(schema, hit.qualified) });
683
+ } catch (e) {
684
+ return json(400, { ok: false, error: `${engine} declares a wizard core cannot render: ${e.message}` });
685
+ }
686
+ }
687
+ // Author-mode only, and that is structural rather than checked: this
688
+ // server answers loopback alone, and `present` registers nothing like
689
+ // these at all. A credential prompt in a deck you were emailed has
690
+ // nowhere to post.
691
+ if (req.method === 'POST' && url.pathname === '/edit/wizard') {
692
+ const { engine, answers } = JSON.parse(body);
693
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
694
+ // "No such engine" is a third answer, not one of the two failures. It is
695
+ // not an outage to wait out and not a refusal by a provider — it is a
696
+ // marketplace that was never added, and the fix is named.
697
+ if (!(await wizardEntry(engine))) {
698
+ return json(404, { ok: false, state: 'unknown',
699
+ error: `no engine named "${engine}" declares a wizard in any registered marketplace — try: decklight marketplace add <owner/repo>` });
700
+ }
701
+ const r = await configureEngine(engine, answers, {
702
+ fetchSchema: wizardSchemaFor,
703
+ validateAnswers: wizardValidate,
704
+ });
705
+ if (r.state !== CONFIGURED) {
706
+ // The three failures stay three: 503 for "could not reach", 400 for
707
+ // "that was refused", and 412 for "this machine is missing something"
708
+ // (ENGINES#LIPSYNC). A presenter whose key is wrong must not be told
709
+ // to check their network, and one who is missing rhubarb must not be
710
+ // told to check their key — the status code says which it is too.
711
+ const code = r.state === UNREACHABLE ? 503 : r.state === PREREQUISITE ? 412 : 400;
712
+ return json(code, { ok: false, state: r.state, error: r.reason, ...(r.unmet ? { unmet: r.unmet } : {}) });
713
+ }
714
+ // Redacted on the way out, always — the response is the one place a key
715
+ // could leak back into a page, a devtools log, or a screen recording.
716
+ console.log(` wizard: ${engine} configured (${r.file})`);
717
+ return json(200, { ok: true, state: r.state, engine, stored: r.stored });
718
+ }
719
+ if (req.method === 'POST' && url.pathname === '/edit/wizard/forget') {
720
+ const { engine } = JSON.parse(body);
721
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
722
+ const had = forgetCredentials(engine);
723
+ console.log(` wizard: ${engine} ${had ? 'forgotten' : 'was not configured'}`);
724
+ return json(200, { ok: true, forgotten: had });
725
+ }
726
+ if (req.method === 'POST' && url.pathname === '/edit/notes') {
111
727
  const { slide, text } = JSON.parse(body);
112
728
  if (!Number.isInteger(slide) || slide < 1 || typeof text !== 'string') throw new Error('bad payload');
113
- const html = readFileSync(deckPath, 'utf8');
114
- writeFileSync(deckPath, setSlideNotes(html, slide, notesTextToAside(text)));
729
+ applyEdit(setSlideNotes(readDeck(), slide, notesTextToAside(text)));
115
730
  console.log(` notes saved: slide ${slide} (${text.length} chars)`);
116
- res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
117
- return res.end(JSON.stringify({ ok: true }));
731
+ return json(200, { ok: true, ...history.counts() });
732
+ }
733
+ if (req.method === 'POST' && url.pathname === '/edit/layout') {
734
+ const { slide, layout } = JSON.parse(body);
735
+ if (!Number.isInteger(slide) || slide < 1 || typeof layout !== 'string') throw new Error('bad payload');
736
+ const changed = applyEdit(setSlideLayout(readDeck(), slide, layout));
737
+ if (changed) console.log(` layout saved: slide ${slide} → ${layout}`);
738
+ return json(200, { ok: true, changed, ...history.counts() });
739
+ }
740
+ // ── element edit mode (E, right-click a slide element) — #112 ─────
741
+ // Same door as layout/notes: a pure (html, slide, index, …) → html
742
+ // transform, through applyEdit, onto the ONE undo/redo stack.
743
+ if (req.method === 'POST' && url.pathname === '/edit/element/remove') {
744
+ const { slide, index } = JSON.parse(body);
745
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
746
+ const changed = applyEdit(removeSlideElement(readDeck(), slide, index));
747
+ if (changed) console.log(` element removed: slide ${slide} #${index}`);
748
+ return json(200, { ok: true, changed, ...history.counts() });
749
+ }
750
+ if (req.method === 'POST' && url.pathname === '/edit/element/content') {
751
+ const { slide, index, html } = JSON.parse(body);
752
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || typeof html !== 'string') {
753
+ throw new Error('bad payload');
754
+ }
755
+ const changed = applyEdit(setSlideElementHtml(readDeck(), slide, index, html));
756
+ if (changed) console.log(` element content saved: slide ${slide} #${index}`);
757
+ return json(200, { ok: true, changed, ...history.counts() });
118
758
  }
119
- // ── static files from the cwd ────────────────────────────────────
120
- if (req.method === 'GET') {
121
- const rel = url.pathname === '/' ? deckUrl : decodeURIComponent(url.pathname);
122
- const file = resolve(root, '.' + rel);
123
- if (!file.startsWith(root + sep) && file !== root) { res.writeHead(403); return res.end('forbidden'); }
124
- if (!existsSync(file) || !statSync(file).isFile()) { res.writeHead(404); return res.end('not found'); }
125
- res.writeHead(200, { 'content-type': MIME[extname(file).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'no-cache' });
126
- return res.end(readFileSync(file));
759
+ if (req.method === 'POST' && url.pathname === '/edit/element/effect') {
760
+ const { slide, index, effect } = JSON.parse(body);
761
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0
762
+ || (effect !== null && typeof effect !== 'string')) {
763
+ throw new Error('bad payload');
764
+ }
765
+ const changed = applyEdit(setSlideElementBuild(readDeck(), slide, index, effect));
766
+ if (changed) console.log(` element effect saved: slide ${slide} #${index} → ${effect ?? '(removed)'}`);
767
+ return json(200, { ok: true, changed, ...history.counts() });
127
768
  }
769
+ // Remember which agent A should reach for (#125, SPEC AGENT_UNITS). A
770
+ // preference is a choice about this machine, not about the deck, so it
771
+ // is written beside the unit library and never into the file.
772
+ if (req.method === 'POST' && url.pathname === '/edit/agent/prefer') {
773
+ const { agent } = JSON.parse(body);
774
+ if (agent !== null && typeof agent !== 'string') throw new Error('bad payload');
775
+ if (agent && !agents.some((a) => a.name === agent)) {
776
+ return json(400, { ok: false, error: agentUnavailable(agent, agents) });
777
+ }
778
+ setPreferredAgent(agent);
779
+ agentPref = agent ?? undefined;
780
+ console.log(` agent: ${agent ? `${agent} remembered as preferred` : 'preference cleared'}`);
781
+ return json(200, { ok: true, preferredAgent: agent ?? null });
782
+ }
783
+ if (req.method === 'POST' && url.pathname === '/edit/agent') {
784
+ const { prompt, agent, message } = JSON.parse(body);
785
+ if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
786
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
787
+ const cmd = runAgent(prompt.trim(), agent, message);
788
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
789
+ return json(200, { ok: true, agent: cmd.name, label: cmd.label });
790
+ }
791
+ // ── static files from the cwd (staticFiles, serve.mjs) ───────────
792
+ if (files(req, res, url)) return;
128
793
  res.writeHead(405);
129
794
  res.end();
130
795
  } catch (e) {
@@ -134,9 +799,14 @@ export async function editMain(args) {
134
799
  }
135
800
  });
136
801
 
137
- server.listen(port, '127.0.0.1', () => {
138
- console.log(`decklight edit on http://127.0.0.1:${port}${deckUrl} — E edits notes, saves reload the deck. Ctrl-C stops`);
139
- });
802
+ const actual = await listenTakingOverIfNeeded(server, port, host);
803
+ console.log(`decklight author on http://127.0.0.1:${actual}${deckUrl} — E element edit mode, L layouts, Z undo, A agent. Ctrl-C stops`);
140
804
  }
141
805
 
142
- if (import.meta.url === `file://${process.argv[1]}`) editMain(process.argv.slice(2));
806
+
807
+ if (isMain(import.meta.url)) {
808
+ // author spawns this module directly, so the leash the dispatcher used to
809
+ // arm is armed here — a no-op unless a supervising parent set it up.
810
+ exitWhenOrphaned();
811
+ editMain(process.argv.slice(2));
812
+ }