@slidevideo/cli 0.1.2 → 0.2.1

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 (64) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/IMPRESSUM.md +18 -4
  3. package/LICENSE-TERMS.md +46 -13
  4. package/README.md +5 -5
  5. package/addons/slidevideo/geometry.ts +63 -30
  6. package/addons/slidevideo/global-top.vue +41 -9
  7. package/addons/slidevideo/playback-entries.ts +17 -6
  8. package/addons/slidevideo/preview.ts +27 -15
  9. package/dist/adapters/browser-runtime.d.ts +3 -0
  10. package/dist/adapters/elevenlabs.d.ts +1 -0
  11. package/dist/adapters/elevenlabs.js +8 -4
  12. package/dist/adapters/powerpoint.d.ts +7 -4
  13. package/dist/adapters/powerpoint.js +123 -34
  14. package/dist/adapters/slidev-inspection.d.ts +5 -2
  15. package/dist/adapters/slidev-inspection.js +5 -6
  16. package/dist/adapters/slidev-server.js +136 -15
  17. package/dist/adapters/slidev.d.ts +12 -4
  18. package/dist/adapters/slidev.js +356 -70
  19. package/dist/annotation-paint.d.ts +65 -11
  20. package/dist/annotation-paint.js +290 -10
  21. package/dist/annotations.d.ts +13 -8
  22. package/dist/annotations.js +620 -89
  23. package/dist/assembly.d.ts +48 -40
  24. package/dist/assembly.js +72 -28
  25. package/dist/calibration.js +5 -4
  26. package/dist/cli.js +180 -39
  27. package/dist/compositor.d.ts +38 -6
  28. package/dist/compositor.js +299 -46
  29. package/dist/contracts.d.ts +96 -35
  30. package/dist/contracts.js +2 -1
  31. package/dist/executables.d.ts +2 -0
  32. package/dist/executables.js +27 -8
  33. package/dist/media.d.ts +12 -1
  34. package/dist/media.js +53 -4
  35. package/dist/pipeline.d.ts +36 -10
  36. package/dist/pipeline.js +163 -46
  37. package/dist/preview/contracts.d.ts +3 -3
  38. package/dist/preview/player.js +20 -15
  39. package/dist/preview/server.d.ts +2 -1
  40. package/dist/preview/server.js +8 -7
  41. package/dist/run.d.ts +1 -1
  42. package/dist/run.js +8 -3
  43. package/dist/setup-install.d.ts +1 -0
  44. package/dist/setup-install.js +8 -1
  45. package/dist/setup.d.ts +29 -8
  46. package/dist/setup.js +183 -76
  47. package/dist/skill-install.d.ts +35 -0
  48. package/dist/skill-install.js +132 -0
  49. package/dist/speech.js +10 -6
  50. package/dist/storyboard.js +12 -6
  51. package/dist/timing.js +2 -2
  52. package/package.json +4 -3
  53. package/schemas/annotation-geometry.v1.json +260 -28
  54. package/schemas/run-manifest.v1.json +31 -0
  55. package/schemas/schedule.v1.json +655 -1
  56. package/schemas/storyboard.v1.json +558 -33
  57. package/skills/slidevideo/SKILL.md +11 -9
  58. package/skills/slidevideo/references/decks.md +228 -0
  59. package/skills/slidevideo/references/production.md +17 -12
  60. package/skills/slidevideo/references/storyboard.md +71 -38
  61. package/tools/powerpoint/powerpoint.ps1 +52 -41
  62. package/tools/powerpoint/preview.ps1 +5 -5
  63. package/schemas/schedule.v2.json +0 -496
  64. package/schemas/storyboard.v2.json +0 -802
@@ -11,6 +11,8 @@ type Browser = {
11
11
  };
12
12
  export declare function withExecutables<T>(overrides: ToolPaths, run: () => T): T;
13
13
  export declare function configuredLicense(): boolean;
14
+ export declare function configuredElevenLabsKey(): string | undefined;
15
+ export declare function saveElevenLabsKey(key: string): Promise<void>;
14
16
  export declare function saveExecutablePaths(paths: ToolPaths): Promise<void>;
15
17
  export declare function saveLicenseKey(key: string | null): Promise<void>;
16
18
  export declare function isExecutable(path: string): boolean;
@@ -9,6 +9,8 @@ import { edgePython, managedBrowserDirectory, userConfigFile } from './installat
9
9
  import { licenseStatus, revocationMessage } from './license-status.js';
10
10
  export const toolNames = ['browser', 'python', 'ffmpeg', 'ffprobe'];
11
11
  const windows = process.platform === 'win32';
12
+ const macos = process.platform === 'darwin';
13
+ const macosExtraDirectories = macos ? ['/opt/homebrew/bin', '/usr/local/bin'] : [];
12
14
  const environmentPaths = { browser: 'SLIDEVIDEO_CHROMIUM', python: 'SLIDEVIDEO_PYTHON' };
13
15
  const executableScope = new AsyncLocalStorage();
