decklight 0.2.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +855 -80
  3. package/cli/agents.mjs +113 -9
  4. package/cli/associate.mjs +279 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +564 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +730 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +646 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +560 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +201 -0
  34. package/cli/units.mjs +488 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +5 -4
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +11 -2
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +139 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +316 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
package/cli/edit.mjs CHANGED
@@ -2,21 +2,34 @@
2
2
  // Copyright 2026 Gilles Philippart
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
- // decklight edit — the live-editing dev server (SPEC §8 edit mode).
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:
6
8
  //
7
- // decklight edit <deck.html> [--port 8788] [--git | --no-git]
8
- // [--commit-every <seconds>] [--agent <name>]
9
+ // node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
10
+ // [--commit-every <seconds>] [--agent <name>]
11
+ //
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.
9
16
  //
10
17
  // Serves the current working directory over localhost (so decks that
11
18
  // reference ../dist and ../themes just work), watches the deck file, and:
12
19
  //
13
- // GET /edit/ping → { ok, deck, undo, redo, git, agents, agentBusy }
14
- // GET /edit/events → SSE; `reload` on deck change, `agent` job status
15
- // POST /edit/notes → { slide, text } rewrite that slide's notes
16
- // POST /edit/layout → { slide, layout } write data-layout to the file
17
- // POST /edit/undo → step the deck file back through the edit history
18
- // POST /edit/redo → step it forward again
19
- // POST /edit/agent → { prompt, agent? } one-shot AI agent edit
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
20
33
  //
21
34
  // Every mutation goes through ONE undo history — snapshots of the whole
22
35
  // file, held in memory, capped. Undo/redo is deliberately independent of
@@ -29,34 +42,42 @@
29
42
  // --no-git wasn't passed) the server auto-commits the deck on a regular
30
43
  // basis — every --commit-every seconds when it actually changed, plus a
31
44
  // final commit on Ctrl-C. --git also creates the repository when none
32
- // exists. `decklight dev` asks interactively before passing --git down.
45
+ // exists — seeded with a starter .gitignore (createRepo, below).
46
+ // `decklight author` asks interactively before passing --git down.
33
47
 
34
48
  import { createServer } from 'node:http';
35
- import { readFileSync, writeFileSync, watch, existsSync, statSync } from 'node:fs';
36
- import { resolve, extname, sep, basename } from 'node:path';
37
- import { spawn, execFileSync } from 'node:child_process';
38
- import { agentCommand, detectAgents } from './agents.mjs';
39
-
40
- // file://-opened decks probe http://127.0.0.1:8788 directly (origin "null"),
41
- // exactly like the tts bridge — so the endpoints are CORS-open. The server
42
- // still binds 127.0.0.1 only.
43
- const CORS = {
44
- '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 } : {}),
45
71
  'access-control-allow-methods': 'GET, POST, OPTIONS',
46
72
  'access-control-allow-headers': 'content-type',
47
- };
48
-
49
- const MIME = {
50
- '.html': 'text/html; charset=utf-8',
51
- '.js': 'text/javascript', '.mjs': 'text/javascript',
52
- '.css': 'text/css', '.json': 'application/json',
53
- '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg',
54
- '.gif': 'image/gif', '.ico': 'image/x-icon', '.webp': 'image/webp',
55
- '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.mp3': 'audio/mpeg',
56
- '.woff': 'font/woff', '.woff2': 'font/woff2', '.map': 'application/json',
57
- };
73
+ vary: 'Origin',
74
+ });
58
75
 
59
- 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';
60
81
 
61
82
  /** ⟨CLICK⟩-separated plain text → the aside's inner HTML (one <p> per segment). */
