decklight 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +61 -3
  3. package/README.md +58 -28
  4. package/SPEC.md +1326 -85
  5. package/cli/agent-review.mjs +5 -4
  6. package/cli/agents.mjs +148 -18
  7. package/cli/bundle-audio.mjs +10 -3
  8. package/cli/bundle-module.mjs +95 -0
  9. package/cli/bundle.mjs +125 -7
  10. package/cli/cast.mjs +86 -19
  11. package/cli/check-fixes.mjs +194 -0
  12. package/cli/check-watch.mjs +151 -0
  13. package/cli/check.mjs +491 -75
  14. package/cli/code-editor.mjs +287 -0
  15. package/cli/commands.mjs +13 -2
  16. package/cli/commit-flow.mjs +7 -3
  17. package/cli/commit-message.mjs +35 -8
  18. package/cli/commit-split.mjs +125 -25
  19. package/cli/deck-refs.mjs +8 -3
  20. package/cli/decklight.mjs +11 -1
  21. package/cli/design-system-edit.mjs +37 -1
  22. package/cli/design-system-refs.mjs +263 -6
  23. package/cli/design-system.mjs +82 -14
  24. package/cli/edit-address.mjs +184 -0
  25. package/cli/edit-git.mjs +23 -6
  26. package/cli/edit-handover.mjs +257 -40
  27. package/cli/edit-look.mjs +293 -6
  28. package/cli/edit-open.mjs +143 -0
  29. package/cli/edit-slides.mjs +1043 -67
  30. package/cli/edit-translate.mjs +243 -0
  31. package/cli/edit.mjs +3680 -319
  32. package/cli/editor-support.mjs +286 -0
  33. package/cli/enhance.mjs +157 -27
  34. package/cli/find-replace.mjs +142 -0
  35. package/cli/fix-review.mjs +368 -0
  36. package/cli/git.mjs +13 -0
  37. package/cli/init.mjs +101 -22
  38. package/cli/keep-awake.mjs +68 -0
  39. package/cli/marketplace-autocheck.mjs +200 -0
  40. package/cli/marketplace.mjs +250 -13
  41. package/cli/migrate-writing.mjs +214 -0
  42. package/cli/narrate.mjs +121 -5
  43. package/cli/open.mjs +53 -15
  44. package/cli/outside-edit.mjs +257 -0
  45. package/cli/paste.mjs +92 -0
  46. package/cli/pdf.mjs +88 -10
  47. package/cli/pptx-export.mjs +10 -5
  48. package/cli/publish.mjs +24 -3
  49. package/cli/record.mjs +86 -15
  50. package/cli/remote.mjs +32 -6
  51. package/cli/rewrite.mjs +265 -0
  52. package/cli/runtime-link.mjs +218 -17
  53. package/cli/serve.mjs +9 -6
  54. package/cli/setup.mjs +2 -2
  55. package/cli/skill-content.mjs +251 -10
  56. package/cli/skills/slide-writing.md +333 -0
  57. package/cli/skills/voiceover.md +423 -0
  58. package/cli/skills.mjs +282 -15
  59. package/cli/starter-full.mjs +353 -0
  60. package/cli/supervise.mjs +14 -0
  61. package/cli/theme-refs.mjs +14 -2
  62. package/cli/theme.mjs +3 -2
  63. package/cli/translate-core.mjs +466 -0
  64. package/cli/translate-files.mjs +149 -0
  65. package/cli/translate.mjs +458 -0
  66. package/cli/units.mjs +75 -7
  67. package/cli/util.mjs +25 -0
  68. package/cli/vocabulary-docs.mjs +138 -0
  69. package/dist/decklight.css +2506 -113
  70. package/dist/decklight.js +385 -175
  71. package/dist/decklight.js.map +4 -4
  72. package/docs/GLOSSARY.md +9 -2
  73. package/docs/WRITING_RESEARCH.md +327 -0
  74. package/package.json +5 -3
  75. package/themes/coastal.css +3 -0
  76. package/themes/metropolis.css +2 -0
  77. package/themes/reveal-blood.css +3 -0
  78. package/themes/reveal-league.css +2 -0
  79. package/themes/reveal-moon.css +2 -0
  80. package/themes/reveal-serif.css +1 -0
  81. package/themes/reveal-sky.css +1 -0
  82. package/themes/reveal-solarized.css +4 -0
  83. package/tools/brand-palette.mjs +6 -1
  84. package/tools/build-groups.mjs +28 -8
  85. package/tools/cdp.mjs +176 -0
  86. package/tools/chart-spec.mjs +242 -0
  87. package/tools/click-match.mjs +70 -0
  88. package/tools/code-options.mjs +174 -0
  89. package/tools/conversation.mjs +49 -0
  90. package/tools/deck-family.mjs +101 -0
  91. package/tools/deck-html.mjs +212 -15
  92. package/tools/design-system-format.mjs +40 -1
  93. package/tools/design-system-migrations.mjs +207 -0
  94. package/tools/diagram-shapes.mjs +221 -0
  95. package/tools/elevenlabs-tts.mjs +62 -53
  96. package/tools/exec.mjs +10 -2
  97. package/tools/face-clip.mjs +96 -0
  98. package/tools/face-layout.mjs +94 -0
  99. package/tools/gemini-tts.mjs +1 -1
  100. package/tools/invisible-in-print.mjs +27 -0
  101. package/tools/lipsync-auto.mjs +197 -0
  102. package/tools/lipsync-config.mjs +16 -0
  103. package/tools/lipsync-engines.mjs +22 -4
  104. package/tools/lipsync-server.mjs +8 -5
  105. package/tools/lipsync.mjs +122 -30
  106. package/tools/local-voice.mjs +1 -1
  107. package/tools/mouth-file.mjs +26 -0
  108. package/tools/mouth.mjs +320 -0
  109. package/tools/narration-manifest.mjs +100 -6
  110. package/tools/narration-synth.mjs +96 -76
  111. package/tools/recording-impact.mjs +16 -1
  112. package/tools/sentences.mjs +7 -1
  113. package/tools/site-clip.mjs +114 -0
  114. package/tools/starters.mjs +402 -0
  115. package/tools/steps.mjs +118 -0
  116. package/tools/take-check.mjs +146 -0
  117. package/tools/template-theme.mjs +3 -1
  118. package/tools/test-impact.mjs +36 -12
  119. package/tools/theme-check.mjs +196 -1
  120. package/tools/tone-cue.mjs +108 -0
  121. package/tools/tts-cache.mjs +9 -3
  122. package/tools/tts-engines.mjs +100 -11
  123. package/tools/video-cache.mjs +93 -0
  124. package/tools/video-live.mjs +349 -0
  125. package/tools/video-options.mjs +11 -0
  126. package/tools/video.mjs +825 -117
  127. package/tools/viseme-fit.mjs +27 -0
  128. package/tools/viseme-match.mjs +77 -0
  129. package/tools/vocabulary.mjs +397 -0
  130. package/tools/voice-renumber.mjs +605 -0
  131. package/tools/voiceover-server.mjs +42 -11
  132. package/tools/voiceover.mjs +48 -20
  133. package/dist/build-info.json +0 -1
