Spaces:
Configuration error

File size: 8,085 Bytes
023064b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env tsx
/**
 * agentic-cli.ts β€” SIMPLE JSON-INPUT CLI for the agentic pipeline.
 *
 * Reads `input/agentic-scripts.json`, processes each job through the
 * full agentic pipeline (plan β†’ acquire β†’ verify β†’ decide β†’ gate β†’ render).
 *
 * Supports:
 *   - Custom scripts with [Visual: filename] (local assets) tags
 *   - Custom scripts with [Visual: search keywords] (online stock) tags
 *   - localAssets/videoClips arrays for explicit asset binding
 *   - All agentic pipeline benefits (gates, AI brain, plugins, operations)
 *
 * Usage:  npx tsx src/adapters/cli/agentic-cli.ts
 *         npm run generate:agentic
 */
import 'dotenv/config';
import * as fs from 'fs';
import * as path from 'path';
import { runAgenticPipeline } from '../../agentic/orchestrator/pipeline.js';
import { renderAgenticSlideshow } from '../../agentic/orchestrator/render.js';
import { AgenticCliJob, buildPipelineRequest } from './cli-job.js';

// ─── Config ──────────────────────────────────────────────────────────────────

const INPUT_DIR = path.join(process.cwd(), 'input', 'scripts');
const SCRIPTS_FILE = path.join(INPUT_DIR, 'agentic-scripts.json');

// ─── Config ──────────────────────────────────────────────────────────────────

// ─── CLI Entry ──────────────────────────────────────────────────────────────

async function main() {
    console.log('╔═══════════════════════════════════════════════════╗');
    console.log('β•‘   Agentic Video Pipeline CLI                      β•‘');
    console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•');
    console.log();

    if (!fs.existsSync(SCRIPTS_FILE)) {
        console.error(`❌ Input file not found: ${SCRIPTS_FILE}`);
        console.error('   Create an agentic-scripts.json file in input/');
        console.error('   See input/agentic-scripts.example.json for format.');
        process.exit(1);
    }

    const raw = fs.readFileSync(SCRIPTS_FILE, 'utf-8');
    let jobs: AgenticCliJob[];
    try {
        jobs = JSON.parse(raw);
        if (!Array.isArray(jobs) || jobs.length === 0) {
            console.error('❌ agentic-scripts.json must be a non-empty array.');
            process.exit(1);
        }
    } catch {
        console.error(`❌ JSON parse error in ${SCRIPTS_FILE}`);
        process.exit(1);
    }

    let completed = 0;
    let failed = 0;

    for (let i = 0; i < jobs.length; i++) {
        const job = jobs[i];
        const jobLabel = job.title || `Job ${i + 1}`;
        console.log(`\n${'─'.repeat(55)}`);
        console.log(`  Job ${i + 1}/${jobs.length}: "${jobLabel}"`);
        console.log(`${'─'.repeat(55)}`);

        const topic = job.topic ?? job.title ?? 'Untitled video';
        const id = sanitizeId(job.id ?? job.title ?? `job_${Date.now()}`);

        const req = buildPipelineRequest(job, id, topic);

        try {
            const result = await runAgenticPipeline(
                req,
                (progress) => {
                    const pct = progress.percent?.toFixed(0) ?? '??';
                    const stage = progress.stage ?? '?';
                    const msg = (progress.message ?? '').substring(0, 80);
                    if (pct === '100') {
                        process.stdout.write(`\r  βœ… [${stage}] ${msg}\n`);
                    } else {
                        process.stdout.write(`\r  ⏳ [${pct}%] ${stage}: ${msg}  `);
                    }
                },
            );

            // dryRun produces no gate/manifest by design β€” treat successful
            // planning as a completed job (no render expected).
            if (req.dryRun) {
                completed++;
                console.log(`\n  βœ… DRY RUN OK β€” ${result.plan.scenes.length} scenes planned, ${result.plan.totalDurationSec}s`);
                console.log(`  πŸ§ͺ Control-surface validated (no assets fetched, no render)`);
            } else if (result.gate.pass && result.manifest) {
                completed++;
                console.log(`\n  βœ… Gate PASS β€” ${result.plan.scenes.length} scenes, ${result.plan.totalDurationSec}s`);
                console.log(`  πŸ“ Workspace: ${result.workspace.root}`);
                console.log(`  🎬 Rendering video...`);

                // Render the final video using the agentic slideshow renderer
                const outPath = path.resolve(process.cwd(), 'output', id);
                fs.mkdirSync(outPath, { recursive: true });

                // Orientation -> render dimensions. Without this the renderer
                // falls back to its hardcoded 720x1280 (portrait) default and
                // every orientation renders as portrait (verified visually).
                const ORIENT_DIMS: Record<string, { w: number; h: number }> = {
                    portrait: { w: 720, h: 1280 },
                    landscape: { w: 1280, h: 720 },
                    square: { w: 1080, h: 1080 },
                };
                const orient = (job.orientation || 'portrait').toLowerCase();
                const dims = ORIENT_DIMS[orient] ?? ORIENT_DIMS.portrait;
                const finalMp4 = await renderAgenticSlideshow(result, {
                    outPath: path.join(outPath, `${job.title || 'output'}.mp4`),
                    dimensions: dims,
                    crossfadeSec: 0.3,
                    burnCaptions: job.captions !== 'none',
                    intro: job.intro,
                    outro: job.outro,
                    // Phase 1 β€” extended render opts
                    sfx: job.sfx,
                    captions: job.captions,
                    captionTheme: job.captionTheme,
                    kinetic: job.kineticText,
                    kenBurns: job.kenBurns,
                    preset: job.preset,
                    jCutSec: job.jCutSec,
                    brand: job.brand,
                });

                if (fs.existsSync(finalMp4)) {
                    const sizeKb = Math.round(fs.statSync(finalMp4).size / 1024);
                    console.log(`  🎬 Output: ${finalMp4} (${sizeKb} KB)`);
                } else {
                    console.log(`  ⏳ Output pending β€” check workspace: ${result.workspace.root}/render/`);
                }
            } else {
                failed++;
                const failReasons = result.gate.checks
                    .filter((c) => !c.pass)
                    .map((c) => `    ❌ ${c.id}: ${c.label} β€” ${c.detail}`)
                    .join('\n');
                console.log(`\n  ❌ Gate FAIL β€” ${result.plan.scenes.length} scenes`);
                if (failReasons) console.log(failReasons);
            }
        } catch {
            failed++;
            console.error(`\n  ❌ Job failed with error`);
        }
    }

    // ─── Summary ────────────────────────────────────────────────────────────
    console.log(`\n${'═'.repeat(55)}`);
    console.log(`  Summary: ${completed} completed, ${failed} failed out of ${jobs.length} job(s)`);
    if (failed > 0) process.exitCode = 1;
}

function sanitizeId(name: string): string {
    return name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '_')
        .replace(/^_|_$/g, '')
        .substring(0, 64) || `job_${Date.now()}`;
}

main().catch((e) => {
    console.error(`\n❌ Fatal: ${e.message ?? e}`);
    process.exit(1);
});