decklight 0.2.0 → 0.4.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 +881 -80
  3. package/cli/agents.mjs +116 -10
  4. package/cli/associate.mjs +286 -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 +577 -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 +911 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +654 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +564 -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 +219 -0
  34. package/cli/units.mjs +500 -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 +7 -5
  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 +46 -11
  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 +144 -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 +440 -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,166 @@ 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, checkoutPath, classifySource, configHome } = await import('./marketplace.mjs');
328
+ const registry = 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, m] of Object.entries(registry)) {
336
+ const loaded = loadCatalog(market);
337
+ if (!loaded) { stale.push(market); continue; }
338
+ if (!loaded.ok) { stale.push(market); continue; }
339
+ // A cached catalog whose FILES are not on disk is the same actionable
340
+ // state wearing a different face: since MARKETPLACES#CLONE an entry
341
+ // installs from the marketplace's checkout, so listing its themes would
342
+ // be offering rows that can only fail. `marketplace update` fixes both.
343
+ if (classifySource(m.source ?? '').kind !== 'local' && !existsSync(checkoutPath(configHome(), market))) {
344
+ stale.push(market);
345
+ continue;
346
+ }
347
+ for (const e of loaded.manifest.entries ?? []) {
348
+ if (e.type !== 'theme') continue;
349
+ themes.push({
350
+ name: e.name, marketplace: market, qualified: `${e.name}@${market}`,
351
+ description: e.description ?? '', source: e.source,
352
+ });
353
+ }
354
+ }
355
+ return { themes, stale };
230
356
  };
357
+ /**
358
+ * Every entry a registered marketplace declares a wizard for, qualified.
359
+ * Advertised in /edit/ping beside the agents: the palette's Configure rows
360
+ * come from here, so a player never has to guess an engine name to ask
361
+ * /edit/wizard about (ENGINES#WIZARD).
362
+ */
363
+ const configurableEngines = async () => {
364
+ const { loadRegistry, loadCatalog } = await import('./marketplace.mjs');
365
+ const engines = [];
366
+ for (const market of Object.keys(loadRegistry().marketplaces ?? {})) {
367
+ const loaded = loadCatalog(market);
368
+ if (!loaded?.ok) continue;
369
+ for (const e of loaded.manifest.entries ?? []) {
370
+ if (!e.wizard) continue;
371
+ // The title is display-only; a malformed schema still gets listed, so
372
+ // opening it surfaces validateSchema's refusal instead of silence.
373
+ engines.push({
374
+ name: e.name, qualified: `${e.name}@${market}`,
375
+ title: typeof e.wizard.title === 'string' ? e.wizard.title : e.name,
376
+ });
377
+ }
378
+ }
379
+ return engines;
380
+ };
381
+
382
+ // ── the engine wizard: where a schema comes from, and who checks answers ─
383
+ // Both injected into configureEngine rather than reached for inside it: this
384
+ // server knows how catalogs are read, and cli/wizard.mjs has no business
385
+ // knowing — which is also what lets the framework be tested without a
386
+ // network or a real key.
387
+ const wizardEntry = async (engine) => {
388
+ const { resolveEntry, MarketplaceError } = await import('./marketplace.mjs');
389
+ // resolveEntry is the seam every install surface goes through — its docblock
390
+ // names the engine wizard as one of them — so `elevenlabs@voices` works, and
391
+ // a bare name that exists in two marketplaces is reported as ambiguous
392
+ // rather than silently resolved to whichever was registered first.
393
+ // loadCatalog returns the VALIDATION result, not the manifest — a cached
394
+ // catalog that no longer validates has no entries to offer, which is the
395
+ // right answer rather than a crash. catalogMap does that unwrapping once.
396
+ try {
397
+ const hit = resolveEntry(engine, await catalogMap());
398
+ // The whole hit, not just the entry: `qualified` is what the wizard's
399
+ // provenance line shows as the asker (#232), and it has to come from the
400
+ // registry rather than from anything the schema itself declares.
401
+ return hit.entry.wizard ? hit : null;
402
+ } catch (e) {
403
+ if (e instanceof MarketplaceError) return null;
404
+ throw e;
405
+ }
406
+ };
407
+ const wizardSchemaFor = async (engine) => {
408
+ const hit = await wizardEntry(engine);
409
+ if (!hit) throw new Error(`no wizard declared for "${engine}" in any registered marketplace`);
410
+ return hit.entry.wizard;
411
+ };
412
+ /**
413
+ * Ask the engine's own bridge whether the answers work.
414
+ *
415
+ * The plugin declares a PATH, never an origin — a schema that could name where
416
+ * to send a freshly pasted key would be a credential exfiltration primitive
417
+ * with a config file for a delivery mechanism. So the origin is this machine,
418
+ * and the plugin only chooses the path on it.
419
+ */
420
+ const wizardValidate = async (schema, answers) => {
421
+ if (!schema.validate) return true;
422
+ // BRIDGE_ADDR is shared with provenance() so the destination the player
423
+ // showed the presenter and the one this line posts to cannot drift apart.
424
+ const r = await fetch(`http://${BRIDGE_ADDR}${schema.validate}`, {
425
+ method: 'POST',
426
+ headers: { 'content-type': 'application/json' },
427
+ body: JSON.stringify({ engine: schema.engine, answers }),
428
+ signal: AbortSignal.timeout(8000),
429
+ });
430
+ if (!r.ok) return false;
431
+ const j = await r.json().catch(() => ({}));
432
+ return j?.ok === true;
433
+ };
434
+
231
435
  let pending = null;