package/cli/record.mjs CHANGED
@@ -4,10 +4,10 @@
4
4
 
5
5
  // decklight narrate --mic — capture the deck's narration in YOUR voice.
6
6
  //
7
- // decklight narrate --mic <deck.html> [--port 8788] [--dir voiceover] [--no-open]
7
+ // decklight narrate --mic <deck.html> [--port 8788] [--dir voices/me] [--no-open]
8
8
  //
9
9
  // WHY THIS IS A COMMAND AND NOT JUST A KEY. The recorder itself lives in the
10
- // deck (V → Record this deck… → With your voice…): it has to, because the notes, the builds and the microphone are
10
+ // deck (V → My voice → Record…, or your voice's card): it has to, because the notes, the builds and the microphone are
11
11
  // all in the browser. But a browser will not open a microphone for a page it
12
12
  // loaded from `file://` — getUserMedia needs a secure context, and a local file
13
13
  // is not one, no matter how many times you click Allow. `http://127.0.0.1` IS
@@ -24,25 +24,48 @@
24
24
  // Deliberately NOT `decklight <deck>`: recording is not editing. Git is off,
25
25
  // no bridge is started, nothing is spent. You are reading your own notes aloud.
26
26
 
27
+ import { resolve } from 'node:path';
27
28
  import { editMain } from './edit.mjs';
29
+ import { deckFamily, tracksRoot } from '../tools/deck-family.mjs';
28
30
  import { openUrl } from './open-browser.mjs';
29
31
  import { argReader, firstPositional, isMain } from '../tools/args.mjs';
30
32
  import { runMain, wrongRecorder } from './util.mjs';
31
33
  import { exitWhenOrphaned } from './supervise.mjs';
32
34
 
33
- const USAGE = `usage: decklight narrate --mic <deck.html> [--port 8788] [--dir voiceover] [--slides a-b] [--no-open]
35
+ const USAGE = `usage: decklight narrate --mic <deck.html> [--port 8788] [--dir voices/me] [--slides a-b [--beats k-l]] [--takes slide|beat] [--countdown N] [--camera] [--remote] [--no-open]
34
36
  serves the deck over http://127.0.0.1 and opens it with the voice recorder up
35
37
 
36
38
  the deck reads you its notes one [click] beat at a time; → ends a beat, which
37
39
  both closes that file and reveals the next build — so your voice paces the
38
- deck exactly as it will when you present it
40
+ deck exactly as it will when you present it. A slide is one take by default:
41
+ → cuts the beat without stopping, and the recording runs on into the next.
42
+ E edits the words of the beat on screen, saved to the deck's notes, and
43
+ records it again
39
44
 
40
45
  --port N port to serve on (taken? moves to the next free one) [8788]
41
- --dir NAME folder to write into, relative to the deck [the deck's own
42
- narration.files, else voiceover]
46
+ --dir NAME folder to write into, relative to the deck [voices/me]
43
47
  --slides a-b re-record only this range (1-based, inclusive; "7" for one
44
48
  slide). Every other slide's files are left untouched, so a
45
49
  fluffed beat costs one slide and not the whole deck