62
83
  export function notesTextToAside(text) {
@@ -71,14 +92,11 @@ export function notesTextToAside(text) {
71
92
 
72
93
  /** Replace (or insert) slide N's <aside class="notes"> in the deck html. */
73
94
  export function setSlideNotes(html, slide, asideInner) {
74
- // top-level sections can't nest, so splitting on the open tag is exact
75
- const parts = html.split(/(<section\b)/);
76
- const idx = 2 * slide; // parts[0] preamble, then [tag, content] pairs
77
- if (!parts[idx]) throw new Error(`no slide ${slide} (deck has ${(parts.length - 1) / 2})`);
95
+ const { parts, idx } = locateSlide(html, slide);
78
96
  const aside = `<aside class="notes">\n ${asideInner}\n </aside>`;
79
97
  const seg = parts[idx];
80
- parts[idx] = /<aside class="notes">[\s\S]*?<\/aside>/.test(seg)
81
- ? seg.replace(/<aside class="notes">[\s\S]*?<\/aside>/, aside)
98
+ parts[idx] = NOTES_ASIDE.test(seg)
99
+ ? seg.replace(NOTES_ASIDE, aside)
82
100
  : seg.replace(/<\/section>/, ` ${aside}\n </section>`);
83
101
  return parts.join('');
84
102
  }
@@ -89,9 +107,7 @@ export const LAYOUTS = ['auto', 'centered', 'pinned', 'top', 'split', 'split-fli
89
107
  /** Set (or, for 'auto', remove) slide N's data-layout attribute in the deck html. */
90
108
  export function setSlideLayout(html, slide, name) {
91
109
  if (!LAYOUTS.includes(name)) throw new Error(`unknown layout "${name}"`);
92
- const parts = html.split(/(<section\b)/);
93
- const idx = 2 * slide;
94
- if (!parts[idx]) throw new Error(`no slide ${slide} (deck has ${(parts.length - 1) / 2})`);
110
+ const { parts, idx } = locateSlide(html, slide);
95
111
  const seg = parts[idx];
96
112
  const gt = seg.indexOf('>');
97
113
  if (gt < 0) throw new Error(`slide ${slide}: malformed <section> tag`);
@@ -101,6 +117,52 @@ export function setSlideLayout(html, slide, name) {
101
117
  return parts.join('');
102
118
  }
103
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
+
104
166
  /**
105
167
  * The edit history: whole-file snapshots, in memory, capped. record() the
106
168
  * content a mutation is about to replace; undo()/redo() take the CURRENT
@@ -132,48 +194,47 @@ export function createHistory(limit = 200) {
132
194
  }
133
195
 
134
196
  // ── git: the durable record (the history above is the fast loop) ──────────
135
- const git = (gitArgs, cwd) =>
136
- execFileSync('git', gitArgs, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
137
-
138
- export function inGitRepo(dir) {
139
- try { return git(['rev-parse', '--is-inside-work-tree'], dir) === 'true'; } catch { return false; }
140
- }
141
-
142
- /** Commit the deck if it changed. Returns true when a commit was made. */
143
- export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${basename(deckPath)}`) {
144
- try {
145
- if (!git(['status', '--porcelain', '--', deckPath], cwd)) return false;
146
- git(['add', '--', deckPath], cwd);
147
- try {
148
- git(['commit', '-m', message, '--', deckPath], cwd);
149
- } catch (e) {
150
- // a fresh machine has no git identity — commit anyway rather than
151
- // silently dropping the safety net, without touching global config
152
- if (!/user\.(name|email)|tell me who you are/i.test(String(e.stderr || e))) throw e;
153
- git(['-c', 'user.name=decklight', '-c', 'user.email=decklight@localhost',
154
- 'commit', '-m', message, '--', deckPath], cwd);
155
- }
156
- return true;
157
- } catch (e) {
158
- console.error(` git autocommit failed: ${String(e.stderr || e.message || e).slice(0, 160)}`);
159
- return false;
160
- }
161
- }
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 };
162
202
 
163
203
  export async function editMain(args) {
164
204
  if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
165
- console.log(`usage: decklight edit <deck.html> [--port 8788] [--git | --no-git]
205
+ console.log(`usage: node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
166
206
  [--commit-every <seconds>] [--agent <name>]
167
207
  serves the cwd, live-reloads the deck on change, and accepts edits from the
168
- player: notes (E), per-slide layout (L/⇧L), undo/redo (Z/⇧Z), agent asks (A)
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
169
212
  --git auto-commit the deck on a regular basis (creates the repo if needed)
170
213
  --no-git never touch git (default outside a repository)
171
- --commit-every N autocommit cadence in seconds [300]
172
- --agent <name> preferred AI agent for A (default: first one detected)`);
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`);
173
219
  return;
174
220
  }
175
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
221
+ const { opt } = argReader(args);
176
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';
177
238
  const root = process.cwd();
178
239
  const deckPath = resolve(root, args.find((a) => !a.startsWith('-')));
179
240
  if (!existsSync(deckPath)) { console.error(`deck not found: ${deckPath}`); process.exitCode = 1; return; }
@@ -191,16 +252,22 @@ export async function editMain(args) {
191
252
  return true;
192
253
  };
193
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
+
194
259
  // ── git autocommit — the durable record, independent of undo/redo ──────
195
260
  const noGit = args.includes('--no-git');
196
261
  const wantGit = args.includes('--git');
197
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);
198
265
  let gitOn = false;
199
266
  if (!noGit && (wantGit || inGitRepo(root))) {
200
267
  if (!inGitRepo(root)) {
201
268
  try {
202
- git(['init'], root);
203
- console.log(` git: initialized a repository in ${root}`);
269
+ const wroteIgnore = createRepo(root);
270
+ console.log(` git: initialized a repository in ${root}${wroteIgnore ? ' (with a starter .gitignore)' : ''}`);
204
271
  } catch (e) {
205
272
  console.error(` git init failed: ${String(e.stderr || e.message || e).slice(0, 160)}`);
206
273
  }
@@ -208,8 +275,17 @@ export async function editMain(args) {
208
275
  if (inGitRepo(root)) {
209
276
  gitOn = true;
210
277
  gitAutocommit(deckPath, root, `decklight: start editing ${basename(deckPath)}`);
211
- setInterval(() => gitAutocommit(deckPath, root), commitEvery * 1000).unref();
212
- console.log(` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`);
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)`);
213
289
  }
214
290
  }
215
291
  const finalCommit = () => { if (gitOn) gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`); };
@@ -217,29 +293,158 @@ export async function editMain(args) {
217
293
  process.on('SIGTERM', () => { finalCommit(); process.exit(0); });
218
294
 
219
295
  // ── AI agents — one-shot editing tasks from the player (A) ─────────────
220
- const agentPref = opt('--agent');
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();
221
299
  const agents = detectAgents();
222
- let agentJob = null; // { name, prompt, startedAt } — strictly one at a time
223
- if (agents.length) console.log(` agents: ${agents.map((a) => a.name).join(', ')} — “Ask agent” (A) is live`);
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
+ }
224
309
 
225
310
  // ── live reload: watch the deck, broadcast SSE (debounced — editors fire
226
311
  // multiple fs events per save) ─────────────────────────────────────────
227
- const clients = new Set();
228
- const broadcast = (event, data) => {
229
- for (const res of clients) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
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;
230
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
+
231
427
  let pending = null;
232
428
  watch(deckPath, () => {
233
429
  clearTimeout(pending);
234
430
  pending = setTimeout(() => {
235
- for (const res of clients) res.write('data: reload\n\n');
431
+ clients.raw('data: reload\n\n');
236
432
  console.log(` changed → reload × ${clients.size}`);
237
433
  }, 150);
238
434
  });
239
435
 
240
- function runAgent(prompt, name) {
436
+ function runAgent(prompt, name, message) {
241
437
  const cmd = agentCommand(name || agentPref, prompt, deckRel);
242
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
+ }
243
448
  const before = readDeck();
244
449
  agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: Date.now() };
245
450
  broadcast('agent', { state: 'start', ...agentJob });
@@ -260,6 +465,13 @@ export async function editMain(args) {
260
465
  const after = readDeck();
261
466
  const changed = after !== before;
262
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
+ }
263
475
  agentJob = null;
264
476
  broadcast('agent', {
265
477
  state: 'done', agent: cmd.name, ok: code === 0, changed, code,
@@ -270,7 +482,22 @@ export async function editMain(args) {
270
482
  return cmd;
271
483
  }
272
484
 
485
+ const files = staticFiles(root, { index: deckUrl });
273
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
+ }
274
501
  try {
275
502
  const url = new URL(req.url, 'http://x');
276
503
  const json = (code, obj) => {
@@ -283,14 +510,64 @@ export async function editMain(args) {
283
510
  ok: true, deck: deckUrl, name: basename(deckPath),
284
511
  ...history.counts(), git: gitOn,
285
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,
286
516
  agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt },
517
+ wizards: await configurableEngines(),
287
518
  });
288
519
  }
289
520
  if (req.method === 'GET' && url.pathname === '/edit/events') {
290
- res.writeHead(200, { ...CORS, 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
291
- res.write(': connected\n\n');
292
- clients.add(res);
293
- req.on('close', () => clients.delete(res));
521
+ clients.add(req, res, CORS);
522
+ return;
523
+ }
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); });
294
571
  return;
295
572
  }
296
573
  if (req.method === 'POST' && /^\/edit\/(undo|redo)$/.test(url.pathname)) {
@@ -306,6 +583,146 @@ export async function editMain(args) {
306
583
  if (req.method === 'POST') {
307
584
  for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
308
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
+ }
309
726
  if (req.method === 'POST' && url.pathname === '/edit/notes') {
310
727
  const { slide, text } = JSON.parse(body);
311
728
  if (!Number.isInteger(slide) || slide < 1 || typeof text !== 'string') throw new Error('bad payload');
@@ -320,23 +737,59 @@ export async function editMain(args) {
320
737
  if (changed) console.log(` layout saved: slide ${slide} → ${layout}`);
321
738
  return json(200, { ok: true, changed, ...history.counts() });
322
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() });
758
+ }
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() });
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
+ }
323
783
  if (req.method === 'POST' && url.pathname === '/edit/agent') {
324
- const { prompt, agent } = JSON.parse(body);
784
+ const { prompt, agent, message } = JSON.parse(body);
325
785
  if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
326
786
  if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
327
- const cmd = runAgent(prompt.trim(), agent);
328
- if (!cmd) return json(400, { ok: false, error: agent ? `agent "${agent}" not detected` : 'no agent CLI detected (claude, codex, bob, …)' });
787
+ const cmd = runAgent(prompt.trim(), agent, message);
788
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
329
789
  return json(200, { ok: true, agent: cmd.name, label: cmd.label });
330
790
  }
331
- // ── static files from the cwd ────────────────────────────────────
332
- if (req.method === 'GET') {
333
- const rel = url.pathname === '/' ? deckUrl : decodeURIComponent(url.pathname);
334
- const file = resolve(root, '.' + rel);
335
- if (!file.startsWith(root + sep) && file !== root) { res.writeHead(403); return res.end('forbidden'); }
336
- if (!existsSync(file) || !statSync(file).isFile()) { res.writeHead(404); return res.end('not found'); }
337
- res.writeHead(200, { 'content-type': MIME[extname(file).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'no-cache' });
338
- return res.end(readFileSync(file));
339
- }
791
+ // ── static files from the cwd (staticFiles, serve.mjs) ───────────
792
+ if (files(req, res, url)) return;
340
793
  res.writeHead(405);
341
794
  res.end();
342
795
  } catch (e) {
@@ -346,10 +799,14 @@ export async function editMain(args) {
346
799
  }
347
800
  });
348
801
 
349
- server.listen(port, '127.0.0.1', () => {
350
- const actual = server.address().port;
351
- console.log(`decklight edit on http://127.0.0.1:${actual}${deckUrl} — E notes, L layouts, Z undo, A agent. Ctrl-C stops`);
352
- });
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`);
353
804
  }
354
805
 
355
- 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
+ }