decklight 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
@@ -0,0 +1,257 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // First-run TTS setup (SPEC PRESENTING): the guided questions that turn "gemini needs
5
+ // a GCP project" from a dead end into a working voice. Both entry points share
6
+ // it — `decklight tts` runs it where it used to exit with that error (and on
7
+ // `--setup`), `decklight author` offers it where it would otherwise skip the
8
+ // voice bridge.
9
+ //
10
+ // The questions ARE the engines' error strings turned around: everything the
11
+ // wizard asks about is something tts-engines.mjs would have thrown about one
12
+ // keypress later. It ends with one real test synthesis — the picker's preview
13
+ // sentence — and saves NOTHING unless that synthesis succeeded, so a saved
14
+ // config is a config that has actually spoken.
15
+ //
16
+ // Interaction is injected (`ask`, the resolvePortConflict pattern), so every
17
+ // path is testable without a TTY.
18
+
19
+ import { execFileSync, spawnSync } from 'node:child_process';
20
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
21
+ import { homedir, tmpdir } from 'node:os';
22
+ import { delimiter, dirname, join } from 'node:path';
23
+ import {
24
+ createEngine, ENGINES, PIPER_DEFAULT_VOICE, piperModelDir,
25
+ piperDownloadCmd, piperDownloadLine,
26
+ } from './tts-engines.mjs';
27
+ import { gcloudToken, validProjectId } from './gemini-tts.mjs';
28
+ import { KEY_ENV as ELEVENLABS_KEY_ENV, apiKey as elevenLabsKey } from './elevenlabs-tts.mjs';
29
+
30
+ // The picker's preview default (SPEC PRESENTING) — the wizard's proof is the same
31
+ // audio the deck's N picker previews.
32
+ export const TEST_SENTENCE = 'Hey, this is Decklight';
33
+
34
+ /** The saved answers live at ~/.config/decklight/tts.json — $XDG_CONFIG_HOME honored. */
35
+ export function ttsConfigPath(env = process.env) {
36
+ const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config');
37
+ return join(base, 'decklight', 'tts.json');
38
+ }
39
+
40
+ /** The saved config, or null — a missing (or unreadable) file is first-run, not an error. */
41
+ export function loadTtsConfig(env = process.env) {
42
+ try { return JSON.parse(readFileSync(ttsConfigPath(env), 'utf8')); }
43
+ catch { return null; }
44
+ }
45
+
46
+ export function saveTtsConfig(config, env = process.env) {
47
+ const file = ttsConfigPath(env);
48
+ mkdirSync(dirname(file), { recursive: true });
49
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
50
+ return file;
51
+ }
52
+
53
+ // cli/agents.mjs has the full onPath (explicit paths too); tools/ cannot
54
+ // import from cli/, and the wizard only ever probes bare names.
55
+ function binOnPath(bin, env = process.env) {
56
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
57
+ return (env.PATH || '').split(delimiter)
58
+ .some((dir) => dir && exts.some((ext) => existsSync(join(dir, bin + ext))));
59
+ }
60
+
61
+ /** The project gcloud is configured with — the prefill when $GOOGLE_CLOUD_PROJECT is unset. */
62
+ export function gcloudConfigProject() {
63
+ try {
64
+ const out = execFileSync('gcloud', ['config', 'get-value', 'project'],
65
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
66
+ return out && !out.startsWith('(') ? out : null; // '(unset)' when none
67
+ } catch { return null; }
68
+ }
69
+
70
+ /**
71
+ * The suggested default follows what the machine already has. An ElevenLabs key
72
+ * in the environment is the strongest signal of the four: nobody exports one by
73
+ * accident, and it is the only engine that can speak in a voice that is yours.
74
+ * After that, piper on PATH speaks for free today and a visible GCP project puts
75
+ * chirp one Enter away. A bare machine suggests piper — the wizard can install
76
+ * it, and it is the only engine with no bill attached.
77
+ */
78
+ export function suggestEngine({ hasBin = binOnPath, env = process.env, project = null } = {}) {
79
+ if (elevenLabsKey(env)) return 'elevenlabs';
80
+ if (hasBin('piper', env)) return 'piper';
81
+ if (project) return 'chirp';
82
+ return 'piper';
83
+ }
84
+
85
+ // Proof you can HEAR, when the machine has a player — silence is not a
86
+ // failure (CI has no speakers), and the synthesis already proved itself.
87
+ function playWav(wav, env = process.env) {
88
+ const player = ['afplay', 'paplay', 'aplay'].find((b) => binOnPath(b, env));
89
+ if (!player) return;
90
+ const f = join(tmpdir(), `decklight-tts-test-${process.pid}.wav`);
91
+ try {
92
+ writeFileSync(f, wav);
93
+ execFileSync(player, [f], { stdio: 'ignore', timeout: 15_000 });
94
+ } catch { /* headless audio stack */ }
95
+ finally { rmSync(f, { force: true }); }
96
+ }
97
+
98
+ const yes = (answer, dflt) => (answer.trim() === '' ? dflt : /^y/i.test(answer.trim()));
99
+
100
+ // Menu order is a recommendation — free first — so it is NOT tts-engines'
101
+ // ENGINES order (which keeps gemini first as the historical default).
102
+ const MENU = ['piper', 'chirp', 'gemini', 'elevenlabs'];
103
+
104
+ /**
105
+ * The guided setup. `ask` is `(prompt) => Promise<string>` and is required —
106
+ * the caller owns the readline (dev already holds one for its git question).
107
+ * Everything with a side effect is injectable so tests never touch PATH,
108
+ * gcloud, or the network. Returns `{ config, engine }` — the engine has
109
+ * already spoken the test sentence, so `decklight tts` can serve with it as
110
+ * is — or null when setup was declined or the test synthesis failed; in
111
+ * either of those cases NOTHING was saved.
112
+ */
113
+ export async function runSetupWizard({
114
+ ask,
115
+ log = console.log,
116
+ env = process.env,
117
+ hasBin = binOnPath,
118
+ detectProject,
119
+ mintToken = gcloudToken,
120
+ makeEngine = createEngine,
121
+ runCmd, // (bin, args) => ok — install commands, run only on an explicit yes
122
+ canImport, // (python) => can it import piper? injected so tests never spawn one
123
+ play = playWav,
124
+ prefill = {}, // --setup re-runs: the saved answers become the defaults
125
+ } = {}) {
126
+ detectProject ??= () => env.GOOGLE_CLOUD_PROJECT || prefill.project || gcloudConfigProject();
127
+ runCmd ??= (bin, args) => {
128
+ log(` $ ${bin} ${args.join(' ')}`);
129
+ return spawnSync(bin, args, { stdio: 'inherit' }).status === 0;
130
+ };
131
+
132
+ // 1. the engine, with the trade-offs stated
133
+ const detected = detectProject();
134
+ const suggested = MENU.includes(prefill.engine) ? prefill.engine
135
+ : suggestEngine({ hasBin, env, project: detected });
136
+ log(' which voice engine?');
137
+ log(' 1) piper free · offline · unlimited — one-time ~120 MB voice model download');
138
+ log(' 2) chirp Google Cloud TTS — 30 voices, 1M chars/month free');
139
+ log(' 3) gemini best delivery, honors a tone — billed, no free tier');
140
+ log(` 4) elevenlabs your own account's voices, cloned ones included — needs $${ELEVENLABS_KEY_ENV}`);
141
+ let engineName;
142
+ for (;;) {
143
+ const a = (await ask(` engine [${MENU.indexOf(suggested) + 1}] `)).trim().toLowerCase();
144
+ engineName = a === '' ? suggested : (MENU[Number(a) - 1] ?? (MENU.includes(a) ? a : undefined));
145
+ if (engineName) break;
146
+ log(` 1, 2, 3, 4 — or a name: ${MENU.join(', ')}`);
147
+ }
148
+ const config = { engine: engineName };
149
+
150
+ // 2. only what that engine actually needs
151
+ if (engineName === 'piper') {
152
+ // Whether the downloader can be reached through uvx is knowledge this code
153
+ // HAS and generic detection does not: if the wizard installs piper below it
154
+ // does so with uv, and uvx ships with uv. Detecting it instead would make
155
+ // the wizard's behaviour depend on the machine running the test.
156
+ let uvx = hasBin('uvx', env);
157
+ if (!hasBin('piper', env)) {
158
+ log(' piper is not installed. the install is one command:');
159
+ log(' uv tool install piper-tts');
160
+ if (!yes(await ask(' run it now? [y/N] '), false)) {
161
+ log(' install piper, then run: decklight tts');
162
+ return null;
163
+ }
164
+ if (!runCmd('uv', ['tool', 'install', 'piper-tts'])) {
165
+ log(' install failed — nothing saved');
166
+ return null;
167
+ }
168
+ uvx = true; // uv just ran, so uvx is there too
169
+ }
170
+ const voice = prefill.voice ?? PIPER_DEFAULT_VOICE;
171
+ const models = piperModelDir(env);
172
+ if (!existsSync(join(models, `${voice}.onnx`))) {
173
+ // the command is CHOSEN, not assumed: `uv tool install piper-tts` above
174
+ // puts piper in an isolated venv the ambient python cannot import from,
175
+ // so the plain `python -m piper.download_voices` we used to print here
176
+ // failed with ModuleNotFoundError on a machine that had just installed
177
+ // piper successfully — following our own instructions
178
+ const dl = piperDownloadCmd(voice, models, {
179
+ hasBin: (b) => (b === 'uvx' ? uvx : hasBin(b, env)),
180
+ ...(canImport ? { canImport } : {}),
181
+ });
182
+ log(` the ${voice} voice model is missing (~120 MB, one-time). the download is one command:`);
183
+ log(` ${piperDownloadLine(dl)}`);
184
+ if (!dl) return null;
185
+ if (!yes(await ask(' run it now? [y/N] '), false)) {
186
+ log(' fetch the model, then run: decklight tts');
187
+ return null;
188
+ }
189
+ mkdirSync(models, { recursive: true });
190
+ if (!runCmd(dl.bin, dl.args)) {
191
+ log(' download failed — nothing saved');
192
+ return null;
193
+ }
194
+ }
195
+ config.voice = voice;
196
+ } else if (engineName === 'elevenlabs') {
197
+ // The key is the whole prerequisite, and it is the one answer this wizard
198
+ // will not write down: config files get committed, and a key is not a
199
+ // preference. Name where to get it and where to put it, then move on.
200
+ if (!elevenLabsKey(env)) {
201
+ log(` no ${ELEVENLABS_KEY_ENV} in the environment. create a key at`);
202
+ log(' https://elevenlabs.io/app/settings/api-keys');
203
+ log(' then export it (your shell profile is the right home for it — decklight');
204
+ log(' deliberately never writes it to its config file):');
205
+ log(` export ${ELEVENLABS_KEY_ENV}=...`);
206
+ log(' then run: decklight tts');
207
+ return null;
208
+ }
209
+ // Which voice is a question the account answers, not the user: the roster
210
+ // arrives with the test synthesis below and the picker offers it, yours
211
+ // first. Nothing to ask, so nothing is asked.
212
+ } else {
213
+ // chirp and gemini are the same two checks: which project, and can a
214
+ // token be minted. The id is validated here with the same rule the
215
+ // engines enforce — punctuation from a copy-paste must not survive to
216
+ // become an opaque 403.
217
+ let project = detected;
218
+ for (;;) {
219
+ const a = (await ask(` GCP project id${project ? ` [${project}]` : ''} `)).trim() || project || '';
220
+ if (validProjectId(a)) { project = a; break; }
221
+ log(` not a GCP project id: ${JSON.stringify(a)} — 6-30 chars, lowercase letters, digits and hyphens`);
222
+ }
223
+ config.project = project;
224
+ try { mintToken(); }
225
+ catch {
226
+ // detect and name the way in — never drive a browser auth flow
227
+ log(' no application-default credentials — mint them with:');
228
+ log(' gcloud auth application-default login');
229
+ log(' then run: decklight tts');
230
+ return null;
231
+ }
232
+ }
233
+
234
+ // 3. prove it: one real synthesis of the picker's preview sentence
235
+ let engine;
236
+ try {
237
+ engine = makeEngine({ engine: config.engine, project: config.project, voice: config.voice, env });
238
+ log(` testing ${engine.name} · ${engine.model} — "${TEST_SENTENCE}" …`);
239
+ const t0 = Date.now();
240
+ const { wav, usage } = await engine.synth(TEST_SENTENCE, {});
241
+ log(` ✓ spoke in ${((Date.now() - t0) / 1000).toFixed(1)}s · ${usage.note} · ${engine.cost}`);
242
+ // an account roster is worth reporting: it is the reason to pick this engine
243
+ const roster = await engine.listVoices?.().catch(() => null);
244
+ if (roster) log(` ${roster.length} voice(s) on this key — ${roster.slice(0, 3).map((v) => `${v.name} (${v.flavor})`).join(', ')}${roster.length > 3 ? ', …' : ''}`);
245
+ play(wav, env);
246
+ } catch (e) {
247
+ engine?.synth.close?.();
248
+ log(` test synthesis failed: ${e.message ?? e}`);
249
+ log(' nothing saved — fix that, then run: decklight tts --setup');
250
+ return null;
251
+ }
252
+
253
+ // 4. only a config that has spoken gets saved
254
+ const file = saveTtsConfig(config, env);
255
+ log(` saved to ${file} — decklight tts and decklight author read it from now on`);
256
+ return { config, engine };
257
+ }
package/tools/veo.mjs ADDED
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // Veo (Vertex AI) — the MOTION half of the talking head.
6
+ //
7
+ // Wav2Lip is a mouth, not a person: it repaints the lip region and leaves the
8
+ // rest of the source exactly as it found it. Given a photo, that means a frozen
9
+ // stare with a moving mouth — lifelike lips on a mannequin. Given a VIDEO of a
10
+ // person, the same model keeps the head turns, the blinks and the shoulders and
11
+ // still puts the deck's narration on the lips. So the fix is not a better mouth,
12
+ // it is a better source: Veo animates the portrait once, Wav2Lip re-syncs that
13
+ // clip to every sentence.
14
+ //
15
+ // The unit is the PORTRAIT, never the sentence. A Veo call takes ~40s and is
16
+ // billed per second of output, while the player asks the bridge for video once
17
+ // per SENTENCE, through a 10-sentence lookahead — one Veo call per sentence
18
+ // would be both unusably slow and a runaway bill. So each portrait is turned
19
+ // into one short motion loop, on first use, and cached on disk: a deck of any
20
+ // length costs exactly one Veo call per portrait, ever. Delete the cache dir to
21
+ // re-roll the performance.
22
+ //
23
+ // Audio is deliberately OFF (generateAudio: false — also the cheaper rate). The
24
+ // deck plays the character video muted and takes the voice from its narration
25
+ // track, so a Veo voice would be a second speaker talking over the first.
26
+ //
27
+ // const veo = createVeo({ project, cacheDir });
28
+ // const clip = await veo.motionFor('/path/portrait.jpg'); // → mp4 path
29
+ //
30
+ // Models (Vertex, us-central1): veo-3.1-lite-generate-001 (default — cheapest,
31
+ // and its extra fidelity would go into a mouth Wav2Lip is about to repaint
32
+ // anyway), veo-3.1-fast-generate-001, veo-3.1-generate-001, veo-3.0-*.
33
+ // Durations are fixed by the API: 4, 6 or 8 seconds.
34
+
35
+ import { execFile } from 'node:child_process';
36
+ import { createHash } from 'node:crypto';
37
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
38
+ import { join } from 'node:path';
39
+ import { promisify } from 'node:util';
40
+ import { gcloudToken, authHeaders } from './gemini-tts.mjs';
41
+
42
+ const run = promisify(execFile);
43
+
44
+ export const VEO_MODELS = [
45
+ 'veo-3.1-lite-generate-001',
46
+ 'veo-3.1-fast-generate-001',
47
+ 'veo-3.1-generate-001',
48
+ 'veo-3.0-fast-generate-001',
49
+ 'veo-3.0-generate-001',
50
+ ];
51
+ export const VEO_SECONDS = [4, 6, 8];
52
+
53
+ // Direct the camera, not the performance: Wav2Lip will overwrite the mouth, so
54
+ // what has to survive is head motion, blinks and a steady frame. A moving camera
55
+ // or a changing background would make every per-sentence cut visible.
56
+ export const DEFAULT_PROMPT =
57
+ 'The person in the photograph looks directly into the camera and speaks to the viewer, '
58
+ + 'calm and engaged. Subtle natural head movement, occasional blinks, small shifts of the '
59
+ + 'shoulders, warm attentive expression. Locked-off static camera, no zoom, no pan. '
60
+ + 'The background stays exactly as it is. Photorealistic, natural skin, soft even lighting.';
61
+
62
+ /**
63
+ * @param {object} o
64
+ * @param {string} o.project GCP project (billed)
65
+ * @param {string} [o.cacheDir] motion clips land here, keyed by the inputs
66
+ * @param {number} [o.faceY] square crop's top edge, as a fraction of height.
67
+ * Veo is asked for 9:16 (a talking head is taller
68
+ * than it is wide) but the deck's overlay is a
69
+ * CIRCLE, so the clip is cropped square around the
70
+ * head — which sits high in a portrait frame.
71
+ * @param {Function} [o.token] injectable for tests (default: ADC via gcloud)
72
+ * @param {Function} [o.fetch] injectable for tests
73
+ * @param {Function} [o.exec] injectable for tests (default: ffmpeg via execFile)
74
+ */
75
+ export function createVeo({
76
+ project,
77
+ location = 'us-central1',
78
+ model = VEO_MODELS[0],
79
+ seconds = 8,
80
+ prompt = DEFAULT_PROMPT,
81
+ cacheDir = '.',
82
+ faceY = 0.12,
83
+ size = 640,
84
+ token = gcloudToken,
85
+ fetch: fetchImpl = fetch,
86
+ exec = run,
87
+ pollMs = 10_000,
88
+ } = {}) {
89
+ if (!project) throw new Error('veo needs a GCP project — pass --veo-project <id> or set GOOGLE_CLOUD_PROJECT');
90
+ if (!VEO_SECONDS.includes(Number(seconds))) {
91
+ throw new Error(`veo: --veo-seconds must be one of ${VEO_SECONDS.join(', ')} (the API allows no others)`);
92
+ }
93
+ mkdirSync(cacheDir, { recursive: true });
94
+
95
+ const base = `https://${location}-aiplatform.googleapis.com/v1/projects/${project}`
96
+ + `/locations/${location}/publishers/google/models/${model}`;
97
+ const inflight = new Map(); // portrait path → promise, so a burst of
98
+ // lookahead prefetches cannot buy two clips
99
+
100
+ async function generate(portrait) {
101
+ const headers = authHeaders(token(), project);
102
+ const body = {
103
+ instances: [{
104
+ prompt,
105
+ image: {
106
+ bytesBase64Encoded: readFileSync(portrait).toString('base64'),
107
+ mimeType: portrait.toLowerCase().endsWith('.png') ? 'image/png' : 'image/jpeg',
108
+ },
109
+ }],
110
+ parameters: {
111
+ aspectRatio: '9:16',
112
+ durationSeconds: Number(seconds),
113
+ sampleCount: 1,
114
+ generateAudio: false, // the deck owns the voice (and it is cheaper)
115
+ personGeneration: 'allow_adult',
116
+ resolution: '720p',
117
+ },
118
+ };
119
+
120
+ // Vertex can answer a transient 429/5xx (quota, a backend blip) on the
121
+ // start call or any of the ~120 polls; without a retry one blip throws
122
+ // away a billed long-running operation. Back off and retry the transient
123
+ // statuses, and refresh the token on a 401 — the poll loop can outlive it.
124
+ async function post(url, payload) {
125
+ for (let attempt = 0; ; attempt++) {
126
+ let res;
127
+ try {
128
+ res = await fetchImpl(url, { method: 'POST', headers, body: JSON.stringify(payload) });
129
+ } catch (e) {
130
+ if (attempt >= 4) throw e;
131
+ await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt));
132
+ continue;
133
+ }
134
+ if (res.status === 401 && attempt < 4) { headers.authorization = `Bearer ${token()}`; continue; }
135
+ if ((res.status === 429 || res.status >= 500) && attempt < 4) {
136
+ await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt));
137
+ continue;
138
+ }
139
+ return res.json();
140
+ }
141
+ }
142
+
143
+ const started = await post(`${base}:predictLongRunning`, body);
144
+ if (started.error) throw new Error(`veo: ${started.error.message ?? JSON.stringify(started.error)}`);
145
+
146
+ // Generation is a long-running operation: minutes, not milliseconds.
147
+ for (let i = 0; i < 120; i++) {
148
+ await new Promise((r) => setTimeout(r, pollMs));
149
+ const op = await post(`${base}:fetchPredictOperation`, { operationName: started.name });
150
+ if (op.error) throw new Error(`veo: ${op.error.message ?? JSON.stringify(op.error)}`);
151
+ if (!op.done) continue;
152
+ const vids = op.response?.videos ?? op.response?.generatedSamples ?? [];
153
+ const b64 = vids[0]?.bytesBase64Encoded ?? vids[0]?.video?.bytesBase64Encoded;
154
+ // A refusal is a SUCCESS with nothing in it — Veo's safety filters decline
155
+ // some real faces outright, and saying so is more use than an empty file.
156
+ if (!b64) {
157
+ throw new Error('veo returned no video — the safety filter refused this portrait '
158
+ + `(raiMediaFilteredReasons: ${JSON.stringify(op.response?.raiMediaFilteredReasons ?? 'none given')}). `
159
+ + 'Try another photo, or run without --veo for a still portrait.');
160
+ }
161
+ return Buffer.from(b64, 'base64');
162
+ }
163
+ throw new Error('veo: timed out waiting for the operation');
164
+ }
165
+
166
+ /** portrait image → a cached mp4 of that person moving. One call per portrait. */
167
+ async function motionFor(portrait) {
168
+ const key = createHash('sha256')
169
+ .update(readFileSync(portrait)).update(`|${model}|${seconds}|${size}|${faceY}|${prompt}`)
170
+ .digest('hex').slice(0, 32);
171
+ const out = join(cacheDir, `veo-${key}.mp4`);
172
+ if (existsSync(out)) return out;
173
+
174
+ if (!inflight.has(key)) {
175
+ const p = (async () => {
176
+ if (existsSync(out)) return out;
177
+ const raw = join(cacheDir, `veo-${key}.raw.mp4`);
178
+ const tmp = join(cacheDir, `veo-${key}.tmp.mp4`);
179
+ try {
180
+ const t0 = Date.now();
181
+ process.stdout.write(` veo ${model} · ${seconds}s · ${portrait} … `);
182
+ writeFileSync(raw, await generate(portrait));
183
+ // 9:16 → a square on the head, at the size the face detector likes:
184
+ // s3fd misses faces in a big frame (it found nothing at 1070px wide,
185
+ // everything at 640), and the deck's overlay is a circle anyway.
186
+ await exec('ffmpeg', ['-y', '-i', raw,
187
+ '-vf', `crop=iw:iw:0:ih*${faceY},scale=${size}:${size}`,
188
+ '-an', '-c:v', 'libx264', '-crf', '18', '-preset', 'fast',
189
+ '-pix_fmt', 'yuv420p', '-movflags', '+faststart', tmp],
190
+ { timeout: 300_000 });
191
+ renameSync(tmp, out);
192
+ console.log(`${((Date.now() - t0) / 1000).toFixed(0)}s → ${out}`);
193
+ return out;
194
+ } finally {
195
+ for (const f of [raw, tmp]) rmSync(f, { force: true });
196
+ }
197
+ })().finally(() => inflight.delete(key));
198
+ inflight.set(key, p);
199
+ }
200
+ return inflight.get(key);
201
+ }
202
+
203
+ return { motionFor, model, seconds };
204
+ }