50
+ --beats k-l with --slides naming one slide: re-record only these beats of it
51
+ ("3" for one). The other beats' files are left byte for byte, and
52
+ slide-NN.wav is rebuilt from all of them. The recorder's card can
53
+ also start from any beat: ← → pick it before you press Enter
54
+ --takes slide|beat one take per slide, read straight through, or per beat,
55
+ each counted in and retaken on its own
56
+ [per slide, every visit: the card's choice lasts the visit]
57
+ --countdown N seconds of count-in before each take, 0 for none (0-9)
58
+ [the recorder card's count-in: 3 s, 1 s or off, remembered]
59
+ --camera film your face too, beat by beat, beside the audio (the
60
+ recorder card's Camera option, for this visit; it is offered
61
+ only when the browser finds a camera). The deck plays it in the
62
+ character's medallion with your voice, or full screen where a
63
+ slide says data-face="full 1.4"; decklight video shows it too.
64
+ Needs ffmpeg to save it [the card's choice, remembered]
65
+ --remote the phone remote too, so recording needs no keyboard: its next
66
+ ends a beat and its retake redoes one, and a tap is not in the
67
+ take the way a keystroke is. The recorder's card shows the QR;
68
+ off this machine only the remote answers, as with decklight <deck> --remote
46
69
  --no-open don't launch a browser — print the URL and wait
47
70
 
48
71
  writes <dir>/slide-NN.wav (the whole slide) and <dir>/slide-NN-KK.wav (one
@@ -85,10 +108,14 @@ export function dirProblem(name) {
85
108
  * record against the slides your audience will see, at the build they will see
86
109
  * them at.
87
110
  */
88
- export function recordUrl(port, deckUrl, dir, slides) {
111
+ export function recordUrl(port, deckUrl, dir, slides, beats, countdown, takes, camera = false) {
89
112
  const q = ['record',
90
113
  ...(dir ? [`dir=${encodeURIComponent(dir)}`] : []),
91
- ...(slides ? [`slides=${encodeURIComponent(slides)}`] : [])].join('&');
114
+ ...(slides ? [`slides=${encodeURIComponent(slides)}`] : []),
115
+ ...(beats ? [`beats=${encodeURIComponent(beats)}`] : []),
116
+ ...(countdown != null ? [`countdown=${countdown}`] : []),
117
+ ...(takes ? [`takes=${takes}`] : []),
118
+ ...(camera ? ['camera'] : [])].join('&');
92
119
  return `http://127.0.0.1:${port}${deckUrl}?${q}`;
93
120
  }
94
121
 
@@ -111,6 +138,39 @@ export function slidesProblem(range) {
111
138
  return null;
112
139
  }
113
140
 
141
+ /**
142
+ * `3` or `3-4` with `--slides` naming one slide → null; anything else → a
143
+ * message. Beats are counted per slide, so a range of slides has no beat 3 to
144
+ * name. Whether the slide HAS that many beats is the runtime's to say (it
145
+ * reads the notes), and the card says it with the count.
146
+ */
147
+ export function beatsProblem(beats, slides) {
148
+ if (beats === undefined || beats === null) return null;
149
+ const m = /^(\d+)(?:-(\d+))?$/.exec(String(beats).trim());
150
+ if (!m) return `--beats must be k-l or a single beat number (got "${beats}")`;
151
+ const from = Number(m[1]);
152
+ const to = m[2] ? Number(m[2]) : from;
153
+ if (from < 1) return '--beats is 1-based — there is no beat 0';
154
+ if (to < from) return `--beats ${beats} ends before it starts`;
155
+ const one = /^(\d+)(?:-(\d+))?$/.exec(String(slides ?? '').trim());
156
+ if (!one || (one[2] && one[2] !== one[1])) {
157
+ return `--beats needs --slides to name one slide, since beats are counted per slide (--slides 6 --beats ${beats})`;
158
+ }
159
+ return null;
160
+ }
161
+
162
+ /** `--countdown`: whole seconds, 0 to 9; anything else → a message. */
163
+ export function countdownProblem(value) {
164
+ if (value === undefined || value === null) return null;
165
+ return /^\d$/.test(String(value).trim()) ? null : `--countdown is whole seconds from 0 (none) to 9 (got "${value}")`;
166
+ }
167
+
168
+ /** `--takes`: `slide` or `beat`; anything else → a message. */
169
+ export function takesProblem(value) {
170
+ if (value === undefined || value === null) return null;
171
+ return ['slide', 'beat'].includes(value) ? null : `--takes is slide or beat (got "${value}")`;
172
+ }
173
+
114
174
  export async function recordMain(args, { open = openUrl, out = process.stdout, onListen = null } = {}) {
115
175
  if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
116
176
  out.write(USAGE);
@@ -119,11 +179,14 @@ export async function recordMain(args, { open = openUrl, out = process.stdout, o
119
179
  const { opt } = argReader(args);
120
180
  const dir = opt('--dir');
121
181
  const slides = opt('--slides');
122
- for (const bad of [dirProblem(dir), slidesProblem(slides)]) {
182
+ const beats = opt('--beats');
183
+ const countdown = opt('--countdown');
184
+ const takes = opt('--takes');
185
+ for (const bad of [dirProblem(dir), slidesProblem(slides), beatsProblem(beats, slides), countdownProblem(countdown), takesProblem(takes)]) {
123
186
  if (bad) { process.stderr.write(`decklight narrate --mic: ${bad}\n`); return 2; }
124
187
  }
125
188
 
126
- const deck = firstPositional(args, ['--dir', '--slides', '--port']);
189
+ const deck = firstPositional(args, ['--dir', '--slides', '--beats', '--countdown', '--takes', '--port']);
127
190
  // Before the server, not after: this used to serve the YAML file, print a
128
191
  // URL and open a browser on it, with no error anywhere.
129
192
  const mixedUp = wrongRecorder('narrate', deck);
@@ -131,7 +194,10 @@ export async function recordMain(args, { open = openUrl, out = process.stdout, o
131
194
  let started;
132
195
  // `--no-git`, always: recording is not editing, and a take that happens to
133
196
  // coincide with the autocommit cadence has no business creating a commit.
134
- await editMain([deck, '--port', String(opt('--port', 8788)), '--no-git'], {
197
+ // `--remote` passes through untouched: the edit server owns the LAN
198
+ // listener, the token and the line that prints its URL (NO_TRUST#REMOTE).
199
+ const remote = args.includes('--remote');
200
+ await editMain([deck, '--port', String(opt('--port', 8788)), '--no-git', ...(remote ? ['--remote'] : [])], {
135
201
  // the same seam editMain offers, passed through: this server outlives the
136
202
  // call (it is the whole point), so a caller that is not a terminal — a
137
203
  // test — needs a handle to close it
@@ -141,11 +207,16 @@ export async function recordMain(args, { open = openUrl, out = process.stdout, o
141
207
  // missing or outside the served root — say nothing on top of it.
142
208
  if (!started) return process.exitCode ?? 1;
143
209
 
144
- const url = recordUrl(started.port, started.deckUrl, dir, slides);
210
+ const url = recordUrl(started.port, started.deckUrl, dir, slides, beats, countdown == null ? null : Number(countdown), takes, args.includes('--camera'));
145
211
  out.write(`decklight narrate --mic on ${url}\n`);
146
- out.write(' V → Record this deck… → With your voice… opens the recorder · → ends a beat and reveals the next build · Esc stops\n');
147
- out.write(` files land in ${dir ?? "the deck's narration folder"}, next to the deck.`
148
- + `${slides ? ` Only slide${/-/.test(slides) ? 's' : ''} ${slides}.` : ''} Ctrl-C when you are done.\n`);
212
+ out.write(' V → My voice opens the recorder again · → ends a beat and reveals the next build · Esc stops\n');
213
+ if (remote) out.write(' the phone remote is on: scan the QR on the recorder\'s card; next ends a beat, retake redoes it\n');
214
+ if (args.includes('--camera')) out.write(' the camera is on: your face is filmed with every beat, beside its audio\n');
215
+ // `voices/me`, or `voices-fr/me` for the French of a deck (PRESENTING_VOICE)
216
+ out.write(` files land in ${dir ?? `${tracksRoot(deckFamily(resolve(deck)))}/me`}, next to the deck.`
217
+ + `${dir ? '' : ' Recording again refreshes it.'}`
218
+ + `${slides ? ` Only slide${/-/.test(slides) ? 's' : ''} ${slides}${beats ? `, beat${/-/.test(beats) ? 's' : ''} ${beats}` : ''}.` : ''}`
219
+ + ' Ctrl-C when you are done.\n');
149
220
  if (!args.includes('--no-open')) await open(url, { out, what: url });
150
221
  return 0;
151
222
  }
package/cli/remote.mjs CHANGED
@@ -16,7 +16,9 @@ import { escapeHtml, isLoopback, sseChannel } from './serve.mjs';
16
16
  /**
17
17
  * The phone controller page (#39): a clicker, NOT a second screen — SPEC NON_GOALS
18
18
  * rules out multiplex/follow-along, so this renders no slides, only two big
19
- * targets and the position readout. Self-contained by necessity: the phone is
19
+ * targets and the position readout. While the voice recorder is capturing a
20
+ * beat (`narrate --mic --remote`, #848) prev gives its place to retake and the
21
+ * readout says which beat. Self-contained by necessity: the phone is
20
22
  * off-loopback, and every asset it could reference is one more thing the token
21
23
  * would have to guard. It carries the token it was opened with into both its
22
24
  * POSTs and its SSE subscription.
@@ -37,6 +39,12 @@ export function remoteControllerHtml(deckName) {
37
39
  .deck { font-weight: 400; opacity: .6; font-size: .8rem; }
38
40
  .pos { font-size: 1.6rem; font-variant-numeric: tabular-nums; }
39
41
  main { flex: 1; display: grid; grid-template-rows: 1fr 1fr; gap: .6rem; padding: .6rem; }
42
+ .rec { display: none; color: #ff6b6b; font-size: .85rem; letter-spacing: .04em; }
43
+ #retake { display: none; }
44
+ body.recording .rec { display: block; }
45
+ body.recording #prev { display: none; }
46
+ body.recording #retake { display: block; background: #3a2226; }
47
+ body.recording header { border-bottom-color: #5a2a2f; }
40
48
  button { font: inherit; font-size: 2rem; border: 0; border-radius: 1rem; color: #eee;
41
49
  background: #26262b; touch-action: manipulation; }
42
50
  button:active { background: #3a3a44; }
@@ -46,17 +54,21 @@ export function remoteControllerHtml(deckName) {
46
54
  <body>
47
55
  <header>
48
56
  <div class="deck">${escapeHtml(deckName)}</div>
57
+ <div class="rec" id="rec">● recording</div>
49
58
  <div class="pos" id="pos">—</div>
50
59
  </header>
51
60
  <main>
52
61
  <button id="next" aria-label="next">▼ next</button>
53
62
  <button id="prev" aria-label="previous">▲ prev</button>
63
+ <button id="retake" aria-label="retake this beat">↺ retake</button>
54
64
  </main>
55
65
  <footer id="state">connecting…</footer>
56
66
  <script>
57
67
  var t = new URLSearchParams(location.search).get('t') || '';
58
68
  var q = t ? '?t=' + encodeURIComponent(t) : '';
59
69
  var pos = document.getElementById('pos');
70
+ var rec = document.getElementById('rec');
71
+ var next = document.getElementById('next');
60
72
  var state = document.getElementById('state');
61
73
  function send(key) {
62
74
  return fetch('/deck/remote/key' + q, {
@@ -64,11 +76,21 @@ export function remoteControllerHtml(deckName) {
64
76
  body: JSON.stringify({ key: key }),
65
77
  }).catch(function () { state.textContent = 'offline'; });
66
78
  }
67
- document.getElementById('next').onclick = function () { send('next'); };
79
+ next.onclick = function () { send('next'); };
68
80
  document.getElementById('prev').onclick = function () { send('prev'); };
81
+ document.getElementById('retake').onclick = function () { send('retake'); };
69
82
  var es = new EventSource('/deck/remote/events' + q);
70
83
  es.addEventListener('pos', function (e) {
71
- try { var p = JSON.parse(e.data); pos.textContent = p.i + ' / ' + p.n; } catch (err) {}
84
+ try {
85
+ var p = JSON.parse(e.data);
86
+ // the voice recorder is capturing a beat: say which, so the phone is
87
+ // usable without looking at the laptop, and offer retake in prev's place
88
+ var r = p.rec;
89
+ document.body.classList.toggle('recording', !!r);
90
+ rec.textContent = r ? '● recording · beat ' + r.beat + ' of ' + r.of : '● recording';
91
+ pos.textContent = r ? 'slide ' + r.slide + ' / ' + p.n : p.i + ' / ' + p.n;
92
+ next.textContent = r ? '▼ next beat' : '▼ next';
93
+ } catch (err) {}
72
94
  });
73
95
  es.onopen = function () { state.textContent = 'connected'; };
74
96
  es.onerror = function () { state.textContent = 'reconnecting…'; };
@@ -123,7 +145,9 @@ export function createRemoteRelay({ deckName, token, remoteUrl, relayToDeck, dec
123
145
  }
124
146
  if (req.method === 'POST' && url.pathname === '/deck/remote/key') {
125
147
  const { key } = JSON.parse(body);
126
- if (key !== 'next' && key !== 'prev') throw new Error('bad payload');
148
+ // `retake` means something only while the voice recorder is capturing
149
+ // a beat (#848); the deck ignores it anywhere else
150
+ if (key !== 'next' && key !== 'prev' && key !== 'retake') throw new Error('bad payload');
127
151
  // relayed as a named event on the stream the deck ALREADY listens to —
128
152
  // no second socket, no WebSockets anywhere in this codebase
129
153
  relayToDeck('remote', { key });
@@ -137,9 +161,11 @@ export function createRemoteRelay({ deckName, token, remoteUrl, relayToDeck, dec
137
161
  if (!isLoopback(req.socket?.remoteAddress)) {
138
162
  return json(403, { ok: false, error: 'position reports come from the deck, not the phone' });
139
163
  }
140
- const { i, n } = JSON.parse(body);
164
+ const { i, n, rec = null } = JSON.parse(body);
141
165
  if (!Number.isInteger(i) || !Number.isInteger(n)) throw new Error('bad payload');
142
- lastPos = { i, n };
166
+ // the beat the voice recorder is capturing, or null (#848)
167
+ if (rec !== null && !['slide', 'beat', 'of'].every((k) => Number.isInteger(rec?.[k]))) throw new Error('bad payload');
168
+ lastPos = { i, n, rec: rec && { slide: rec.slide, beat: rec.beat, of: rec.of } };
143
169
  pushPos();
144
170
  return json(200, { ok: true });
145
171
  }
@@ -0,0 +1,265 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The slide-text writing tools (SPEC PRESENTING_WRITING): the words ON the
6
+ * slide, rewritten by the locally installed agent and reviewed before they
7
+ * land, the way the script rewrites are (cli/enhance.mjs, #907).
8
+ *
9
+ * THE AGENT SEES TEXT RUNS, NOT MARKUP. A slide's visible text is cut into
10
+ * runs, the text between tags outside the notes, code, scripts, styles and
11
+ * SVG, numbered, and the agent is asked for the same numbered runs back.
12
+ * Decklight puts them into the slide where they came from. So a tool can
13
+ * only change words: the slide's structure, its builds, attributes, styles
14
+ * and classes cannot move, which is what makes it safe to run on a whole
15
+ * deck. An answer with markup in it, a run skipped or emptied, or a change a
16
+ * tool does not allow (a typo fix that rewords, a tighten that lengthens)
17
+ * fails its check, and that slide is left exactly as it was, with why.
18
+ *
19
+ * Four tools (TOOLS): `tighten` (shorter, same meaning), `typos` (spelling,
20
+ * grammar and punctuation, nothing else), `match` (reworded to agree with the
21
+ * speaker notes, which are sent along) and `custom` (one instruction of the
22
+ * author's, with the same check as match).
23
+ */
24
+
25
+ import { agentAsk, agentUnavailable, detectAgents } from './agents.mjs';
26
+ import { ask, unwrapAnswer, ENHANCE_TIMEOUT_MS, ENHANCE_CONCURRENCY } from './enhance.mjs';
27
+ import { sectionBodies, sectionCloseIndex, isHiddenSection, locateSlide, cleanNotes, NOTES_ASIDE } from '../tools/deck-html.mjs';
28
+
29
+ /** Where the slide's text stops being the slide's: containers whose insides are not words to rewrite. */
30
+ const SKIP = /<!--[\s\S]*?-->|<(script|style|pre|code|svg|aside|textarea|kbd|samp)\b[^>]*>[\s\S]*?<\/\1\s*>/gi;
31
+ const TAG = /<[^>]+>/g;
32
+
33
+ const decode = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|#39|apos|nbsp);/gi, (m, b) => {
34
+ const low = b.toLowerCase();
35
+ if (low === 'amp') return '&';
36
+ if (low === 'lt') return '<';
37
+ if (low === 'gt') return '>';
38
+ if (low === 'quot') return '"';
39
+ if (low === '#39' || low === 'apos') return "'";
40
+ if (low === 'nbsp') return ' ';
41
+ const code = low.startsWith('#x') ? parseInt(low.slice(2), 16) : parseInt(low.slice(1), 10);
42
+ return Number.isFinite(code) ? String.fromCodePoint(code) : m;
43
+ });
44
+ const encode = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
45
+
46
+ /**
47
+ * A slide's visible text as numbered runs: `[{ n, start, end, text }]`, each
48
+ * a stretch of text between tags with at least one word in it, `start`/`end`
49
+ * its place in `content` (the section's inside), `text` decoded. Pure.
50
+ */
51
+ export function textRuns(content) {
52
+ const src = String(content ?? '');
53
+ const runs = [];
54
+ // what is skipped is blanked to a mark, same length, so offsets stay the
55
+ // offsets and a run that touches it is not a run; then the text is walked
56
+ // by tag boundaries, so a run never crosses a tag
57
+ const skipped = src.replace(SKIP, (x) => '\u0000'.repeat(x.length));
58
+ const bounds = [];
59
+ for (const m of skipped.matchAll(TAG)) bounds.push([m.index, m.index + m[0].length]);
60
+ let at = 0;
61
+ for (const [s, e] of [...bounds, [src.length, src.length]]) {
62
+ const piece = skipped.slice(at, s);
63
+ if (/\S/.test(piece) && !piece.includes('\u0000')) {
64
+ const lead = piece.match(/^\s*/)[0].length, trail = piece.match(/\s*$/)[0].length;
65
+ const text = decode(piece.slice(lead, piece.length - trail));
66
+ if (/[\p{L}\p{N}]/u.test(text)) runs.push({ n: runs.length + 1, start: at + lead, end: at + piece.length - trail, text });
67
+ }
68
+ at = e;
69
+ }
70
+ return runs;
71
+ }
72
+
73
+ /** `content` with each run's text replaced by `texts[n]` (encoded), from the back so offsets hold. Pure. */
74
+ export function withRuns(content, runs, texts) {
75
+ let out = String(content ?? '');
76
+ for (const r of [...runs].sort((a, b) => b.start - a.start)) {
77
+ const t = texts.get?.(r.n) ?? texts[r.n];
78
+ if (typeof t !== 'string' || t === r.text) continue;
79
+ out = out.slice(0, r.start) + encode(t) + out.slice(r.end);
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /** The runs as the agent is shown them: one per line, numbered. */
85
+ export const runsText = (runs) => runs.map((r) => `${r.n}: ${r.text.replace(/\s*\n\s*/g, ' ')}`).join('\n');
86
+
87
+ /** The agent's answer as a map n → text; a line that is not `n: text` is ignored. Pure. */
88
+ export function parseRuns(answer) {
89
+ const out = new Map();
90
+ for (const line of unwrapAnswer(answer).split('\n')) {
91
+ const m = /^\s*(\d+)\s*[:.)]\s?(.*)$/.exec(line);
92
+ if (m) out.set(Number(m[1]), m[2].trim());
93
+ }
94
+ return out;
95
+ }
96
+
97
+ const RULES = `# About this text
98
+
99
+ These are the text runs of one presentation slide, the words the audience reads, numbered in reading order. Each run is one stretch of text between the slide's tags; the layout, builds and styling around them belong to the presentation software and are not shown.
100
+
101
+ Answer with the same numbered runs, one per line, in the form \`N: text\`, every number present and in order. A run you leave unchanged, repeat exactly as it is. Never merge, split, reorder, add or drop a run. No markup, no quotes around a run, no code fences, no commentary before or after. Keep the language of the original.`;
102
+
103
+ /** The four tools: what each asks for, and how its answer is checked. */
104
+ export const TOOLS = {
105
+ tighten: {
106
+ label: 'tighten', done: 'tightened', what: 'text: tightened',
107
+ ask: 'Make each run shorter while keeping its meaning, its voice and its terms. Fewer words, not fewer points: cut filler, hedges and repetition, prefer the plain word. A run that is already tight stays exactly as it is. Never make a run longer.',
108
+ },
109
+ typos: {
110
+ label: 'fix typos and grammar', done: 'fixed', what: 'text: typos and grammar',
111
+ ask: 'Fix spelling, grammar, punctuation and capitalisation only. Change nothing else: not the wording, not the order of the words, not the terms, not the language. A run with nothing wrong stays exactly as it is.',
112
+ },
113
+ match: {
114
+ label: 'match the script', done: 'matched to the script', what: 'text: matched to the script',
115
+ ask: 'The slide\'s speaker notes, what the presenter says while this slide is on screen, are given under # Notes. Reword the runs so they agree with the notes: the same terms, the same claims, the same order of ideas. Keep each run about as long as it is; a run that already agrees stays exactly as it is.',
116
+ },
117
+ custom: {
118
+ label: 'custom instruction', done: 'rewritten', what: 'text: rewritten',
119
+ ask: null, // the author's own words (`instruction`)
120
+ },
121
+ };
122
+
123
+ /** The whole ask for one slide's runs. */
124
+ export function rewritePrompt(tool, runs, { instruction = '', notes = '' } = {}) {
125
+ const t = TOOLS[tool] ?? TOOLS.custom;
126
+ const task = t.ask ?? `Apply this instruction to every run it applies to, and leave the others exactly as they are: ${String(instruction).trim()}`;
127
+ return `# Instructions\n\n${task}\n\n${RULES}${tool === 'match' && notes ? `\n\n# Notes\n\n${notes}` : ''}\n\n# Runs\n\n${runsText(runs)}`;
128
+ }
129
+
130
+ /** Character edit distance, for the typo check — the runs are short. */
131
+ export function editDistance(a, b) {
132
+ const m = a.length, n = b.length;
133
+ if (!m) return n;
134
+ if (!n) return m;
135
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
136
+ for (let i = 1; i <= m; i++) {
137
+ const cur = [i];
138
+ for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
139
+ prev = cur;
140
+ }
141
+ return prev[n];
142
+ }
143
+ const words = (s) => String(s).trim().split(/\s+/).filter(Boolean).length;
144
+
145
+ /**
146
+ * Why an answer cannot be written, or null: every run answered, none
147
+ * emptied, no markup, and the tool's own rule — a typo fix that changed more
148
+ * than a few characters per word reworded; a tighten that lengthened a run;
149
+ * a match or a custom rewrite that doubled or halved the slide. Pure.
150
+ */
151
+ export function rewriteProblem(tool, runs, answers) {
152
+ if (!answers?.size) return 'the agent answered nothing the check could read';
153
+ for (const r of runs) {
154
+ if (!answers.has(r.n)) return `the agent skipped run ${r.n}`;
155
+ const a = answers.get(r.n);
156
+ if (!a.trim()) return `the agent emptied run ${r.n}`;
157
+ if (/[<>]/.test(a)) return `the agent answered run ${r.n} with markup`;
158
+ if (tool === 'typos' && editDistance(r.text, a) > 3 * words(r.text) + 2) return `the agent reworded run ${r.n} — a typo fix changes a few characters, not the words`;
159
+ if (tool === 'tighten' && a.length > r.text.length + 2) return `the agent made run ${r.n} longer`;
160
+ }
161
+ const before = runs.reduce((n, r) => n + words(r.text), 0);
162
+ const after = runs.reduce((n, r) => n + words(answers.get(r.n)), 0);
163
+ if (tool !== 'typos' && tool !== 'tighten') {
164
+ if (after > 2.5 * Math.max(1, before)) return 'the agent\'s answer is far longer than the slide — commentary, not a rewrite';
165
+ if (after < 0.4 * before) return 'the agent\'s answer is far shorter than the slide — points were dropped';
166
+ }
167
+ return null;
168
+ }
169
+
170
+ /** A section body's inside: from after its opening tag to its own close. */
171
+ function insideOf(body) {
172
+ const open = body.indexOf('>');
173
+ const close = sectionCloseIndex(body);
174
+ if (open < 0 || close < 0 || close < open) return null;
175
+ return { from: open + 1, to: close };
176
+ }
177
+
178
+ /**
179
+ * The slides a tool can work on: `[{ slide, runs, notes }]` for every shown
180
+ * section with text (or those in `only`). Pure.
181
+ */
182
+ export function rewritable(html, only = null) {
183
+ const bodies = sectionBodies(html);
184
+ return bodies.flatMap((body, i) => {
185
+ const slide = i + 1;
186
+ if (only && !only.includes(slide)) return [];
187
+ if (isHiddenSection(body)) return [];
188
+ const at = insideOf(body);
189
+ if (!at) return [];
190
+ const runs = textRuns(body.slice(at.from, at.to));
191
+ if (!runs.length) return [];
192
+ const aside = NOTES_ASIDE.exec(body);
193
+ return [{ slide, runs, notes: aside ? cleanNotes(aside[1]) : '' }];
194
+ });
195
+ }
196
+
197
+ /**
198
+ * One slide's runs, rewritten: the agent is asked, its answer parsed and
199
+ * checked. Resolves to `{ ok, texts }` (a Map n → text) or `{ ok: false, why }`.
200
+ */
201
+ export async function rewriteRuns(tool, runs, {
202
+ instruction = '', notes = '', agent = null, cwd = process.cwd(), env = process.env, timeoutMs = ENHANCE_TIMEOUT_MS,
203
+ resolveAgent = agentAsk, exec = ask, signal = null,
204
+ } = {}) {
205
+ const cmd = resolveAgent(agent, rewritePrompt(tool, runs, { instruction, notes }), { env });
206
+ if (!cmd) return { ok: false, why: agentUnavailable(agent, detectAgents({ env })) };
207
+ const out = await exec(cmd, cwd, timeoutMs, signal);
208
+ if (signal?.aborted) return { ok: false, why: 'stopped' };
209
+ if (out == null) return { ok: false, why: 'the agent did not answer in time' };
210
+ const texts = parseRuns(out);
211
+ const why = rewriteProblem(tool, runs, texts);
212
+ if (why) return { ok: false, why };
213
+ const changed = runs.some((r) => texts.get(r.n) !== r.text);
214
+ return { ok: true, texts, changed };
215
+ }
216
+
217
+ /**
218
+ * The answers written into `html`: each slide that passed and changed, and
219
+ * only if its runs still read exactly as they did when the agent was asked.
220
+ * Returns `{ html, stale }`.
221
+ */
222
+ export function applyRewritten(html, answers) {
223
+ let out = html;
224
+ const stale = [];
225
+ for (const a of answers) {
226
+ if (!a.ok || !a.changed) continue;
227
+ const { parts, idx } = locateSlide(out, a.slide);
228
+ const body = parts[idx];
229
+ const at = insideOf(body);
230
+ const now = at ? textRuns(body.slice(at.from, at.to)) : [];
231
+ if (!at || now.length !== a.runs.length || now.some((r, i) => r.text !== a.runs[i].text)) { stale.push(a.slide); continue; }
232
+ parts[idx] = body.slice(0, at.from) + withRuns(body.slice(at.from, at.to), now, a.texts) + body.slice(at.to);
233
+ out = parts.join('');
234
+ }
235
+ return { html: out, stale };
236
+ }
237
+
238
+ /**
239
+ * Ask the agent to run `tool` over `slides` (1-based, or null for every shown
240
+ * slide with text) of the deck in `html`. Resolves to `{ html, results,
241
+ * answers }` like enhanceDeck: one `{ slide, ok, changed, why }` per slide,
242
+ * and the raw answers for a caller that applies them to a newer copy.
243
+ */
244
+ export async function rewriteDeck(html, tool, slides = null, {
245
+ instruction = '', agent = null, cwd = process.cwd(), env = process.env, timeoutMs = ENHANCE_TIMEOUT_MS,
246
+ concurrency = ENHANCE_CONCURRENCY, resolveAgent = agentAsk, exec = ask, onSlide = () => {}, signal = null,
247
+ } = {}) {
248
+ if (!resolveAgent(agent, 'x', { env })) throw new Error(agentUnavailable(agent, detectAgents({ env })));
249
+ const todo = rewritable(html, slides);
250
+ const answers = [];
251
+ let next = 0, finished = 0;
252
+ const worker = async () => {
253
+ while (next < todo.length && !signal?.aborted) {
254
+ const { slide, runs, notes } = todo[next++];
255
+ const a = await rewriteRuns(tool, runs, { instruction, notes, agent, cwd, env, timeoutMs, resolveAgent, exec, signal });
256
+ const r = { slide, ok: a.ok, changed: !!(a.ok && a.changed), ...(a.ok ? {} : { why: a.why }) };
257
+ answers.push({ ...r, runs, texts: a.texts ?? null });
258
+ onSlide({ ...r, done: ++finished, of: todo.length });
259
+ }
260
+ };
261
+ await Promise.all(Array.from({ length: Math.min(concurrency, todo.length) }, worker));
262
+ answers.sort((a, b) => a.slide - b.slide);
263
+ const results = answers.map(({ runs, texts, ...r }) => r);
264
+ return { html: applyRewritten(html, answers).html, results, answers };
265
+ }