232
436
  watch(deckPath, () => {
233
437
  clearTimeout(pending);
234
438
  pending = setTimeout(() => {
235
- for (const res of clients) res.write('data: reload\n\n');
439
+ clients.raw('data: reload\n\n');
236
440
  console.log(` changed → reload × ${clients.size}`);
237
441
  }, 150);
238
442
  });
239
443
 
240
- function runAgent(prompt, name) {
444
+ function runAgent(prompt, name, message) {
241
445
  const cmd = agentCommand(name || agentPref, prompt, deckRel);
242
446
  if (!cmd) return null;
447
+ // Anything uncommitted at this moment is the PLAYER's work, not the
448
+ // agent's. Sweeping it into its own commit first is what keeps the agent's
449
+ // commit honest: otherwise a hand edit made just before pressing A lands
450
+ // under the agent's message, and a history that misattributes authorship is
451
+ // worse than one that only says "autosave".
452
+ if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
453
+ && gitAutocommit(deckPath, root, `decklight: save before ${cmd.name} edits ${basename(deckPath)}`)) {
454
+ console.log(' git: committed your outstanding changes first');
455
+ }
243
456
  const before = readDeck();
244
457
  agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: Date.now() };
245
458
  broadcast('agent', { state: 'start', ...agentJob });
@@ -260,6 +473,13 @@ export async function editMain(args) {
260
473
  const after = readDeck();
261
474
  const changed = after !== before;
262
475
  if (changed) history.record(before); // Z takes the agent's edit back
476
+ // One commit per completed agent edit, carrying the agent's own summary
477
+ // — the boundary and the message both come from the work, not a clock.
478
+ // A failed run or one that changed nothing commits nothing.
479
+ if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
480
+ const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
481
+ if (gitAutocommit(deckPath, root, subject)) console.log(` git: committed "${subject}"`);
482
+ }
263
483
  agentJob = null;