14
16
  function readConfig() {
@@ -19,6 +21,9 @@ function readConfig() {
19
21
  (configuration.licensed !== undefined && typeof configuration.licensed !== 'boolean')) {
20
22
  throw new Error('Expected version 1 and an optional boolean licensed field');
21
23
  }
24
+ if (configuration.elevenlabs_api_key !== undefined && typeof configuration.elevenlabs_api_key !== 'string') {
25
+ throw new Error('Expected a string elevenlabs_api_key');
26
+ }
22
27
  const paths = configuration.paths;
23
28
  if (paths !== undefined && (!paths || typeof paths !== 'object' || Array.isArray(paths) ||
24
29
  Object.entries(paths).some(([tool, path]) => !toolNames.some(name => name === tool) || typeof path !== 'string' || !isAbsolute(path)))) {
@@ -41,6 +46,12 @@ export function configuredLicense() {
41
46
  console.error(revocationMessage);
42
47
  return status === 'active';
43
48
  }
49
+ export function configuredElevenLabsKey() {
50
+ return (executableScope.getStore()?.configuration ?? readConfig()).elevenlabs_api_key;
51
+ }
52
+ export function saveElevenLabsKey(key) {
53
+ return updateConfig(configuration => { configuration.elevenlabs_api_key = key; });
54
+ }
44
55
  export function saveExecutablePaths(paths) {
45
56
  return updateConfig(configuration => { configuration.paths = { ...configuration.paths, ...paths }; });
46
57
  }
@@ -100,18 +111,24 @@ export function browserCandidates() {
100
111
  const windowsRoots = [process.env.LOCALAPPDATA, process.env.ProgramFiles, process.env['ProgramFiles(x86)']].filter((path) => !!path);
101
112
  const locations = (...parts) => windowsRoots.map(root => join(root, ...parts));
102
113
  record('Chromium', [
103
- ...(windows ? locations('Chromium', 'Application', 'chrome.exe') : ['/usr/lib/chromium/chromium']),
114
+ ...(windows ? locations('Chromium', 'Application', 'chrome.exe')
115
+ : macos ? ['/Applications/Chromium.app/Contents/MacOS/Chromium']
116
+ : ['/usr/lib/chromium/chromium']),
104
117
  findOnPath('chromium'), findOnPath('chromium-browser'),
105
- ...(windows ? [] : ['/snap/bin/chromium']),
118
+ ...(windows || macos ? [] : ['/snap/bin/chromium']),
106
119
  chromium.executablePath(),
107
120
  ]);
108
121
  record('Google Chrome', [
109
122
  findOnPath('google-chrome'), findOnPath('google-chrome-stable'),
110
- ...(windows ? [findOnPath('chrome'), ...locations('Google', 'Chrome', 'Application', 'chrome.exe')] : ['/opt/google/chrome/chrome']),
123
+ ...(windows ? [findOnPath('chrome'), ...locations('Google', 'Chrome', 'Application', 'chrome.exe')]
124
+ : macos ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']
125
+ : ['/opt/google/chrome/chrome']),
111
126
  ]);
112
127
  record('Microsoft Edge', [
113
128
  findOnPath('microsoft-edge'), findOnPath('microsoft-edge-stable'),
114
- ...(windows ? [findOnPath('msedge'), ...locations('Microsoft', 'Edge', 'Application', 'msedge.exe')] : ['/opt/microsoft/msedge/msedge']),
129
+ ...(windows ? [findOnPath('msedge'), ...locations('Microsoft', 'Edge', 'Application', 'msedge.exe')]
130
+ : macos ? ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge']
131
+ : ['/opt/microsoft/msedge/msedge']),
115
132
  ]);
116
133
  return [...found.values()];
117
134
  }
@@ -122,7 +139,7 @@ export function browserName(path) {
122
139
  const name = basename(path).toLowerCase();
123
140
  return browserCandidates().find(browser => browser.path === path)?.name
124
141
  ?? (name.includes('edge') ? 'Microsoft Edge' : name.includes('chromium') ? 'Chromium'
125
- : /(?:^|-)chrome(?:-stable)?(?:\.exe)?$/.test(name) ? 'Google Chrome' : 'Custom browser');
142
+ : /(?:^|[-\s])chrome(?:-stable)?(?:\.exe)?$/.test(name) ? 'Google Chrome' : 'Custom browser');
126
143
  }
127
144
  export function toolCandidate(tool) {
128
145
  const context = executableScope.getStore();
@@ -148,11 +165,13 @@ export function discoverExecutable(tool) {
148
165
  path = browserCandidates().find(browser => browser.name === 'Chromium')?.path;
149
166
  else if (tool === 'python') {
150
167
  const managed = edgePython();
151
- path = isExecutable(managed) ? managed : windows ? findOnPath('py') ?? findOnPath('python') : findOnPath('python3') ?? findOnPath('python');
168
+ path = isExecutable(managed) ? managed : windows ? findOnPath('py') ?? findOnPath('python') : findOnPath('python3', macosExtraDirectories) ?? findOnPath('python', macosExtraDirectories);
152
169
  }
153
170
  else {
154
- const wingetLinks = windows && process.env.LOCALAPPDATA ? [join(process.env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links')] : [];
155
- path = findOnPath(tool, wingetLinks);
171
+ const extraDirectories = windows && process.env.LOCALAPPDATA
172
+ ? [join(process.env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links')]
173
+ : macosExtraDirectories;
174
+ path = findOnPath(tool, extraDirectories);
156
175
  }
157
176
  return path;
158
177
  }
package/dist/media.d.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import type { MediaProperties } from './contracts.js';
3
- export declare const executionScope: AsyncLocalStorage<AbortSignal>;
3
+ export type ExecutionContext = {
4
+ signal: AbortSignal;
5
+ bounded: boolean;
6
+ };
7
+ export declare const executionScope: AsyncLocalStorage<ExecutionContext>;
8
+ export declare function executionSignal(): AbortSignal | undefined;
9
+ export declare function hasStageDeadline(): boolean;
4
10
  export declare function execute(command: string, args: string[], timeout?: number, env?: NodeJS.ProcessEnv): Promise<Buffer>;
5
11
  export declare const digest: (value: string | Buffer) => string;
6
12
  export declare function hashFile(path: string): Promise<string>;
@@ -8,5 +14,10 @@ export declare function json<T>(path: string): Promise<T>;
8
14
  export declare function saveJson(path: string, value: unknown): Promise<void>;
9
15
  export declare function probe(path: string): Promise<MediaProperties>;
10
16
  export declare function decode(path: string): Promise<void>;
17
+ export declare function balancedSum(terms: readonly string[]): string;
18
+ export declare function ffmpegFilterScriptFlags(ffmpegPath?: string): Promise<{
19
+ complex: string;
20
+ video: string;
21
+ }>;
11
22
  export declare function audioDuration(path: string): Promise<number>;
12
23
  export declare function videoFramePeriod(path: string): Promise<number>;
package/dist/media.js CHANGED
@@ -1,21 +1,26 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { spawn } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
+ import { createReadStream } from 'node:fs';
4
5
  import { readFile, mkdir, writeFile, rename } from 'node:fs/promises';
5
6
  import { dirname } from 'node:path';
6
7
  import { ProductionError } from './errors.js';
7
8
  import { executable } from './executables.js';
8
9
  export const executionScope = new AsyncLocalStorage();
9
- export async function execute(command, args, timeout = 120000, env = process.env) {
10
+ export function executionSignal() { return executionScope.getStore()?.signal; }
11
+ export function hasStageDeadline() { return executionScope.getStore()?.bounded === true; }
12
+ export async function execute(command, args, timeout, env = process.env) {
10
13
  if (command === 'ffmpeg' || command === 'ffprobe')
11
14
  command = executable(command);
12
15
  return new Promise((resolve, reject) => {
13
- const signal = executionScope.getStore();
16
+ const context = executionScope.getStore();
17
+ const signal = context?.signal;
14
18
  signal?.throwIfAborted();
15
19
  const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], env, signal, killSignal: 'SIGKILL', windowsHide: true });
16
20
  const out = [];
17
21
  const err = [];
18
- const timer = setTimeout(() => { child.kill('SIGKILL'); }, timeout);
22
+ const limit = timeout ?? (context?.bounded ? undefined : 120000);
23
+ const timer = limit !== undefined ? setTimeout(() => { child.kill('SIGKILL'); }, limit) : undefined;
19
24
  child.stdout.on('data', data => out.push(data));
20
25
  child.stderr.on('data', data => err.push(data));
21
26
  child.on('error', error => { clearTimeout(timer); reject(new ProductionError('DEPENDENCY', `${command}: ${error.message}`, 3)); });
@@ -29,7 +34,21 @@ export async function execute(command, args, timeout = 120000, env = process.env
29
34
  });
30
35
  }
31
36
  export const digest = (value) => createHash('sha256').update(value).digest('hex');
32
- export async function hashFile(path) { return digest(await readFile(path)); }
37
+ export async function hashFile(path) {
38
+ executionSignal()?.throwIfAborted();
39
+ const hash = createHash('sha256');
40
+ const stream = createReadStream(path);
41
+ try {
42
+ for await (const chunk of stream) {
43
+ executionSignal()?.throwIfAborted();
44
+ hash.update(chunk);
45
+ }
46
+ return hash.digest('hex');
47
+ }
48
+ finally {
49
+ stream.destroy();
50
+ }
51
+ }
33
52
  export async function json(path) { return JSON.parse(await readFile(path, 'utf8')); }
34
53
  export async function saveJson(path, value) {
35
54
  await mkdir(dirname(path), { recursive: true });
@@ -43,6 +62,36 @@ export async function probe(path) {
43
62
  return { width: video?.width ?? 0, height: video?.height ?? 0, fps: d ? n / d : 0, duration_ms: Number(data.format.duration) * 1000, has_audio: data.streams.some((s) => s.codec_type === 'audio') };
44
63
  }
45
64
  export async function decode(path) { await execute('ffmpeg', ['-v', 'error', '-xerror', '-i', path, '-f', 'null', '-']); }
65
+ export function balancedSum(terms) {
66
+ if (terms.length === 0)
67
+ return '0';
68
+ let level = [...terms];
69
+ while (level.length > 1) {
70
+ const next = [];
71
+ for (let index = 0; index < level.length; index += 2) {
72
+ next.push(index + 1 < level.length ? `(${level[index]}+${level[index + 1]})` : level[index]);
73
+ }
74
+ level = next;
75
+ }
76
+ return level[0];
77
+ }
78
+ const filterScriptFlags = new Map();
79
+ export function ffmpegFilterScriptFlags(ffmpegPath = executable('ffmpeg')) {
80
+ let cached = filterScriptFlags.get(ffmpegPath);
81
+ if (!cached) {
82
+ cached = execute(ffmpegPath, ['-version'], 10000).then(output => {
83
+ const major = Number(output.toString().match(/^\s*libavfilter\s+(\d+)\./m)?.[1] ?? 0);
84
+ return major >= 10
85
+ ? { complex: '-/filter_complex', video: '-/vf' }
86
+ : { complex: '-filter_complex_script', video: '-filter_script:v' };
87
+ }).catch(error => {
88
+ filterScriptFlags.delete(ffmpegPath);
89
+ throw error;
90
+ });
91
+ filterScriptFlags.set(ffmpegPath, cached);
92
+ }
93
+ return cached;
94
+ }
46
95
  export async function audioDuration(path) { const pcm = await execute('ffmpeg', ['-v', 'error', '-i', path, '-vn', '-ac', '1', '-ar', '48000', '-f', 's16le', '-']); return pcm.length / 96; }
47
96
  export async function videoFramePeriod(path) {
48
97
  const data = JSON.parse((await execute('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_frames', '-show_entries', 'frame=best_effort_timestamp_time,duration_time', '-of', 'json', path])).toString());
@@ -1,14 +1,26 @@
1
- import type { ProgressReporter } from './contracts.js';
1
+ import { type FrameRate, type Viewport, type ProgressReporter } from './contracts.js';
2
+ export type InspectInput = {
3
+ kind: 'storyboard';
4
+ storyboard: string;
5
+ viewport?: Viewport;
6
+ } | {
7
+ kind: 'deck';
8
+ deck: string;
9
+ viewport?: Viewport;
10
+ };
2
11
  export type Options = {
3
12
  command: string;
4
13
  storyboard?: string;
14
+ inspect?: InspectInput;
15
+ viewport?: Viewport;
16
+ fps?: FrameRate;
5
17
  run?: string;
6
18
  cache?: string;
7
19
  output?: string;
8
20
  resume?: boolean;
9
21
  export?: string;
10
22
  verify_timing?: boolean;
11
- timeout_ms: number;
23
+ timeout_ms?: number;
12
24
  progress?: ProgressReporter;
13
25
  };
14
26
  export declare function produce(options: Options): Promise<{
@@ -21,30 +33,44 @@ export declare function produce(options: Options): Promise<{
21
33
  run_id: string | undefined;
22
34
  timing_status: string;
23
35
  } | {
36
+ version: number;
37
+ command: string;
38
+ status: string;
39
+ artifacts: Record<string, string>;
40
+ warnings: string[];
41
+ completed_stages: string[];
42
+ run_id: string | undefined;
43
+ timing_status: string;
24
44
  inspection: {
25
45
  annotation_targets: {
26
46
  slide: string;
47
+ clicks?: number;
27
48
  targets: {
28
49
  identity: string;
29
50
  description: string;
30
51
  }[];
31
52
  }[] | undefined;
53
+ dimensions?: Viewport;
32
54
  slides: {
33
55
  id: string;
56
+ alias?: string;
34
57
  index: number;
35
58
  clicks: number;
36
59
  clicks_known?: boolean;
60
+ click_durations_ms?: number[];
37
61
  }[];
38
62
  media_ids: string[];
63
+ media?: {
64
+ id: string;
65
+ slide: string;
66
+ sha256: string;
67
+ duration_ms: number;
68
+ }[];
39
69
  files: string[];
40
70
  capabilities: string[];
71
+ unsupported?: {
72
+ slide?: string;
73
+ reason: string;
74
+ }[];
41
75
  };
42
- version: number;
43
- command: string;
44
- status: string;
45
- artifacts: Record<string, string>;
46
- warnings: string[];
47
- completed_stages: string[];
48
- run_id: string | undefined;
49
- timing_status: string;
50
76
  }>;
package/dist/pipeline.js CHANGED
@@ -1,14 +1,46 @@
1
1
  import { mkdir, readdir, rm } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
+ import { defaultVideoOutput, defaultViewport } from './contracts.js';
3
4
  import { loadStoryboard, fingerprint } from './storyboard.js';
4
5
  import { presentationAdapter, ttsAdapters } from './adapters/registry.js';
5
6
  import { generateSpeech } from './speech.js';
6
7
  import { resolveTiming } from './timing.js';
7
8
  import { Run, filesIn } from './run.js';
8
- import { json, saveJson, execute, executionScope, hashFile } from './media.js';
9
+ import { json, saveJson, execute, executionScope } from './media.js';
9
10
  import { assemble } from './assembly.js';
10
11
  import { configuredLicense } from './executables.js';
11
12
  import { requireCondition, ProductionError } from './errors.js';
13
+ const baseStageTimeoutMs = 180_000;
14
+ function defaultStageTimeoutMs(stage, story, options) {
15
+ if (stage === 'tts')
16
+ return Math.max(baseStageTimeoutMs, 60_000 + story.narration.length * 90_000);
17
+ if (stage === 'resolve')
18
+ return baseStageTimeoutMs;
19
+ const duration = options.schedule?.duration_ms ?? 0;
20
+ if (stage === 'record') {
21
+ return options.verifyTiming
22
+ ? Math.ceil(duration * 2) + 240_000
23
+ : Math.ceil(duration * 1.25) + baseStageTimeoutMs;
24
+ }
25
+ const pixelScale = Math.max(1, (options.video.width * options.video.height) / (1920 * 1080));
26
+ const hasEffects = (options.schedule?.annotations.length ?? 0) > 0
27
+ || (options.schedule?.overlays?.length ?? 0) > 0
28
+ || !options.licensed;
29
+ return Math.ceil(duration * pixelScale * (options.verifyTiming || hasEffects ? 2 : 1)) + baseStageTimeoutMs;
30
+ }
31
+ function stageTimeoutError(stage, deadline, plannedDurationMs) {
32
+ const minutes = Number((deadline / 60_000).toFixed(2));
33
+ const detail = plannedDurationMs !== undefined
34
+ ? `${stage} exceeded its ${minutes} min timeout (${deadline} ms) for ${plannedDurationMs} ms planned playback`
35
+ : `${stage} exceeded its ${minutes} min timeout (${deadline} ms)`;
36
+ const context = {
37
+ stage,
38
+ timeout_ms: deadline,
39
+ timeout_minutes: minutes,
40
+ ...(plannedDurationMs !== undefined ? { planned_duration_ms: plannedDurationMs } : {}),
41
+ };
42
+ return new ProductionError('STAGE_TIMEOUT', detail, stage === 'tts' ? 4 : stage === 'record' ? 5 : 7, context);
43
+ }
12
44
  export async function produce(options) {
13
45
  let run;
14
46
  let lock;
@@ -20,6 +52,32 @@ export async function produce(options) {
20
52
  process.once('SIGTERM', interrupt);
21
53
  try {
22
54
  options.progress?.('Validating inputs');
55
+ if (options.command === 'inspect' && options.inspect?.kind === 'deck') {
56
+ const target = options.inspect;
57
+ const deck = resolve(target.deck);
58
+ const adapter = presentationAdapter(deck);
59
+ requireCondition(adapter.inspectTargets, 'ANNOTATION_CAPABILITY', `Adapter ${adapter.id} does not expose annotation targets`, 3);
60
+ activeAdapter = adapter;
61
+ try {
62
+ const { inspection, annotation_targets } = await executionScope.run({ signal: controller.signal, bounded: false }, async () => {
63
+ const inspected = await adapter.inspect(deck);
64
+ const viewport = target.viewport ?? inspected.dimensions ?? defaultViewport;
65
+ const targets = await adapter.inspectTargets(deck, viewport);
66
+ return { inspection: inspected, annotation_targets: targets };
67
+ });
68
+ controller.signal.throwIfAborted();
69
+ const warnings = [];
70
+ if (inspection.slides.some(slide => slide.clicks_known === false))
71
+ warnings.push('Slides without explicit click bounds require runtime reveal checks before recording.');
72
+ if ((inspection.unsupported?.length ?? 0) > 0)
73
+ warnings.push('Deck contains unsupported native features. Adjust the deck before production.');
74
+ return { version: 1, command: options.command, status: 'completed', artifacts: {}, warnings, completed_stages: [], run_id: undefined, timing_status: 'not_evaluated', inspection: { ...inspection, annotation_targets } };
75
+ }
76
+ finally {
77
+ await adapter.cleanup();
78
+ activeAdapter = undefined;
79
+ }
80
+ }
23
81
  if (options.command === 'assemble') {
24
82
  requireCondition(options.run, 'RUN_REQUIRED', 'assemble requires --run');
25
83
  try {
@@ -34,8 +92,13 @@ export async function produce(options) {
34
92
  const story = await loadStoryboard(source);
35
93
  const overlays = story.overlays ?? [];
36
94
  const adapter = presentationAdapter(story.deck);
95
+ const initialViewport = options.command === 'inspect'
96
+ ? (options.inspect?.kind === 'storyboard' ? options.inspect.viewport : undefined) ?? options.viewport ?? defaultViewport
97
+ : options.command === 'validate'
98
+ ? options.viewport ?? defaultViewport
99
+ : undefined;
37
100
  const inspection = await adapter.inspect(story.deck);
38
- adapter.validate(story, inspection);
101
+ await adapter.validate(story, inspection, initialViewport ? { viewport: initialViewport } : undefined);
39
102
  for (const segment of story.narration) {
40
103
  const voice = segment.voice ?? story.voice;
41
104
  requireCondition(voice, 'VOICE_REQUIRED', `Narration ${segment.id} needs a voice`);
@@ -43,7 +106,7 @@ export async function produce(options) {
43
106
  requireCondition(tts, 'TTS_ADAPTER', `Unsupported TTS provider ${voice.provider}`, 3);
44
107
  tts.validate(voice);
45
108
  }
46
- const result = { version: 1, command: options.command, status: 'completed', artifacts: {}, warnings: story.cues.length || story.annotations?.length ||
109
+ const result = { version: 1, command: options.command, status: 'completed', artifacts: {}, warnings: story.cues.length || story.annotations.length ||
47
110
  overlays.some(overlay => overlay.visible?.some(interval => typeof interval.start !== 'number' || typeof interval.end !== 'number')) ? ['Phrase cues require paired speech alignment at resolution.'] : [], completed_stages: [], run_id: undefined, timing_status: 'not_evaluated' };
48
111
  if (story.cues.some(cue => cue.action.type === 'slide'))
49
112
  result.warnings.push('Phrase-driven navigation requires reveal target checks after resolution.');
@@ -53,7 +116,7 @@ export async function produce(options) {
53
116
  requireCondition(adapter.inspectTargets, 'ANNOTATION_CAPABILITY', `Adapter ${adapter.id} does not expose annotation targets`, 3);
54
117
  activeAdapter = adapter;
55
118
  try {
56
- const annotation_targets = await adapter.inspectTargets(story);
119
+ const annotation_targets = await executionScope.run({ signal: controller.signal, bounded: false }, () => adapter.inspectTargets(story.deck, initialViewport));
57
120
  controller.signal.throwIfAborted();
58
121
  return { ...result, inspection: { ...inspection, annotation_targets } };
59
122
  }
@@ -89,6 +152,7 @@ export async function produce(options) {
89
152
  throw error;
90
153
  }
91
154
  requireCondition(entries.length === 0, 'NEW_RUN_REQUIRED', 'build requires a new or empty directory. Use --resume for unchanged inputs.');
155
+ await adapter.validate(story, inspection, { viewport: options.viewport ?? defaultViewport });
92
156
  }
93
157
  await mkdir(directory, { recursive: true });
94
158
  lock = join(directory, '.lock');
@@ -105,11 +169,28 @@ export async function produce(options) {
105
169
  run = await Run.open(directory, source, fingerprints.inputs, fingerprints.input_hash);
106
170
  result.run_id = run.manifest.run_id;
107
171
  const recordedMode = run.manifest.verify_timing ?? (run.manifest.stages.record ? true : undefined);
108
- const production = { verify_timing: options.verify_timing ?? recordedMode ?? false };
172
+ const recordedVideo = run.manifest.video;
173
+ const video = {
174
+ width: options.viewport?.width ?? recordedVideo?.width ?? defaultVideoOutput.width,
175
+ height: options.viewport?.height ?? recordedVideo?.height ?? defaultVideoOutput.height,
176
+ fps: options.fps ?? recordedVideo?.fps ?? defaultVideoOutput.fps,
177
+ };
178
+ const production = { verify_timing: options.verify_timing ?? recordedMode ?? false, output: video };
109
179
  if (['build', 'record', 'assemble'].includes(options.command)) {
110
180
  requireCondition(recordedMode === undefined || recordedMode === production.verify_timing, 'RUN_MODE_MISMATCH', 'Timing verification differs from this run. Start a new run directory.');
111
- run.manifest.verify_timing = production.verify_timing;
112
- await run.save();
181
+ requireCondition(recordedVideo === undefined || (recordedVideo.width === video.width && recordedVideo.height === video.height && recordedVideo.fps === video.fps), 'RUN_MODE_MISMATCH', 'Output dimensions or frame rate differ from this run. Start a new run directory.');
182
+ if (!(options.command === 'build' && !options.resume) && (options.command !== 'assemble' || recordedVideo !== undefined)) {
183
+ await adapter.validate(story, inspection, { viewport: video });
184
+ }
185
+ if (options.command === 'build' || options.command === 'record') {
186
+ run.manifest.verify_timing = production.verify_timing;
187
+ run.manifest.video = video;
188
+ await run.save();
189
+ }
190
+ else if (recordedMode !== undefined) {
191
+ run.manifest.verify_timing = production.verify_timing;
192
+ await run.save();
193
+ }
113
194
  options.progress?.(production.verify_timing ? 'Timing verification enabled' : 'Timing verification skipped; the user reviews the video');
114
195
  }
115
196
  requireCondition(!options.output || !run.manifest.output || resolve(options.output) === run.manifest.output, 'OUTPUT_MISMATCH', 'Run is bound to a different output path');
@@ -117,12 +198,38 @@ export async function produce(options) {
117
198
  const schedulePath = join(directory, 'timing/schedule.json');
118
199
  const visualPath = join(directory, 'recording/visual.json');
119
200
  const reportPath = join(directory, 'assembly/report.json');
201
+ const resolveViewport = ['build', 'record', 'assemble'].includes(options.command) ? video : undefined;
202
+ const resolveSchedule = async () => {
203
+ const schedule = await resolveTiming(story, await json(speechPath));
204
+ await adapter.validate(story, inspection, { ...(resolveViewport ? { viewport: resolveViewport } : {}), schedule });
205
+ return schedule;
206
+ };
120
207
  const selected = options.command === 'build' ? ['tts', 'resolve', 'record', 'assemble'] : [options.command];
121
208
  const licensed = selected.includes('assemble') && (run.manifest.assembly_licensed ??
122
209
  (run.manifest.stages.assemble?.status === 'completed' || configuredLicense()));
210
+ const runBounded = async (targetStage, deadline, plannedDurationMs, work) => {
211
+ let timedOut = false;
212
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); void activeAdapter?.cleanup().catch(() => { }); }, deadline);
213
+ try {
214
+ try {
215
+ await executionScope.run({ signal: controller.signal, bounded: true }, work);
216
+ }
217
+ catch (error) {
218
+ if (timedOut)
219
+ throw stageTimeoutError(targetStage, deadline, plannedDurationMs);
220
+ throw error;
221
+ }
222
+ if (timedOut)
223
+ throw stageTimeoutError(targetStage, deadline, plannedDurationMs);
224
+ controller.signal.throwIfAborted();
225
+ }
226
+ finally {
227
+ clearTimeout(timer);
228
+ }
229
+ };
123
230
  for (const stage of selected) {
124
231
  const reused = run.manifest.stages[stage]?.status === 'completed';
125
- const labels = { validate: 'Input validation', tts: 'Speech generation', resolve: 'Timing resolution', record: 'Presentation preparation', assemble: 'Assembly and encoding' };
232
+ const labels = { tts: 'Speech generation', resolve: 'Timing resolution', record: 'Presentation preparation', assemble: 'Assembly and encoding' };
126
233
  options.progress?.(reused ? `Verifying saved ${stage}` : labels[stage]);
127
234
  if (interrupted)
128
235
  throw new ProductionError('INTERRUPTED', 'Production interrupted', 130);
@@ -145,31 +252,40 @@ export async function produce(options) {
145
252
  }
146
253
  requireCondition(existing.length === 0, 'RECORD_RETRY_NEW_RUN', 'Recording evidence already exists. Start a new run to preserve this attempt.');
147
254
  }
255
+ let schedule;
256
+ if (stage === 'record' && !reused) {
257
+ const resolveDeadline = options.timeout_ms ?? defaultStageTimeoutMs('resolve', story, { video, verifyTiming: production.verify_timing, licensed });
258
+ if (run.manifest.stages.resolve?.status === 'completed') {
259
+ await runBounded('resolve', resolveDeadline, undefined, async () => {
260
+ const resolved = await resolveSchedule();
261
+ await run.verify('resolve');
262
+ requireCondition(JSON.stringify(resolved) === JSON.stringify(await json(schedulePath)), 'SCHEDULE_MISMATCH', 'Resolved schedule changed');
263
+ });
264
+ }
265
+ else {
266
+ await run.stage('resolve', [schedulePath], () => runBounded('resolve', resolveDeadline, undefined, async () => {
267
+ await saveJson(schedulePath, await resolveSchedule());
268
+ }));
269
+ }
270
+ schedule = await json(schedulePath);
271
+ }
272
+ else if (stage === 'assemble' && !reused) {
273
+ schedule = await json(schedulePath);
274
+ }
148
275
  const artifacts = [];
276
+ const prehashed = {};
149
277
  const operation = async () => {
150
278
  if (stage === 'tts') {
151
279
  const speech = await generateSpeech(story, join(directory, 'speech'), ttsAdapters, options.cache, options.progress);
152
280
  artifacts.push(speechPath, ...speech.assets.map(asset => asset.audio));
153
281
  }
154
282
  if (stage === 'resolve') {
155
- const schedule = await resolveTiming(story, await json(speechPath));
156
- adapter.validate(story, inspection, schedule);
157
- await saveJson(schedulePath, schedule);
283
+ await saveJson(schedulePath, await resolveSchedule());
158
284
  artifacts.push(schedulePath);
159
285
  }
160
286
  if (stage === 'record') {
161
- const schedule = await resolveTiming(story, await json(speechPath));
162
- if (run.manifest.stages.resolve?.status === 'completed') {
163
- await run.verify('resolve');
164
- requireCondition(JSON.stringify(schedule) === JSON.stringify(await json(schedulePath)), 'SCHEDULE_MISMATCH', 'Resolved schedule changed');
165
- }
166
- else {
167
- await saveJson(schedulePath, schedule);
168
- run.manifest.stages.resolve = { status: 'completed', artifacts: { [schedulePath]: await hashFile(schedulePath) } };
169
- await run.save();
170
- }
171
- adapter.validate(story, inspection, schedule);
172
287
  activeAdapter = adapter;
288
+ let recordError;
173
289
  try {
174
290
  await adapter.prepare(story, schedule, join(directory, 'recording'), production);
175
291
  const visual = await adapter.execute(options.progress);
@@ -178,23 +294,39 @@ export async function produce(options) {
178
294
  artifacts.push(visual.file, ...visual.timing.checks.map(check => check.evidence));
179
295
  Object.assign(run.manifest.versions, visual.provenance.dependencies, { [`presentation:${visual.provenance.adapter}`]: visual.provenance.version });
180
296
  }
297
+ catch (error) {
298
+ recordError = error;
299
+ throw error;
300
+ }
181
301
  finally {
182
- await adapter.cleanup();
183
- activeAdapter = undefined;
302
+ try {
303
+ await adapter.cleanup();
304
+ }
305
+ catch (cleanupError) {
306
+ if (!recordError && !interrupted && !controller.signal.aborted)
307
+ throw cleanupError;
308
+ }
309
+ finally {
310
+ activeAdapter = undefined;
311
+ }
184
312
  }
185
313
  artifacts.push(...await filesIn(join(directory, 'recording')));
186
314
  run.manifest.versions.ffmpeg = (await execute('ffmpeg', ['-version'])).toString().split('\n')[0];
187
315
  }
188
316
  if (stage === 'assemble') {
317
+ requireCondition(run.manifest.video, 'RUN_MANIFEST', 'Run manifest has no recorded video output settings. Start a new run directory.');
189
318
  const output = resolve(options.output ?? run.manifest.output ?? join(directory, 'final.mp4'));
190
319
  requireCondition(!run.manifest.output || run.manifest.output === output, 'OUTPUT_MISMATCH', 'Run is bound to a different output path');
191
- run.manifest.output = output;
192
- run.manifest.assembly_licensed = licensed;
193
- await run.save();
194
320
  try {
195
- await assemble(story, await json(schedulePath), await json(speechPath), await json(visualPath), join(directory, 'assembly'), output, {
321
+ const { outputSha256 } = await assemble(schedule, await json(speechPath), await json(visualPath), join(directory, 'assembly'), output, {
196
322
  ...production, licensed, inputHashes: run.manifest.inputs,
323
+ onOutputReserved: async () => {
324
+ run.manifest.output = output;
325
+ run.manifest.assembly_licensed = licensed;
326
+ await run.save();
327
+ },
197
328
  });
329
+ prehashed[output] = outputSha256;
198
330
  }
199
331
  catch (error) {
200
332
  if (error instanceof ProductionError && error.exitCode === 3)
@@ -204,24 +336,9 @@ export async function produce(options) {
204
336
  artifacts.push(output, reportPath, ...await filesIn(join(directory, 'assembly')));
205
337
  }
206
338
  };
207
- let timedOut = false;
208
- const timer = setTimeout(() => { timedOut = true; controller.abort(); void activeAdapter?.cleanup().catch(() => { }); }, options.timeout_ms);
209
- try {
210
- await run.stage(stage, artifacts, async () => {
211
- try {
212
- await executionScope.run(controller.signal, operation);
213
- }
214
- catch (error) {
215
- if (timedOut)
216
- throw new ProductionError('STAGE_TIMEOUT', `${stage} exceeded ${options.timeout_ms} ms`, stage === 'tts' ? 4 : stage === 'record' ? 5 : 7);
217
- throw error;
218
- }
219
- controller.signal.throwIfAborted();
220
- });
221
- }
222
- finally {
223
- clearTimeout(timer);
224
- }
339
+ const deadline = options.timeout_ms ?? defaultStageTimeoutMs(stage, story, { schedule, video, verifyTiming: production.verify_timing, licensed });
340
+ const plannedDurationMs = schedule?.duration_ms;
341
+ await run.stage(stage, artifacts, () => runBounded(stage, deadline, plannedDurationMs, operation), prehashed);
225
342
  options.progress?.(`${reused ? 'Reused' : 'Completed'} ${stage}`);
226
343
  }
227
344
  if (options.export) {
@@ -26,9 +26,9 @@ export type NativeFrame = {
26
26
  height: number;
27
27
  };
28
28
  content: Rectangle;
29
- annotations: {
30
- id: string;
31
- bounds: Rectangle;
29
+ targets: {
30
+ key: string;
31
+ fragments: Rectangle[];
32
32
  }[];
33
33
  image: string;
34
34
  };