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
@@ -0,0 +1,458 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * decklight translate — a deck in several languages (SPEC TRANSLATE_CLI).
7
+ *
8
+ * decklight translate <deck.html> [--to fr,es] [--slides 3,5-8] [--agent <name>] [--agent-model <m>]
9
+ * [--status | --check] [--dry-run] [--no-agent] [--discard-structure]
10
+ *
11
+ * DECKLIGHT DOES NOT TRANSLATE, AN AGENT DOES, AND DECKLIGHT WRITES THE FILE.
12
+ * The agent is the one the writing tools use, run read-only, one ask per
13
+ * slide; it is shown numbered pieces of text and answers numbered pieces of
14
+ * text, and only an answer that passes `translateProblem` is written. The
15
+ * file it lands in is the source with its words replaced (cli/translate-core.mjs),
16
+ * so an agent cannot move, drop or restyle anything.
17
+ *
18
+ * What is behind is a string comparison against the record and never a
19
+ * question for a model: `--status`, `--check` and `--no-agent` start none.
20
+ */
21
+
22
+ import { existsSync, readFileSync } from 'node:fs';
23
+ import { basename, dirname, resolve } from 'node:path';
24
+ import { agentAsk, agentUnavailable, detectAgents } from './agents.mjs';
25
+ import { ask, ENHANCE_TIMEOUT_MS, ENHANCE_CONCURRENCY, parseSlides } from './enhance.mjs';
26
+ import { parseRuns } from './rewrite.mjs';
27
+ import { deckConfig, withConfigKeys } from './runtime-link.mjs';
28
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
29
+ import { writeFileAtomic } from '../tools/atomic-write.mjs';
30
+ import { sectionBodies } from '../tools/deck-html.mjs';
31
+ import { knownLanguages, languageFiles, resolveSource, slidesPhrase } from './translate-files.mjs';
32
+ import { runMain } from './util.mjs';
33
+ import { slideRenumber } from './commit-split.mjs';
34
+ import { applyPlans, planSteps, voiceFolders } from '../tools/voice-renumber.mjs';
35
+ import {
36
+ deckUnits, emptyRecord, formatRecord, languageName, languageStatus, matchRecord,
37
+ nextRecord, parseRecord, readBack, renderTranslation, sourceLang, withAlternates,
38
+ } from './translate-core.mjs';
39
+
40
+ export const USAGE = `usage: decklight translate <deck.html> [--to fr,es] [--slides 3,5-8] [--agent <name>] [--agent-model <m>]
41
+ [--status | --check] [--dry-run] [--no-agent] [--discard-structure]
42
+ writes the deck in another language beside it: talk.fr.html, made from talk.html with its words
43
+ replaced, and talk.fr.translation.json, the record of what each piece was translated from.
44
+ Commit all three. Run it again after editing talk.html and only what changed is translated
45
+
46
+ --to fr,es the languages (BCP 47 tags) [every language the deck's "languages" names]
47
+ a language named for the first time is added there
48
+ --slides 3,5-8 ask the agent about these slides only; the rest catch up without it
49
+ --agent NAME the coding agent that translates [the one the writing tools use]
50
+ --agent-model M its model, for this run
51
+ --status what is behind, per language. Starts no agent and writes nothing
52
+ --check the same, and exit 1 when any language is behind (for CI)
53
+ --dry-run ask the agent and print what would change, write nothing
54
+ --no-agent regenerate from the record alone: the structure catches up, the
55
+ words that need a model stay behind and are counted
56
+ --discard-structure overwrite a translation that was changed in more than its words
57
+
58
+ fixing a translation is editing the translation: a sentence you change in talk.fr.html is
59
+ kept, and never re-asked while its source stands. The slides' text and notes are sent to
60
+ the agent, and most agents are cloud services
61
+ `;
62
+
63
+ export { knownLanguages, languageFiles, resolveSource } from './translate-files.mjs';
64
+
65
+ const VALUE_FLAGS = ['--to', '--slides', '--agent', '--agent-model', '--wait'];
66
+
67
+ /** Run started by the edit server: "stop" on stdin stops it after the slides in flight (TRANSLATE_PANEL). */
68
+ function stopOnInput(controller) {
69
+ process.stdin.setEncoding('utf8');
70
+ process.stdin.on('data', (s) => { if (/\bstop\b/.test(s)) controller.abort(); });
71
+ process.stdin.on('error', () => {});
72
+ process.stdin.unref?.();
73
+ }
74
+ const TAG = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i;
75
+
76
+ /** Is `tag` a language this command can name a file after? */
77
+ export function tagProblem(tag) {
78
+ if (!TAG.test(tag)) return `"${tag}" is not a language tag (fr, pt-BR, zh-Hans)`;
79
+ try { Intl.getCanonicalLocales(tag); } catch { return `"${tag}" is not a language tag (fr, pt-BR, zh-Hans)`; }
80
+ return null;
81
+ }
82
+
83
+ // ── the ask ──────────────────────────────────────────────────────────────────
84
+
85
+ const KIND_LABEL = { run: 'text', beat: 'notes', attr: 'attribute', label: 'diagram', title: 'title' };
86
+ const PARA = ' ¶ ';
87
+ const oneLine = (u) => (u.kind === 'beat' ? u.text.split('\n\n').join(PARA) : u.text.replace(/\s*\n\s*/g, ' '));
88
+ const fromLine = (kind, s) => (kind === 'beat' ? s.split(/\s*¶\s*/).map((p) => p.trim()).filter(Boolean).join('\n\n') : s.trim());
89
+
90
+ /** The script a language is written in, as a regex over letters, or null when no check is made for it. */
91
+ export function scriptRe(lang) {
92
+ let script;
93
+ try { script = new Intl.Locale(lang).maximize().script; } catch { return null; }
94
+ const P = (...names) => new RegExp(`[${names.map((n) => `\\p{Script=${n}}`).join('')}]`, 'u');
95
+ return ({
96
+ Latn: P('Latin'), Cyrl: P('Cyrillic'), Grek: P('Greek'), Arab: P('Arabic'), Hebr: P('Hebrew'),
97
+ Deva: P('Devanagari'), Thai: P('Thai'), Hang: P('Hangul'), Kore: P('Hangul', 'Han'),
98
+ Hans: P('Han'), Hant: P('Han'), Jpan: P('Han', 'Hiragana', 'Katakana'), Beng: P('Bengali'),
99
+ Taml: P('Tamil'), Geor: P('Georgian'), Armn: P('Armenian'), Ethi: P('Ethiopic'),
100
+ })[script] ?? null;
101
+ }
102
+ const scriptOf = (lang) => { try { return new Intl.Locale(lang).maximize().script; } catch { return null; } };
103
+
104
+ /** The whole ask for one slide's pieces. */
105
+ export function translatePrompt(units, { from, to, title = '', glossary = {}, done = [], limits = null } = {}) {
106
+ const fromName = from ? `${languageName(from, { in: 'en' })} (${from})` : 'the language it is written in';
107
+ const toName = `${languageName(to, { in: 'en' })} (${to})`;
108
+ const terms = Object.entries(glossary ?? {});
109
+ const changed = units.map((u, k) => ({ u, n: k + 1 })).filter(({ u }) => u.status === 'changed' && u.previous);
110
+ return [
111
+ '# Instructions',
112
+ '',
113
+ `Translate the numbered pieces of one presentation slide from ${fromName} into ${toName}.`,
114
+ '',
115
+ 'Each piece is one stretch of text: [text] is words on the slide, [notes] is what the presenter says aloud while the slide is on screen (write it to be spoken), [attribute] is a short label such as an image description or a chapter name, [diagram] is a word drawn in a diagram or a chart, [title] is the deck\'s title. Translate each piece on its own; never merge, split, reorder, add or drop one.',
116
+ '',
117
+ 'Answer with the same numbered pieces, one per line, in the form `N: text`, every number present and in order. No markup, no quotes around a piece, no code fences, no commentary before or after.',
118
+ '',
119
+ 'Keep every bracketed direction such as [pause], [long pause] or [whispers] exactly as written, where it falls in the sentence: it is an instruction to the voice, not words. ¶ marks a paragraph break: keep each one. Product names, commands, code, file names and URLs stay as they are. Keep each piece about as long as it is: the slide\'s text has to fit where it is.',
120
+ ...(terms.length ? ['', '# Glossary', '', 'Translate these terms this way, every time (a term given as itself stays as it is):', '', ...terms.map(([a, b]) => `- ${a} → ${b}`)] : []),
121
+ ...(title ? ['', '# The deck', '', `Title: ${title}`] : []),
122
+ ...(done.length ? ['', '# Already translated on this slide', '', 'Agree with these:', '', ...done.map((u) => `- ${oneLine(u)} → ${u.kind === 'beat' ? u.target.split('\n\n').join(PARA) : u.target}`)] : []),
123
+ ...(changed.length ? ['', '# Previous translations', '', 'These pieces were translated before and their source has since been reworded. Change the previous translation only as much as the rewording needs:', '',
124
+ ...changed.map(({ u, n }) => `${n}: was "${oneLine({ ...u, text: u.previous.source })}", translated "${u.kind === 'beat' ? u.previous.target.split('\n\n').join(PARA) : u.previous.target}"`)] : []),
125
+ ...(limits ? ['', '# Too long', '', 'Your last translation of this slide did not fit on it. Answer again with shorter text, keeping the meaning, each piece within the characters given.'] : []),
126
+ '',
127
+ '# Pieces',
128
+ '',
129
+ ...units.map((u, k) => `${k + 1} [${KIND_LABEL[u.kind] ?? u.kind}${limits?.[k] ? `, at most ${limits[k]} characters` : ''}]: ${oneLine(u)}`),
130
+ ].join('\n');
131
+ }
132
+
133
+ const tagsOf = (s) => (String(s).match(/\[[^\]\n]{1,40}\]/g) ?? []).map((t) => t.toLowerCase().replace(/\s+/g, ' ')).sort().join('|');
134
+ const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
135
+
136
+ /**
137
+ * Why an answer cannot be written, or null (SPEC TRANSLATE_CLI): every piece
138
+ * answered and none emptied, no markup, a piece's bracketed directions and
139
+ * paragraphs all kept, every glossary term as the glossary says, and the
140
+ * answer in the target language's script where the source's differs. Pure.
141
+ */
142
+ export function translateProblem(units, answers, { from = null, to, glossary = {}, limits = null } = {}) {
143
+ if (!answers?.size) return 'the agent answered nothing the check could read';
144
+ for (const [k, u] of units.entries()) {
145
+ const n = k + 1;
146
+ if (!answers.has(n)) return `the agent skipped piece ${n}`;
147
+ const a = answers.get(n);
148
+ if (!a.trim()) return `the agent emptied piece ${n}`;
149
+ if (/[<>]/.test(a)) return `the agent answered piece ${n} with markup`;
150
+ if (tagsOf(oneLine(u)) !== tagsOf(a)) return `piece ${n} lost or changed a bracketed direction such as [pause]`;
151
+ if (u.kind === 'beat' && (oneLine(u).match(/¶/g) ?? []).length !== (a.match(/¶/g) ?? []).length) return `piece ${n} lost a paragraph break`;
152
+ if (limits?.[k] && a.trim().length > limits[k]) return `piece ${n} is still longer than ${limits[k]} characters`;
153
+ for (const [term, target] of Object.entries(glossary ?? {})) {
154
+ if (!term || !target) continue;
155
+ const hit = new RegExp(`(?<!\\p{L})${escRe(term)}(?!\\p{L})`, 'iu').test(u.text);
156
+ if (hit && !a.toLowerCase().includes(String(target).toLowerCase())) return `piece ${n}: the glossary says "${term}" is "${target}"`;
157
+ }
158
+ }
159
+ const want = scriptRe(to);
160
+ if (want && scriptOf(to) !== scriptOf(from ?? 'en')) {
161
+ const letters = [...answers.values()].join(' ');
162
+ if (/\p{L}/u.test(letters) && !want.test(letters)) return `the answer is not written in ${languageName(to, { in: 'en' })}'s script`;
163
+ }
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * One slide's pieces, translated: the agent is asked, its answer parsed and
169
+ * checked. Resolves to `{ ok, texts: [text] }` or `{ ok: false, why }`.
170
+ */
171
+ export async function translateUnits(units, opts) {
172
+ const { agent = null, model, cwd = process.cwd(), env = process.env, timeoutMs = ENHANCE_TIMEOUT_MS, resolveAgent = agentAsk, exec = ask, signal = null } = opts;
173
+ const cmd = resolveAgent(agent, translatePrompt(units, opts), { env, model });
174
+ if (!cmd) return { ok: false, why: agentUnavailable(agent, detectAgents({ env })) };
175
+ const out = await exec(cmd, cwd, timeoutMs, signal);
176
+ if (signal?.aborted) return { ok: false, why: 'stopped' };
177
+ if (out == null) return { ok: false, why: 'the agent did not answer in time' };
178
+ const answers = parseRuns(out);
179
+ const why = translateProblem(units, answers, opts);
180
+ if (why) return { ok: false, why };
181
+ return { ok: true, texts: units.map((u, k) => fromLine(u.kind, answers.get(k + 1))) };
182
+ }
183
+
184
+ /** Run `fn` over `items`, `n` at a time, in order of starting. */
185
+ async function pool(items, n, fn, signal = null) {
186
+ let next = 0;
187
+ const worker = async () => { while (next < items.length && !signal?.aborted) { const i = next++; await fn(items[i], i); } };
188
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
189
+ }
190
+
191
+ /**
192
+ * The same source text is given the same translation (TRANSLATION_UNITS): a
193
+ * chapter name or a step of a run of steps is matched to the others by its
194
+ * words, so an attribute translated twice in one run, or once now and once
195
+ * before, takes one translation.
196
+ */
197
+ export function unifyAttributes(matched) {
198
+ const first = new Map();
199
+ const all = [...matched.deck, ...matched.slides.flat()];
200
+ for (const u of all) if (u.kind === 'attr' && u.status === 'current' && !first.has(u.text)) first.set(u.text, u);
201
+ for (const u of all) if (u.kind === 'attr' && u.status === 'translated' && !first.has(u.text)) first.set(u.text, u);
202
+ for (const u of all) {
203
+ if (u.kind !== 'attr' || u.status !== 'translated') continue;
204
+ const f = first.get(u.text);
205
+ if (f && f !== u) { u.target = f.target; u.state = f.state; }
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Ask the agent for every behind unit on `slides` (1-based numbers, null for
211
+ * all), in place on `matched`. Resolves to `[{ slide, ok, why, count, redone }]`.
212
+ */
213
+ export async function translateMatched(matched, { slides = null, limitsBySlide = null, onSlide = () => {}, ...opts }) {
214
+ const todo = [];
215
+ const behind = (u) => u.status === 'changed' || u.status === 'missing';
216
+ if (matched.deck.some(behind) && !limitsBySlide) todo.push({ slide: 0, units: matched.deck.filter(behind) });
217
+ matched.slides.forEach((S, i) => {
218
+ if (slides && !slides.includes(i + 1)) return;
219
+ if (limitsBySlide && !limitsBySlide.has(i + 1)) return;
220
+ const units = limitsBySlide ? S.filter((u) => u.status === 'translated') : S.filter(behind);
221
+ if (units.length) todo.push({ slide: i + 1, units, done: S.filter((u) => u.status === 'current') });
222
+ });
223
+ const results = [];
224
+ let finished = 0;
225
+ await pool(todo, opts.concurrency ?? ENHANCE_CONCURRENCY, async ({ slide, units, done = [] }) => {
226
+ const limits = limitsBySlide?.get(slide)?.(units) ?? null;
227
+ const asked = limitsBySlide ? units.map((u) => ({ ...u, status: 'missing' })) : units;
228
+ const a = await translateUnits(asked, { ...opts, done, limits });
229
+ const r = { slide, ok: a.ok, count: units.length, ...(a.ok ? {} : { why: a.why }), redone: 0 };
230
+ if (a.ok) {
231
+ units.forEach((u, k) => {
232
+ if (u.status === 'changed' && u.previous?.state === 'reviewed') r.redone++;
233
+ Object.assign(u, { status: 'translated', target: a.texts[k], state: 'machine' });
234
+ });
235
+ }
236
+ results.push(r);
237
+ onSlide({ ...r, done: ++finished, of: todo.length });
238
+ }, opts.signal);
239
+ unifyAttributes(matched);
240
+ return results.sort((x, y) => x.slide - y.slide);
241
+ }
242
+
243
+ // ── the command ──────────────────────────────────────────────────────────────
244
+
245
+ /**
246
+ * The language's recordings follow its slides: where each slide of the
247
+ * translation as it was is in the translation as it is now, read off the
248
+ * sections (as the edit server reads an agent's edit), applied to the
249
+ * language's own voice folders. A line saying what moved, or ''.
250
+ */
251
+ export function followTakes(deckPath, before, after, label) {
252
+ const pairs = slideRenumber(before, after);
253
+ if (!pairs.length) return '';
254
+ const dirs = voiceFolders(deckPath);
255
+ if (!dirs.length) return '';
256
+ const r = planSteps(dirname(deckPath), dirs.map((dir) => ({ dir, pairs })));
257
+ if (r.error) return `translate: ${label}: ${r.error} — they were left where they were; realign them from the narration panel\n`;
258
+ if (!r.plans.length) return '';
259
+ try { applyPlans(dirname(deckPath), r.plans); } catch (e) { return `translate: ${label}: the recordings could not follow the slides — ${e.message}\n`; }
260
+ return `translate: ${label}: the recordings in ${r.plans.map((p) => `${p.dir}/`).join(', ')} followed their slides\n`;
261
+ }
262
+
263
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
264
+
265
+ /** One line of `--status` for a language. */
266
+ export function statusLine(lang, st, html, { exists = true } = {}) {
267
+ const name = `${languageName(lang)} · ${lang}`;
268
+ if (!exists) return ` ○ ${name} not translated yet`;
269
+ const read = `${st.reviewed} of ${st.total} reviewed`;
270
+ if (st.up) return ` ✓ ${name} up to date · ${read}`;
271
+ const parts = [st.changed && `${st.changed} changed`, st.missing && `${st.missing} missing`].filter(Boolean).join(', ');
272
+ return ` ↑ ${name} behind: ${parts} ${slidesPhrase(html, st.behind)} · ${read}`;
273
+ }
274
+
275
+ /** The overflowing slides of a written deck, by the same render `decklight check` reads; null with no browser. */
276
+ async function overflowing(deckPath, { render = null, wait = 8000 } = {}) {
277
+ const r = render ?? (await import('./check.mjs').then(async (check) => {
278
+ const { findChrome } = await import('../tools/chrome.mjs');
279
+ const bin = findChrome();
280
+ return bin ? (path) => check.checkOnce(path, path, { render: check.oneShot(bin), wait }) : null;
281
+ }));
282
+ if (!r) return null;
283
+ const once = await r(deckPath);
284
+ return once ? [...new Set(once.findings.filter((f) => f.rule === 'overflow' && f.slide).map((f) => f.slide))] : null;
285
+ }
286
+
287
+ export async function translateMain(args = [], {
288
+ out = process.stdout, err = process.stderr, env = process.env, exec = ask, resolveAgent = agentAsk, render = null,
289
+ } = {}) {
290
+ if (args.includes('--help') || args.includes('-h')) { out.write(USAGE); return 0; }
291
+ const { opt } = argReader(args);
292
+ const given = firstPositional(args, VALUE_FLAGS);
293
+ if (!given) { err.write(`decklight translate: needs a deck\n\n${USAGE}`); return 1; }
294
+ const deckPath = resolve(given);
295
+ if (!existsSync(deckPath)) { err.write(`decklight translate: no such deck: ${given}\n`); return 1; }
296
+ const { source, given: was } = resolveSource(deckPath);
297
+ if (was) err.write(`decklight translate: ${basename(deckPath)} is the ${languageName(was, { in: 'en' })} of ${basename(source)} — translating from ${basename(source)}\n`);
298
+ let html = readFileSync(source, 'utf8');
299
+ const from = sourceLang(html);
300
+ const sourceName = basename(source);
301
+
302
+ const status = args.includes('--status') || args.includes('--check');
303
+ const dry = args.includes('--dry-run');
304
+ const noAgent = args.includes('--no-agent');
305
+ const discard = args.includes('--discard-structure');
306
+ const asked = opt('--to') ? opt('--to').split(',').map((s) => s.trim()).filter(Boolean) : null;
307
+ for (const t of asked ?? []) {
308
+ const bad = tagProblem(t);
309
+ if (bad) { err.write(`decklight translate: ${bad}\n`); return 1; }
310
+ if (from && t.toLowerCase() === from.toLowerCase()) { err.write(`decklight translate: ${sourceName} is already in ${t}\n`); return 1; }
311
+ }
312
+ const known = knownLanguages(source, html);
313
+ const langs = asked ?? known;
314
+ if (!langs.length) {
315
+ err.write(`decklight translate: ${sourceName} names no languages yet — say which with --to (decklight translate ${given} --to fr)\n`);
316
+ return 1;
317
+ }
318
+ const total = sectionBodies(html).length;
319
+ let only = null;
320
+ if (opt('--slides')) {
321
+ try { only = parseSlides(opt('--slides'), total); } catch (e) { err.write(`decklight translate: ${e.message}\n`); return 1; }
322
+ }
323
+
324
+ // a language named for the first time joins the source's list
325
+ const fresh = langs.filter((l) => !known.some((k) => k.toLowerCase() === l.toLowerCase()));
326
+ if (fresh.length && !status && !dry) {
327
+ const listed = Array.isArray(deckConfig(html)?.languages) ? deckConfig(html).languages : [];
328
+ const next = withConfigKeys(html, { languages: [...listed, ...fresh] });
329
+ if (next) { writeFileAtomic(source, next); html = next; }
330
+ else err.write(`decklight translate: ${sourceName} has no configuration block to list ${fresh.join(', ')} in — name ${fresh.length === 1 ? 'it' : 'them'} with --to each time\n`);
331
+ }
332
+
333
+ if (!status && !noAgent && !resolveAgent(opt('--agent') ?? null, 'x', { env })) {
334
+ err.write(`decklight translate: ${agentUnavailable(opt('--agent') ?? null, detectAgents({ env }))}\n`
335
+ + ' (--no-agent regenerates the translations without one: the words that need a model stay behind)\n');
336
+ return 1;
337
+ }
338
+
339
+ const source$ = deckUnits(html);
340
+ // every language of the deck, linked from each translation (TRANSLATION_SWITCH)
341
+ const everyLang = [...new Map([...knownLanguages(source, html), ...langs].map((l) => [l.toLowerCase(), l])).values()];
342
+ const alternates = [
343
+ ...(from ? [{ lang: from, href: sourceName }] : []),
344
+ ...everyLang.map((l) => ({ lang: l, href: basename(languageFiles(source, l).deck) })),
345
+ ];
346
+ const controller = new AbortController();
347
+ if (args.includes('--from-server')) stopOnInput(controller);
348
+ let code = 0;
349
+ if (status) out.write(`${sourceName}${from ? ` (${from})` : ''} · ${plural(langs.length, 'language')}\n`);
350
+ for (const lang of langs) {
351
+ const files = languageFiles(source, lang);
352
+ const label = `${languageName(lang, { in: 'en' })} (${basename(files.deck)})`;
353
+ let record;
354
+ try { record = existsSync(files.record) ? parseRecord(readFileSync(files.record, 'utf8')) : emptyRecord(sourceName, from, lang); }
355
+ catch (e) { err.write(`decklight translate: ${basename(files.record)} cannot be read — ${e.message}\n`); code = 2; continue; }
356
+ const translation = existsSync(files.deck) ? readFileSync(files.deck, 'utf8') : null;
357
+ const back = readBack(record, translation);
358
+ if (back.structure.length && !discard) {
359
+ for (const s of back.structure) {
360
+ err.write(`decklight translate: ${basename(files.deck)}${s.slide ? `, slide ${s.slide}` : ''}: ${s.why}. `
361
+ + `A translation takes its structure from ${sourceName}: make that change there, or run again with --discard-structure to overwrite it\n`);
362
+ }
363
+ code = 2;
364
+ continue;
365
+ }
366
+ const base = back.structure.length ? record : back.record;
367
+ const matched = matchRecord(source$, { ...base, slides: back.structure.length ? [] : base.slides });
368
+ const before = languageStatus(matched);
369
+
370
+ if (status) {
371
+ out.write(`${statusLine(lang, before, html, { exists: !!translation })}\n`);
372
+ if (back.corrected) out.write(` ${plural(back.corrected, 'correction')} in ${basename(files.deck)}, kept as reviewed at the next run\n`);
373
+ if (!before.up || !translation) code = args.includes('--check') ? Math.max(code, 1) : code;
374
+ continue;
375
+ }
376
+
377
+ let results = [];
378
+ let writtenRecord = null;
379
+ if (!noAgent && !before.up) {
380
+ out.write(`translate: ${label} — ${plural(before.changed + before.missing, 'piece')} to translate ${slidesPhrase(html, only ? before.behind.filter((n) => only.includes(n)) : before.behind)}\n`);
381
+ const common = {
382
+ from, to: lang, title: source$.deck[0]?.text ?? '', glossary: base.glossary ?? {},
383
+ agent: opt('--agent') ?? null, model: opt('--agent-model'), env, exec, resolveAgent, cwd: dirname(source),
384
+ signal: controller.signal,
385
+ };
386
+ results = await translateMatched(matched, {
387
+ ...common, slides: only,
388
+ onSlide: (r) => out.write(` [${r.done}/${r.of}] ${r.slide ? `slide ${r.slide}` : 'the title'} ${r.ok ? `· ${plural(r.count, 'piece')}` : `· left as it was: ${r.why}`}\n`),
389
+ });
390
+
391
+ // fit is measured, not estimated: render, and re-ask a slide that overflows for shorter text
392
+ if (!dry && results.some((r) => r.ok && r.slide)) {
393
+ for (let round = 0; round < 2; round++) {
394
+ const draft = renderTranslation(html, matched, { lang, sourceName, alternates });
395
+ writeFileAtomic(files.deck, draft.html);
396
+ const over = await overflowing(files.deck, { render, wait: Number(opt('--wait', 8000)) });
397
+ const ours = (over ?? []).filter((n) => matched.slides[n - 1]?.some((u) => u.status === 'translated'));
398
+ if (!ours.length) break;
399
+ out.write(` ${plural(ours.length, 'slide')} ${slidesPhrase(html, ours)} ${ours.length === 1 ? 'does' : 'do'} not fit — asking for shorter text\n`);
400
+ const limitsBySlide = new Map(ours.map((n) => [n, (units) => units.map((u) => (u.kind === 'run' ? Math.max(4, Math.min(u.text.length, Math.floor(u.target.length * 0.85))) : null))]));
401
+ await translateMatched(matched, { ...common, limitsBySlide });
402
+ }
403
+ }
404
+ }
405
+
406
+ const after = languageStatus(matched);
407
+ if (dry) {
408
+ const now = matched.slides.flatMap((S, i) => S.filter((u) => u.status === 'translated').map((u) => ({ u, slide: i + 1 })));
409
+ for (const { u, slide } of now) out.write(` slide ${slide} [${KIND_LABEL[u.kind]}] ${u.text.replace(/\n+/g, ' ')}\n → ${u.target.replace(/\n+/g, ' ')}\n`);
410
+ out.write(`translate: --dry-run — ${basename(files.deck)} not written\n`);
411
+ } else {
412
+ const written = renderTranslation(html, matched, { lang, sourceName, alternates });
413
+ // a slide moved in the source moves this language's takes with it, at
414
+ // the run that moves the slide here (TRANSLATION_VOICE)
415
+ if (translation) out.write(followTakes(files.deck, translation, written.html, label));
416
+ writeFileAtomic(files.deck, written.html);
417
+ writeFileAtomic(files.record, formatRecord(nextRecord(base, matched, written.structure)));
418
+ writtenRecord = nextRecord(base, matched, written.structure);
419
+ }
420
+ const done = results.filter((r) => r.ok).reduce((n, r) => n + r.count, 0);
421
+ const failed = results.filter((r) => !r.ok);
422
+ const redone = results.reduce((n, r) => n + r.redone, 0);
423
+ const parts = [
424
+ `${label}: ${done ? `${plural(done, 'piece')} translated` : 'nothing translated'}`,
425
+ back.corrected ? `${plural(back.corrected, 'correction')} of yours kept` : '',
426
+ after.up ? 'up to date' : `${plural(after.changed + after.missing, 'piece')} still behind ${slidesPhrase(html, after.behind) || 'in the title'}`,
427
+ ...failed.map((r) => `${r.slide ? `slide ${r.slide}` : 'the title'} left as it was: ${r.why}`),
428
+ redone ? `${plural(redone, 'reviewed translation')} redone, the source changed` : '',
429
+ ].filter(Boolean);
430
+ out.write(`translate: ${parts.join(' · ')}\n`);
431
+ if (!dry && done) {
432
+ const still = await overflowing(files.deck, { render, wait: Number(opt('--wait', 8000)) }).catch(() => null);
433
+ if (still?.length) out.write(`translate: ${basename(files.deck)} — ${plural(still.length, 'slide')} still ${still.length === 1 ? 'overflows' : 'overflow'} ${slidesPhrase(html, still)}: shorten the ${languageName(lang, { in: 'en' })} in the file, or the source\n`);
434
+ // what the panel says until the next run measures again (TRANSLATE_PANEL)
435
+ if (still && writtenRecord) writeFileAtomic(files.record, formatRecord({ ...writtenRecord, overflow: still }));
436
+ }
437
+ if (failed.length) code = 2;
438
+ if (controller.signal.aborted) { out.write('translate: stopped — what was answered and passed is written, the rest stays behind\n'); break; }
439
+ }
440
+ // the translations this run did not write still link every language there now is
441
+ if (!status && !dry) {
442
+ for (const l of everyLang) {
443
+ if (langs.some((x) => x.toLowerCase() === l.toLowerCase())) continue;
444
+ const f = languageFiles(source, l).deck;
445
+ if (!existsSync(f)) continue;
446
+ const was = readFileSync(f, 'utf8');
447
+ const now = withAlternates(was, alternates);
448
+ if (now !== was) writeFileAtomic(f, now);
449
+ }
450
+ }
451
+ return code;
452
+ }
453
+
454
+ if (isMain(import.meta.url)) {
455
+ process.exitCode = await runMain('translate', () => translateMain(process.argv.slice(2)));
456
+ // started by the edit server, whose pipe on stdin would keep it alive
457
+ if (process.argv.includes('--from-server')) process.exit(process.exitCode);
458
+ }
package/cli/units.mjs CHANGED
@@ -21,7 +21,9 @@
21
21
  * deck at a desk.
22
22
  *
23
23
  * WHAT IS DELIBERATELY NOT HERE: running an installed unit. A skill is
24
- * Markdown, so it is just files. An import adapter and
24
+ * Markdown, so it is just files — read by an agent, not by a decklight
25
+ * command, so `library add skill` also hands it to the agents `decklight
26
+ * skills` writes for (`cli/skills.mjs` `placeLibrarySkill`, #880). An import adapter and
25
27
  * a build-time transform are both **Node code**, and executing either is one
26
28
  * shared capability rather than two copies of resolve-fetch-validate-load —
27
29
  * `cli/loader.mjs` (`EXTENSIONS#LOADER`) is that shared loader. `bundle
@@ -55,7 +57,7 @@ export const UNIT_TYPES = {
55
57
  files: ['SKILL.md'],
56
58
  optional: ['reference.md'],
57
59
  label: 'agent skill',
58
- use: 'decklight library add skill <name>',
60
+ use: 'your coding agent (decklight skills hands it to Claude Code and the AGENTS.md agents)',
59
61
  example: 'conference-cfp',
60
62
  required: [],
61
63
  },
@@ -249,6 +251,23 @@ export function installedVoices(engine, home = configHome()) {
249
251
  return out;
250
252
  }
251
253
 
254
+ /**
255
+ * The installed marketplace skills, each with the `description` its SKILL.md
256
+ * frontmatter gives — what an agent picks one by (#880): the AGENTS.md section
257
+ * lists them, and `decklight skills` copies them beside the authoring skill.
258
+ * Offline like every read here; a SKILL.md with no frontmatter still lists, by
259
+ * name alone.
260
+ */
261
+ export function librarySkills(home = configHome()) {
262
+ return listUnits('skill', home).map(({ name, path }) => {
263
+ let text = '';
264
+ try { text = readFileSync(join(path, 'SKILL.md'), 'utf8'); } catch { /* listed by name */ }
265
+ const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? '';
266
+ const description = (/^description:[ \t]*(.*)$/m.exec(front)?.[1] ?? '').trim().replace(/^(['"])(.*)\1$/, '$2');
267
+ return { name, description, path };
268
+ });
269
+ }
270
+
252
271
  // ── installing, the one place that reaches the network ─────────────────────
253
272
 
254
273
  /** Read one artifact file from a resolved source (a URL or a local path). */
@@ -418,15 +437,39 @@ export const unitUsage = (type) => {
418
437
  decklight library remove ${type} <name>
419
438
  delete it from your library
420
439
 
421
- used by: ${t.use}
440
+ used by: ${t.use}${type === 'skill' ? `
441
+
442
+ A skill is read by your coding agent, so \`add\` also copies it where the
443
+ agent loads skills: on a terminal it asks, every project (~/.claude/skills/,
444
+ --global, recommended) or this one (.claude/skills/, --dir <path> names
445
+ another); otherwise into a project that already has a .claude/ or a
446
+ Decklight AGENTS.md
447
+ and lists it in every AGENTS.md carrying the Decklight section; \`remove\`
448
+ takes both away again. \`decklight skills\` keeps them.` : ''}
422
449
 
423
450
  Registering a marketplace is not fetching it (SPEC MARKETPLACE_REGISTRY):
424
451
  \`list\` reads only the cache and works on a plane, and the network is touched
425
452
  only by an explicit \`add\`. DECKLIGHT_HOME overrides ~/.decklight/.`;
426
453
  };
427
454
 
455
+ /**
456
+ * The positionals and the agent scope of a unit command: `--global` (each
457
+ * agent's config home) or `--dir <path>` (a project other than the current
458
+ * directory). Only a skill reads the scope — it is the one kind an agent reads.
459
+ */
460
+ function scopeArgs(args) {
461
+ const out = { names: [], global: false, dir: '.', dirNamed: false };
462
+ for (let i = 0; i < args.length; i++) {
463
+ if (args[i] === '--global' || args[i] === '-g') out.global = true;
464
+ else if (args[i] === '--dir') { out.dir = args[++i] ?? '.'; out.dirNamed = true; }
465
+ else if (!args[i].startsWith('-')) out.names.push(args[i]);
466
+ }
467
+ return out;
468
+ }
469
+
428
470
  async function addMain(type, args, home) {
429
- const [ref] = args.filter((a) => !a.startsWith('-'));
471
+ const scope = scopeArgs(args);
472
+ const [ref] = scope.names;
430
473
  if (!ref) { console.error(`decklight library add ${type}: needs a name\n\n${unitUsage(type)}`); return 1; }
431
474
  let done;
432
475
  try { done = await installUnit(type, ref, home); } catch (e) {
@@ -436,6 +479,26 @@ async function addMain(type, args, home) {
436
479
  }
437
480
  console.log(`installed ${done.name}${done.entry.version ? ` ${done.entry.version}` : ''} from ${done.qualified} — ${UNIT_TYPES[type].use}`);
438
481
  if (done.entry.description) console.log(` ${done.entry.description}`);
482
+ // A skill's consumer is an agent, not a decklight command: hand it to the
483
+ // agents `decklight skills` writes for, or it sits where nothing reads (#880).
484
+ if (type === 'skill') {
485
+ const { placeLibrarySkill, skillPlaces, skillPlaceAnswer, skillPlaceQuestion } = await import('./skills.mjs');
486
+ // No scope typed, on a terminal: ask where it goes, every project first,
487
+ // rather than guess from whether this folder has a .claude/ (#893)
488
+ if (!scope.global && !scope.dirNamed && process.stdin.isTTY && process.stdout.isTTY) {
489
+ const { createInterface } = await import('node:readline/promises');
490
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
491
+ let where;
492
+ try { where = skillPlaceAnswer(await rl.question(skillPlaceQuestion(done.name, skillPlaces(done.name, scope)))); } finally { rl.close(); }
493
+ if (!where) {
494
+ console.log(` not handed to an agent: decklight library add skill ${done.name} --global (or --dir <project>) does it later`);
495
+ return 0;
496
+ }
497
+ if (where === 'global') scope.global = true;
498
+ else scope.dirNamed = true;
499
+ }
500
+ for (const line of placeLibrarySkill(done.name, scope)) console.log(` ${line}`);
501
+ }
439
502
  return 0;
440
503
  }
441
504
 
@@ -462,8 +525,9 @@ function listMain(type, home) {
462
525
  return 0;
463
526
  }
464
527
 
465
- function removeMain(type, args, home) {
466
- const [name] = args.filter((a) => !a.startsWith('-'));
528
+ async function removeMain(type, args, home) {
529
+ const scope = scopeArgs(args);
530
+ const [name] = scope.names;
467
531
  if (!name) { console.error(`decklight library remove ${type}: which one?\n\n${unitUsage(type)}`); return 1; }
468
532
  try { removeUnit(type, name, home); } catch (e) {
469
533
  if (!(e instanceof UnitError)) throw e;
@@ -471,6 +535,10 @@ function removeMain(type, args, home) {
471
535
  return 1;
472
536
  }
473
537
  console.log(`removed ${name}`);
538
+ if (type === 'skill') {
539
+ const { unplaceLibrarySkill } = await import('./skills.mjs');
540
+ for (const line of unplaceLibrarySkill(name, scope)) console.log(` ${line}`);
541
+ }
474
542
  return 0;
475
543
  }
476
544
 
@@ -484,7 +552,7 @@ export async function unitMain(type, args = []) {
484
552
  try {
485
553
  if (sub === 'add') return await addMain(type, rest, home);
486
554
  if (sub === 'list') return listMain(type, home);
487
- if (sub === 'remove') return removeMain(type, rest, home);
555
+ if (sub === 'remove') return await removeMain(type, rest, home);
488
556
  } catch (e) {
489
557
  if (e instanceof UnitError || e instanceof MarketplaceError) {
490
558
  console.error(`decklight library ${sub} ${type}: ${e.message}`);
package/cli/util.mjs CHANGED
@@ -147,3 +147,28 @@ export function versionLine(version, info) {
147
147
  if (info.commits === 0 && !info.dirty) return `decklight ${version}`;
148
148
  return `decklight ${version}+${info.commits}.g${info.commit}${info.dirty ? '.dirty' : ''}`;
149
149
  }
150
+
151
+ /**
152
+ * Calls `fn(code, signal)` once a child has exited AND its output has been
153
+ * read to the end — or `graceMs` after the exit, whichever comes first.
154
+ *
155
+ * WHY NOT `exit`. Node fires 'exit' when the process is gone, which can be
156
+ * before the last of what it wrote has come through its pipes: an agent that
157
+ * prints its result line and quits at once was finalised with that line still
158
+ * in flight, and the panel showed an empty report (a CI flake, then a real
159
+ * one on a loaded machine). WHY NOT `close`, which waits for the pipes: a
160
+ * child that leaves a grandchild holding its stdout (an agent's background
161
+ * shell, an MCP server) never closes them, and the run would sit "busy" until
162
+ * its ten-minute timeout. So: the exit, then the pipes, with a bound.
163
+ */
164
+ export function afterOutput(child, fn, graceMs = 2000) {
165
+ const ended = (s) => (!s || s.readableEnded || s.destroyed
166
+ ? Promise.resolve()
167
+ : new Promise((ok) => { s.once('end', ok); s.once('close', ok); }));
168
+ const drained = Promise.all([ended(child.stdout), ended(child.stderr)]);
169
+ child.once('exit', (code, signal) => {
170
+ let timer;
171
+ const grace = new Promise((ok) => { timer = setTimeout(ok, graceMs); });
172
+ Promise.race([drained, grace]).then(() => { clearTimeout(timer); fn(code, signal); });
173
+ });
174
+ }