264
484
  broadcast('agent', {
265
485
  state: 'done', agent: cmd.name, ok: code === 0, changed, code,
@@ -270,7 +490,22 @@ export async function editMain(args) {
270
490
  return cmd;
271
491
  }
272
492
 
493
+ const files = staticFiles(root, { index: deckUrl });
273
494
  const server = createServer(async (req, res) => {
495
+ // The CSRF gate (#222), before anything runs. A same-machine browser tab is
496
+ // the threat, not an off-machine caller, so the check is the request's
497
+ // `Origin`, not its socket address. A foreign origin is refused here —
498
+ // before the body is read, before any file is written, before an agent is
499
+ // spawned — and refused WITHOUT permissive CORS, so the page cannot even
500
+ // read the refusal. Loopback origins, `null` (file://), and the header's
501
+ // absence (the CLI, the port-conflict probe, curl) pass.
502
+ const origin = req.headers.origin;
503
+ const CORS = corsHeadersFor(origin);
504
+ if (!allowEditRequest(req)) {
505
+ res.writeHead(403, { 'content-type': 'text/plain' });
506
+ res.end('forbidden: the author edit surface answers this machine only, and not a foreign web origin');
507
+ return;
508
+ }
274
509
  try {
275
510
  const url = new URL(req.url, 'http://x');
276
511
  const json = (code, obj) => {
@@ -283,14 +518,64 @@ export async function editMain(args) {
283
518
  ok: true, deck: deckUrl, name: basename(deckPath),
284
519
  ...history.counts(), git: gitOn,
285
520
  agents: agents.map((a) => ({ name: a.name, label: a.label })),
521
+ // which one A reaches for, so the picker opens on it rather than
522
+ // defaulting to the first detected agent every session (#125)
523
+ preferredAgent: agentPref ?? null,
286
524
  agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt },
525
+ wizards: await configurableEngines(),
287
526
  });
288
527
  }
289
528
  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));
529
+ clients.add(req, res, CORS);
530
+ return;
531
+ }
532
+ // ── the deck's durable history (#129): what the R overlay reads ────
533
+ // Loopback-only like every other /edit/* path: this serves arbitrary
534
+ // historical revisions of the deck, which is nobody else's business.
535
+ if (req.method === 'GET' && url.pathname === '/edit/history') {
536
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session — there is no history' });
537
+ try { return json(200, { ok: true, entries: deckHistory(deckPath, root) }); }
538
+ catch (e) { return json(500, { ok: false, error: oneline(e) }); }
539
+ }
540
+ if (req.method === 'GET' && url.pathname === '/edit/at') {
541
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
542
+ try {
543
+ // <base href="/"> because this is served from /edit/, not the root:
544
+ // without it every relative ../dist and ./casts path in the deck
545
+ // would resolve one directory too deep and the preview would be bare.
546
+ const html = withBaseHref(deckAt(deckPath, url.searchParams.get('ref') || '', root));
547
+ res.writeHead(200, { ...CORS, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
548
+ return res.end(html);
549
+ } catch {
550
+ res.writeHead(404, { ...CORS, 'content-type': 'text/plain' });
551
+ return res.end('no such revision of this deck');
552
+ }
553
+ }
554
+ // ── element edit mode (E, right-click a slide element) — #112 ─────
555
+ // Reads the element's outerHTML fresh from the FILE, never the live
556
+ // DOM: the engine mutates elements in place (pinned-title classes,
557
+ // namespaced SVG ids, chart/code/math subtree replacement), so the DOM
558
+ // the player sees is not what a Save should write back over.
559
+ if (req.method === 'GET' && url.pathname === '/edit/element/source') {
560
+ const slide = Number(url.searchParams.get('slide'));
561
+ const index = Number(url.searchParams.get('index'));
562
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) {
563
+ return json(400, { ok: false, error: 'bad payload' });
564
+ }
565
+ try {
566
+ const { parts, idx, r } = locateElement(readDeck(), slide, index);
567
+ return json(200, { ok: true, html: parts[idx].slice(r.start, r.end) });
568
+ } catch (e) {
569
+ return json(404, { ok: false, error: oneline(e) });
570
+ }
571
+ }
572
+
573
+ if (req.method === 'POST' && url.pathname === '/edit/shutdown') {
574
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
575
+ res.end(JSON.stringify({ ok: true }));
576
+ // same shutdown a Ctrl-C takes — final autocommit, then actually exit —
577
+ // once the response has cleared the socket, so the asker sees it land
578
+ res.once('finish', () => { finalCommit(); process.exit(0); });
294
579
  return;
295
580
  }
296
581
  if (req.method === 'POST' && /^\/edit\/(undo|redo)$/.test(url.pathname)) {
@@ -306,6 +591,151 @@ export async function editMain(args) {
306
591
  if (req.method === 'POST') {
307
592
  for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
308
593
  }
594
+ if (req.method === 'POST' && url.pathname === '/edit/restore') {
595
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
596
+ const { ref } = JSON.parse(body || '{}');
597
+ if (typeof ref !== 'string' || !ref.trim()) throw new Error('bad payload');
598
+ const before = readDeck();
599
+ let result;
600
+ try { result = restoreDeck(deckPath, ref.trim(), root); }
601
+ catch (e) { return json(400, { ok: false, error: oneline(e) }); }
602
+ // Z takes a restore back like any other edit — the git-level move and
603
+ // the keystroke-level stack stay in step rather than disagreeing.
604
+ if (result.changed) history.record(before);
605
+ console.log(` restored ${basename(deckPath)} to ${result.short}`);
606
+ return json(200, { ok: true, ...result, ...history.counts() });
607
+ }
608
+ // An intermediate commit point: a multi-step agent calls this when IT
609
+ // decides one logical change is finished, so the boundaries follow the
610
+ // work instead of a clock. The message is the agent's, and untrusted.
611
+ if (req.method === 'POST' && url.pathname === '/edit/commit') {
612
+ if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
613
+ const { message } = JSON.parse(body || '{}');
614
+ const subject = commitSubject(message, `decklight: autosave ${basename(deckPath)}`);
615
+ const committed = gitAutocommit(deckPath, root, subject);
616
+ if (committed) console.log(` git: committed "${subject}"`);
617
+ return json(200, { ok: true, committed, subject });
618
+ }
619
+ // ── theme Browse (THEME_BROWSE#UI) ─────────────────────────────────
620
+ // What the picker's Browse entry lists. Cache-only by construction: this
621
+ // reads the catalogs `marketplace update` already fetched and never
622
+ // fetches one itself, so a deck on a plane lists what it has and says so
623
+ // rather than hanging on a network that is not there.
624
+ if (req.method === 'GET' && url.pathname === '/edit/theme/browse') {
625
+ const { themes, stale } = await browsableThemes();
626
+ return json(200, { ok: true, themes, stale, cacheOnly: true });
627
+ }
628
+ // Installing goes through `theme add`'s own functions — validation, the
629
+ // WCAG gates, the block shape — so a theme refused on the command line is
630
+ // refused here, by the same code, for the same reason.
631
+ if (req.method === 'POST' && url.pathname === '/edit/theme/add') {
632
+ const { ref, name: asName } = JSON.parse(body || '{}');
633
+ if (typeof ref !== 'string' || !ref.trim()) return json(400, { ok: false, error: 'which theme?' });
634
+ const { resolveEntry, MarketplaceError } = await import('./marketplace.mjs');
635
+ const { fetchTheme, installTheme, resolveSource } = await import('./theme.mjs');
636
+ const { validateTheme, themeNameFrom, validThemeName } = await import('../tools/theme-check.mjs');
637
+
638
+ let hit;
639
+ try { hit = resolveEntry(ref.trim(), await catalogMap()); }
640
+ catch (e) {
641
+ if (e instanceof MarketplaceError) return json(404, { ok: false, error: e.message });
642
+ throw e;
643
+ }
644
+ if (hit.entry.type !== 'theme') {
645
+ return json(400, { ok: false, error: `"${hit.qualified}" is a ${hit.entry.type}, not a theme` });
646
+ }
647
+ const name = asName || hit.entry.name;
648
+ if (!validThemeName(name)) return json(400, { ok: false, error: `not a usable theme name: "${name}"` });
649
+
650
+ // A manifest's `source` is relative to its MARKETPLACE, not to whoever
651
+ // is installing — resolveSource is where that is worked out, and it lives
652
+ // in theme.mjs because fetching an artifact and fetching a catalog are
653
+ // different permissions on this path.
654
+ const { loadRegistry } = await import('./marketplace.mjs');
655
+ const market = loadRegistry().marketplaces?.[hit.marketplace];
656
+ let src;
657
+ try { src = resolveSource(hit.entry.source, { name: hit.marketplace, source: market?.source }); }
658
+ catch (e) {
659
+ if (e instanceof MarketplaceError) return json(409, { ok: false, error: e.message });
660
+ throw e;
661
+ }
662
+ let css;
663
+ try { css = await fetchTheme(src); }
664
+ catch (e) { return json(502, { ok: false, error: `could not read ${src}: ${oneline(e)}` }); }
665
+
666
+ const check = validateTheme(css);
667
+ if (!check.ok) {
668
+ // The deck is left byte-for-byte unchanged: a picker that could leave
669
+ // a deck carrying a broken theme would be worse than no picker.
670
+ return json(400, { ok: false, error: `${name} fails the theme contract`, problems: check.errors ?? [] });
671
+ }
672
+ const before = readDeck();
673
+ const out = installTheme(before, name, css);
674
+ if (!out.html) return json(500, { ok: false, error: 'the deck has no </head> to install into' });
675
+ history.record(before); // Z takes an install back like any other edit
676
+ writeFileSync(deckPath, out.html);
677
+ console.log(` theme: ${out.replaced ? 'replaced' : 'installed'} ${name} from ${hit.qualified}`);
678
+ return json(200, { ok: true, name, from: hit.qualified, replaced: out.replaced, ...history.counts() });
679
+ }
680
+ // ── the engine wizard (ENGINES#WIZARD) ─────────────────────────────
681
+ // The schema the player renders. Validated on the way OUT as well as on
682
+ // the way in: a catalog is a file someone else wrote, and handing the
683
+ // renderer a schema core has not vetted is how "core renders, a plugin
684
+ // declares" becomes "core renders whatever a plugin sent".
685
+ if (req.method === 'GET' && url.pathname === '/edit/wizard') {
686
+ const engine = url.searchParams.get('engine') ?? '';
687
+ const hit = await wizardEntry(engine);
688
+ if (!hit) return json(404, { ok: false, error: `no wizard declared for "${engine}"` });
689
+ try {
690
+ const schema = validateSchema(hit.entry.wizard);
691
+ // Provenance rides BESIDE the schema, never inside it (#232): `from`
692
+ // is the registry's name for the entry and the sentence pair is
693
+ // derived here from the vetted schema, so the card can say who is
694
+ // asking and where the answer goes in words the plugin did not write.
695
+ return json(200, { ok: true, schema, from: hit.qualified, provenance: provenance(schema, hit.qualified) });
696
+ } catch (e) {
697
+ return json(400, { ok: false, error: `${engine} declares a wizard core cannot render: ${e.message}` });
698
+ }
699
+ }
700
+ // Author-mode only, and that is structural rather than checked: this
701
+ // server answers loopback alone, and `present` registers nothing like
702
+ // these at all. A credential prompt in a deck you were emailed has
703
+ // nowhere to post.
704
+ if (req.method === 'POST' && url.pathname === '/edit/wizard') {
705
+ const { engine, answers } = JSON.parse(body);
706
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
707
+ // "No such engine" is a third answer, not one of the two failures. It is
708
+ // not an outage to wait out and not a refusal by a provider — it is a
709
+ // marketplace that was never added, and the fix is named.
710
+ if (!(await wizardEntry(engine))) {
711
+ return json(404, { ok: false, state: 'unknown',
712
+ error: `no engine named "${engine}" declares a wizard in any registered marketplace — try: decklight marketplace add <owner/repo>` });
713
+ }
714
+ const r = await configureEngine(engine, answers, {
715
+ fetchSchema: wizardSchemaFor,
716
+ validateAnswers: wizardValidate,
717
+ });
718
+ if (r.state !== CONFIGURED) {
719
+ // The three failures stay three: 503 for "could not reach", 400 for
720
+ // "that was refused", and 412 for "this machine is missing something"
721
+ // (ENGINES#LIPSYNC). A presenter whose key is wrong must not be told
722
+ // to check their network, and one who is missing rhubarb must not be
723
+ // told to check their key — the status code says which it is too.
724
+ const code = r.state === UNREACHABLE ? 503 : r.state === PREREQUISITE ? 412 : 400;
725
+ return json(code, { ok: false, state: r.state, error: r.reason, ...(r.unmet ? { unmet: r.unmet } : {}) });
726
+ }
727
+ // Redacted on the way out, always — the response is the one place a key
728
+ // could leak back into a page, a devtools log, or a screen recording.
729
+ console.log(` wizard: ${engine} configured (${r.file})`);
730
+ return json(200, { ok: true, state: r.state, engine, stored: r.stored });
731
+ }
732
+ if (req.method === 'POST' && url.pathname === '/edit/wizard/forget') {
733
+ const { engine } = JSON.parse(body);
734
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
735
+ const had = forgetCredentials(engine);
736
+ console.log(` wizard: ${engine} ${had ? 'forgotten' : 'was not configured'}`);
737
+ return json(200, { ok: true, forgotten: had });
738
+ }
309
739
  if (req.method === 'POST' && url.pathname === '/edit/notes') {
310
740
  const { slide, text } = JSON.parse(body);
311
741
  if (!Number.isInteger(slide) || slide < 1 || typeof text !== 'string') throw new Error('bad payload');
@@ -320,23 +750,59 @@ export async function editMain(args) {
320
750
  if (changed) console.log(` layout saved: slide ${slide} → ${layout}`);
321
751
  return json(200, { ok: true, changed, ...history.counts() });
322
752
  }
753
+ // ── element edit mode (E, right-click a slide element) — #112 ─────
754
+ // Same door as layout/notes: a pure (html, slide, index, …) → html
755
+ // transform, through applyEdit, onto the ONE undo/redo stack.
756
+ if (req.method === 'POST' && url.pathname === '/edit/element/remove') {
757
+ const { slide, index } = JSON.parse(body);
758
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
759
+ const changed = applyEdit(removeSlideElement(readDeck(), slide, index));
760
+ if (changed) console.log(` element removed: slide ${slide} #${index}`);
761
+ return json(200, { ok: true, changed, ...history.counts() });
762
+ }
763
+ if (req.method === 'POST' && url.pathname === '/edit/element/content') {
764
+ const { slide, index, html } = JSON.parse(body);
765
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || typeof html !== 'string') {
766
+ throw new Error('bad payload');
767
+ }
768
+ const changed = applyEdit(setSlideElementHtml(readDeck(), slide, index, html));
769
+ if (changed) console.log(` element content saved: slide ${slide} #${index}`);
770
+ return json(200, { ok: true, changed, ...history.counts() });
771
+ }
772
+ if (req.method === 'POST' && url.pathname === '/edit/element/effect') {
773
+ const { slide, index, effect } = JSON.parse(body);
774
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0
775
+ || (effect !== null && typeof effect !== 'string')) {
776
+ throw new Error('bad payload');
777
+ }
778
+ const changed = applyEdit(setSlideElementBuild(readDeck(), slide, index, effect));
779
+ if (changed) console.log(` element effect saved: slide ${slide} #${index} → ${effect ?? '(removed)'}`);
780
+ return json(200, { ok: true, changed, ...history.counts() });
781
+ }
782
+ // Remember which agent A should reach for (#125, SPEC AGENT_UNITS). A
783
+ // preference is a choice about this machine, not about the deck, so it
784
+ // is written beside the unit library and never into the file.
785
+ if (req.method === 'POST' && url.pathname === '/edit/agent/prefer') {
786
+ const { agent } = JSON.parse(body);
787
+ if (agent !== null && typeof agent !== 'string') throw new Error('bad payload');
788
+ if (agent && !agents.some((a) => a.name === agent)) {
789
+ return json(400, { ok: false, error: agentUnavailable(agent, agents) });
790
+ }
791
+ setPreferredAgent(agent);
792
+ agentPref = agent ?? undefined;
793
+ console.log(` agent: ${agent ? `${agent} remembered as preferred` : 'preference cleared'}`);
794
+ return json(200, { ok: true, preferredAgent: agent ?? null });
795
+ }
323
796
  if (req.method === 'POST' && url.pathname === '/edit/agent') {
324
- const { prompt, agent } = JSON.parse(body);
797
+ const { prompt, agent, message } = JSON.parse(body);
325
798
  if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
326
799
  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, …)' });
800
+ const cmd = runAgent(prompt.trim(), agent, message);
801
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
329
802
  return json(200, { ok: true, agent: cmd.name, label: cmd.label });
330
803
  }
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
- }
804
+ // ── static files from the cwd (staticFiles, serve.mjs) ───────────
805
+ if (files(req, res, url)) return;
340
806
  res.writeHead(405);
341
807
  res.end();
342
808
  } catch (e) {
@@ -346,10 +812,14 @@ export async function editMain(args) {
346
812
  }
347
813
  });
348
814
 
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
- });
815
+ const actual = await listenTakingOverIfNeeded(server, port, host);
816
+ 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
817
  }
354
818
 
355
- if (import.meta.url === `file://${process.argv[1]}`) editMain(process.argv.slice(2));
819
+
820
+ if (isMain(import.meta.url)) {
821
+ // author spawns this module directly, so the leash the dispatcher used to
822
+ // arm is armed here — a no-op unless a supervising parent set it up.
823
+ exitWhenOrphaned();
824
+ editMain(process.argv.slice(2));
825
+ }