π¬ Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
feat: add multi-provider AI video generation
darkzOGx486ea21a8189
diff --git a/.env.example b/.env.exampleindex 886877e..824e1ae 100644--- a/.env.example+++ b/.env.example@@ -14,8 +14,36 @@# ELEVENLABS_API_KEY=your-elevenlabs-api-key-here# ELEVENLABS_VOICE_ID=your-voice-id-here-# Replicate (optional, for AI video generation)-# REPLICATE_API_KEY=your-replicate-api-key-here+# AI video generation (optional; local slideshow is the no-cost default)+# VIDEO_PROVIDER=slideshow+# VIDEO_PROVIDER_ORDER=seedance,minimax_h3,google_omni,kling,wan,slideshow+# VIDEO_GENERATION_MODE=hybrid+# VIDEO_CLIP_DURATION=8+# VIDEO_MAX_GENERATED_SECONDS=60+# VIDEO_RESOLUTION=720p+# VIDEO_ASPECT_RATIO=16:9++# Seedance 2.5 through Replicate+# REPLICATE_API_TOKEN=your-replicate-api-token-here+# REPLICATE_API_KEY=your-replicate-api-token-here+# SEEDANCE_MODEL=bytedance/seedance-2.5++# MiniMax H3+# MINIMAX_API_KEY=your-minimax-api-key-here+# MINIMAX_VIDEO_MODEL=MiniMax-H3++# Google Gemini Omni Flash uses GEMINI_API_KEY above+# GEMINI_VIDEO_MODEL=gemini-omni-flash-preview++# Kling 3.0 Omni+# KLING_ACCESS_KEY=your-kling-access-key-here+# KLING_SECRET_KEY=your-kling-secret-key-here+# KLING_VIDEO_MODEL=kling-v3-omni++# Alibaba Wan 2.7+# DASHSCOPE_API_KEY=your-dashscope-api-key-here+# DASHSCOPE_VIDEO_ENDPOINT=https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis+# DASHSCOPE_TASK_ENDPOINT=https://dashscope-intl.aliyuncs.com/api/v1/tasks# Gemini media generation (used when GEMINI_API_KEY is your provider)# GEMINI_IMAGE_MODEL=gemini-3.1-flash-imagediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 960e1f5..5a72f3a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,12 @@## Unreleased+- Added a durable video-provider layer for Seedance 2.5, MiniMax H3, Gemini Omni Flash, Kling 3.0 Omni, and Wan 2.7+- Added capability-aware automatic routing with local slideshow as the no-cost default and final fallback+- Added persistent external media task IDs, provider/model evidence, cancellation handoff where supported, and restart-safe reuse of known provider tasks+- Added hybrid long-form assembly, per-production paid-seconds caps, truthful fallback metadata, and automatic synthetic-media review handoff+- Added dashboard provider controls and a separately opted-in paid AI-video readiness probe+## v2.8.0 β 2026-08-21- Added a persistent Research & Provenance Desk with source metadata, claim-to-source links, reviewer status, notes, and evidence summariesdiff --git a/README.md b/README.mdindex 8b32108..3b216a5 100644--- a/README.md+++ b/README.md@@ -23,7 +23,7 @@ See the complete release history in [CHANGELOG.md](CHANGELOG.md).- **Self-hosted:** your credentials, media, and channel data stay under your control.- **Approval-first:** nothing is scheduled until quality, rights, and human-review gates pass by default.- **Strategy-driven:** give the Autonomous Channel Operator an objective, audience, pillars, cadence, and guardrails; it turns them into researched content plans and production runs.-- **Provider-flexible:** use Gemini, OpenAI, OpenRouter, Kimi, MiMo, GLM, or another OpenAI-compatible endpoint.+- **Provider-flexible:** use Gemini, OpenAI, OpenRouter, Kimi, MiMo, GLM, or another OpenAI-compatible text endpoint, plus Seedance, MiniMax H3, Gemini Omni Flash, Kling, Wan, or local FFmpeg for video.- **Observable:** follow persistent generation jobs, failures, review state, publishing, and local activation milestones from the dashboard.<!-- Launch gate: add only a real 30β45 second dashboard demo captured from a verified end-to-end run. -->@@ -48,6 +48,8 @@ Before activating autonomous production, open **Production readiness** in the daAI image generation can incur a larger provider charge, so its live probe is a separate opt-in checkbox. Without that checkbox, image configuration is reported as verified, skipped, or using the built-in gradient fallback without making a paid image request.+AI video verification has its own **Include paid video probe** checkbox. When enabled, Lumen creates the provider's shortest supported test clip, records the external task and model, downloads and decodes the MP4, then removes the temporary asset. It never silently tries a second paid provider.+Results persist locally in SQLite with exact remediation steps. A recorded blocking failure stops autonomous generation and publishing until a later run passes; manual work remains available when readiness has never been checked or the last result is older than 24 hours.### Resume an interrupted production@@ -166,6 +168,20 @@ graph LRAdditional integrations: Anthropic Claude (`claude-fable-5`), ElevenLabs (Eleven v3 TTS), Replicate (Wan 2.7 video), local models via Ollama, any OpenAI-compatible endpoint.+### AI video providers++Local slideshow rendering remains the default, so upgrading does not start paid video requests. Choose a provider in **Channel setup**, set a paid-seconds cap, then run the separately opted-in paid video readiness probe.++| Provider | Default model | Best fit | Clip limits |+| --- | --- | --- | --- |+| ByteDance | `bytedance/seedance-2.5` through Replicate | Cinematic long scenes and large reference sets | 4β30 seconds |+| MiniMax | `MiniMax-H3` | Multimodal references, native stereo audio, optional 2K | 4β15 seconds |+| Google | `gemini-omni-flash-preview` | Fast generation and conversational editing | 3β10 seconds |+| Kuaishou | `kling-v3-omni` | Storyboards and character/voice consistency | 3β15 seconds |+| Alibaba | Wan 2.7 task-specific models | Efficient generation, reference video, and continuation | 2β15 seconds |++Long-form productions use hybrid assembly: Lumen generates bounded provider clips for the hook and important sections, fills the remaining timeline locally, mixes the existing narration, and keeps the generated caption file alongside the production. As soon as a provider returns its task ID, Lumen persists it before polling so interrupted jobs can resume that known task instead of submitting it again.+## Configuration### API Keys@@ -216,7 +232,14 @@ OPENAI_API_KEY=sk-...# ELEVENLABS_VOICE_ID=...# Optional: AI video generation-# REPLICATE_API_KEY=...+# VIDEO_PROVIDER=slideshow # auto, seedance, minimax_h3, google_omni, kling, wan+# VIDEO_GENERATION_MODE=hybrid+# VIDEO_MAX_GENERATED_SECONDS=60+# REPLICATE_API_TOKEN=... # Seedance 2.5+# MINIMAX_API_KEY=... # MiniMax H3+# KLING_ACCESS_KEY=...+# KLING_SECRET_KEY=...+# DASHSCOPE_API_KEY=... # Wan 2.7# App configNODE_ENV=productiondiff --git a/agents/production-management-agent.js b/agents/production-management-agent.jsindex e7acdc1..40b6c33 100644--- a/agents/production-management-agent.js+++ b/agents/production-management-agent.js@@ -10,7 +10,7 @@ class ProductionManagementAgent {this.logger = new Logger('ProductionManagement');this.pipeline = [];this.assets = new Map();- this.aiVideoGenerator = new AIVideoGenerator(credentials);+ this.aiVideoGenerator = new AIVideoGenerator(credentials, { db });}async initialize() {@@ -48,7 +48,7 @@ class ProductionManagementAgent {try {this.logger.info('Processing content for production...');- const { strategy, script, thumbnail, seo } = contentData;+ const { strategy, script, thumbnail, seo, jobId = null } = contentData;// Create production entryconst productionId = this.generateProductionId();@@ -81,6 +81,7 @@ class ProductionManagementAgent {estimatedDuration: script.duration,createdAt: new Date().toISOString()};+ productionData.jobId = jobId;// Add to pipelinethis.pipeline.push(productionData);@@ -559,7 +560,12 @@ class ProductionManagementAgent {productionData.script,productionData.assets.video.visualAssets || [],productionData.assets.audio.path,- finalVideoPath+ finalVideoPath,+ {+ jobId: productionData.jobId,+ productionId: productionData.id,+ estimatedDuration: productionData.estimatedDuration+ });// The generator falls back to a placeholder .info file when it cannot render@@ -576,8 +582,13 @@ class ProductionManagementAgent {duration: productionData.estimatedDuration,generatedWith: 'AI',resolution: '1920x1080',- format: 'mp4'+ format: 'mp4',+ provider: this.aiVideoGenerator.lastVideoResult || { actualProvider: 'slideshow', model: 'local-ffmpeg' }};+ productionData.containsSyntheticMedia = Boolean(+ this.aiVideoGenerator.lastVideoResult?.actualProvider &&+ !['slideshow', 'simulation'].includes(this.aiVideoGenerator.lastVideoResult.actualProvider)+ );this.logger.info('AI video assembly complete');return finalVideoPath;diff --git a/config/credentials.example.json b/config/credentials.example.jsonindex 5b95ada..d5e410b 100644--- a/config/credentials.example.json+++ b/config/credentials.example.json@@ -10,6 +10,19 @@"apiKey": "YOUR_OPENAI_API_KEY","model": "gpt-5.6"},+ "replicate": {+ "apiKey": "YOUR_REPLICATE_API_TOKEN"+ },+ "minimax": {+ "apiKey": "YOUR_MINIMAX_API_KEY"+ },+ "kling": {+ "accessKey": "YOUR_KLING_ACCESS_KEY",+ "secretKey": "YOUR_KLING_SECRET_KEY"+ },+ "wan": {+ "apiKey": "YOUR_DASHSCOPE_API_KEY"+ },"channel": {"channelName": "Your Channel Name","channelDescription": "Your channel description.",diff --git a/dashboard/app.js b/dashboard/app.jsindex 623a261..693d7c2 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -139,7 +139,7 @@ function renderDashboard() {renderActivation(state.activation);renderReadiness(state.readiness);renderOperator(state.channelStrategy, state.operatorRuns || [], { ...state.system, readiness: state.readiness });- populateSettings(state.profile, state.settings);+ populateSettings(state.profile, state.settings, state.system.videoProviders || []);}function renderReadiness(readiness = {}) {@@ -196,6 +196,9 @@ function renderJobs(jobs) {container.innerHTML = jobs.slice(0, 6).map(job => {const checkpoints = Array.isArray(job.checkpoints) ? job.checkpoints : [];const completed = new Set(checkpoints.filter(item => item.status === 'completed').map(item => item.stage));+ const mediaTasks = Array.isArray(job.mediaTasks) ? job.mediaTasks : [];+ const mediaCompleted = mediaTasks.filter(item => item.status === 'succeeded').length;+ const mediaProviders = [...new Set(mediaTasks.map(item => label(item.provider)))].join(', ');const resumeFrom = stages.find(stage => !completed.has(stage)) || 'quality_review';const recoverable = ['failed', 'interrupted'].includes(job.status);return `@@ -204,6 +207,7 @@ function renderJobs(jobs) {<strong>${escapeHTML(job.title || job.topic || 'Agent-selected topic')}</strong><div class="meta-line">${statusChip(job.status)} Β· ${escapeHTML(label(job.stage))} Β· ${timeAgo(job.updated_at)}</div>${checkpoints.length ? `<div class="checkpoint-line">${completed.size}/${stages.length} stages saved${job.details?.reusedStages?.length ? ` Β· ${job.details.reusedStages.length} reused` : ''}</div>` : ''}+ ${mediaTasks.length ? `<div class="checkpoint-line">Video: ${mediaCompleted}/${mediaTasks.length} clips ready Β· ${escapeHTML(mediaProviders)}</div>` : ''}<div class="progress"><i style="width:${Math.max(0, Math.min(100, job.progress || 0))}%"></i></div></div>${['queued', 'running'].includes(job.status) ? `<button class="text-button" data-cancel-job="${escapeHTML(job.id)}">Cancel</button>` : ''}@@ -424,7 +428,7 @@ function renderOperator(strategy, runs, system) {}).join('') : empty('Research and planning will appear here when the run begins.');}-function populateSettings(profile = {}, settings = {}) {+function populateSettings(profile = {}, settings = {}, providers = []) {const form = $('#profile-form');const mapping = {channelName: profile.channel_name,@@ -442,6 +446,20 @@ function populateSettings(profile = {}, settings = {}) {}$('#approval-required').checked = settings.approval_required !== 'false';$('#notifications-enabled').checked = settings.notification_enabled !== 'false';+ const videoMapping = {+ videoProvider: settings.video_provider || 'slideshow',+ videoGenerationMode: settings.video_generation_mode || 'hybrid',+ videoClipDuration: settings.video_clip_duration || '8',+ videoMaxGeneratedSeconds: settings.video_max_generated_seconds || '60'+ };+ for (const [name, value] of Object.entries(videoMapping)) {+ if (form.elements[name] && document.activeElement !== form.elements[name]) form.elements[name].value = value;+ }+ const selected = providers.find(provider => provider.id === videoMapping.videoProvider);+ $('#video-provider-status').textContent = videoMapping.videoProvider === 'auto'+ ? `${providers.filter(provider => provider.available && provider.id !== 'slideshow').length} paid provider(s) available; local slideshow remains the final fallback.`+ : videoMapping.videoProvider === 'slideshow' ? 'Local FFmpeg slideshow is selected; no external video credentials are required.'+ : selected?.available ? `${label(selected.id)} is configured (${selected.model}).` : `${label(videoMapping.videoProvider)} credentials are not configured.`;}function switchView(view) {@@ -794,7 +812,10 @@ $('#run-readiness-button').addEventListener('click', async event => {button.disabled = true;button.textContent = 'Running live checksβ¦';try {- await mutate('/api/readiness/run', 'POST', { includePaidMedia: $('#paid-image-probe').checked }, 'Production readiness check completed.');+ await mutate('/api/readiness/run', 'POST', {+ includePaidMedia: $('#paid-image-probe').checked,+ includePaidVideo: $('#paid-video-probe').checked+ }, 'Production readiness check completed.');switchView('readiness');} catch (_error) { /* toast already shown */ }finally {@@ -877,7 +898,11 @@ $('#profile-form').addEventListener('submit', async event => {await mutate('/api/settings', 'PUT', {approval_required: $('#approval-required').checked,notification_enabled: $('#notifications-enabled').checked,- channel_timezone: values.timezone+ channel_timezone: values.timezone,+ video_provider: values.videoProvider,+ video_generation_mode: values.videoGenerationMode,+ video_clip_duration: Number(values.videoClipDuration),+ video_max_generated_seconds: Number(values.videoMaxGeneratedSeconds)}, 'Operator settings saved.');} catch (_error) { /* toast already shown */ }});diff --git a/dashboard/index.html b/dashboard/index.htmlindex 06b1ffd..1315c0e 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -158,6 +158,7 @@</div><div class="readiness-actions"><label class="toggle paid-probe"><input id="paid-image-probe" type="checkbox"><span></span> Include paid image probe</label>+ <label class="toggle paid-probe"><input id="paid-video-probe" type="checkbox"><span></span> Include paid video probe</label><button id="run-readiness-button" class="button primary">Run verified check</button><small>Live provider probes can consume a small amount of quota or credits.</small></div>@@ -184,6 +185,12 @@<label class="toggle"><input id="approval-required" type="checkbox"><span></span> Require approval before scheduling</label><label class="toggle"><input id="notifications-enabled" type="checkbox"><span></span> Save operator notifications</label></div>+ <div class="form-grid video-provider-settings">+ <label><span>Video provider</span><select name="videoProvider"><option value="slideshow">Local slideshow Β· no provider cost</option><option value="auto">Automatic capability routing</option><option value="seedance">ByteDance Seedance 2.5</option><option value="minimax_h3">MiniMax H3</option><option value="google_omni">Google Gemini Omni Flash</option><option value="kling">Kuaishou Kling 3.0 Omni</option><option value="wan">Alibaba Wan 2.7</option></select><small id="video-provider-status">Provider credentials are checked at runtime.</small></label>+ <label><span>Generation mode</span><select name="videoGenerationMode"><option value="hybrid">Hybrid Β· generated clips + local assembly</option><option value="slideshow">Local slideshow only</option></select></label>+ <label><span>Clip duration</span><input name="videoClipDuration" type="number" min="3" max="30" step="1"></label>+ <label><span>Paid seconds cap</span><input name="videoMaxGeneratedSeconds" type="number" min="0" max="600" step="1"><small>Maximum provider-generated seconds per production.</small></label>+ </div><div class="form-actions"><button type="submit" class="button primary">Save channel setup</button><button id="api-key-button" type="button" class="button secondary">Set dashboard API key</button></div></form></section>diff --git a/database/db.js b/database/db.jsindex 8bba051..bcdb641 100644--- a/database/db.js+++ b/database/db.js@@ -247,6 +247,25 @@ class Database {PRIMARY KEY (job_id, stage),FOREIGN KEY (job_id) REFERENCES generation_jobs(id))`,+ `CREATE TABLE IF NOT EXISTS media_generation_tasks (+ id TEXT PRIMARY KEY,+ job_id TEXT,+ production_id TEXT,+ scene_index INTEGER NOT NULL,+ provider TEXT NOT NULL,+ model TEXT NOT NULL,+ external_task_id TEXT,+ status TEXT DEFAULT 'submitting',+ request TEXT NOT NULL DEFAULT '{}',+ provider_data TEXT NOT NULL DEFAULT '{}',+ output_path TEXT,+ error TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ completed_at TEXT,+ UNIQUE(job_id, scene_index, provider),+ FOREIGN KEY (job_id) REFERENCES generation_jobs(id)+ )`,`CREATE TABLE IF NOT EXISTS production_snapshots (production_id TEXT PRIMARY KEY,strategy TEXT,@@ -387,7 +406,14 @@ class Database {['automation_paused', 'false', 'Pause generation and publishing automation'],['channel_timezone', 'America/Chicago', 'Timezone used to present channel schedules'],['max_daily_posts', '1', 'Maximum posts per day'],- ['content_buffer_days', '3', 'Days of content to keep in buffer']+ ['content_buffer_days', '3', 'Days of content to keep in buffer'],+ ['video_provider', 'slideshow', 'Video provider: slideshow, auto, seedance, minimax_h3, google_omni, kling, or wan'],+ ['video_provider_order', 'seedance,minimax_h3,google_omni,kling,wan,slideshow', 'Provider priority used by automatic routing'],+ ['video_generation_mode', 'hybrid', 'Use provider clips within a locally assembled long-form video'],+ ['video_clip_duration', '8', 'Requested duration for each generated provider clip'],+ ['video_max_generated_seconds', '60', 'Maximum paid provider seconds per production'],+ ['video_resolution', '720p', 'Requested generated clip resolution'],+ ['video_aspect_ratio', '16:9', 'Requested generated clip aspect ratio']];for (const [key, value, description] of defaultSettings) {@@ -704,6 +730,7 @@ class Database {return Promise.all(rows.map(async row => {const job = { ...row, details: JSON.parse(row.details || '{}'), cancelRequested: Boolean(row.cancel_requested) };job.checkpoints = await this.listGenerationCheckpoints(job.id);+ job.mediaTasks = await this.listMediaGenerationTasks(job.id);return job;}));}@@ -762,6 +789,60 @@ class Database {);}+ async createMediaGenerationTask(input = {}) {+ const id = this.generateId('media');+ await this.executeQuery(+ `INSERT INTO media_generation_tasks (+ id, job_id, production_id, scene_index, provider, model, status, request, provider_data+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '{}')+ ON CONFLICT(job_id, scene_index, provider) DO UPDATE SET+ production_id = excluded.production_id, request = excluded.request, updated_at = datetime('now')`,+ [id, input.jobId || null, input.productionId || null, input.sceneIndex, input.provider, input.model, input.status || 'submitting', JSON.stringify(input.request || {})]+ );+ return this.findMediaGenerationTask(input.jobId, input.sceneIndex, input.provider);+ }++ async findMediaGenerationTask(jobId, sceneIndex, provider) {+ const row = await this.getRow(+ 'SELECT * FROM media_generation_tasks WHERE job_id IS ? AND scene_index = ? AND provider = ?',+ [jobId || null, sceneIndex, provider]+ );+ return this.parseMediaGenerationTask(row);+ }++ async updateMediaGenerationTask(id, changes = {}) {+ const current = this.parseMediaGenerationTask(await this.getRow('SELECT * FROM media_generation_tasks WHERE id = ?', [id]));+ if (!current) return null;+ await this.executeQuery(+ `UPDATE media_generation_tasks SET model = ?, external_task_id = ?, status = ?, provider_data = ?,+ output_path = ?, error = ?, completed_at = ?, updated_at = datetime('now') WHERE id = ?`,+ [+ changes.model ?? current.model,+ changes.externalTaskId ?? current.external_task_id,+ changes.status ?? current.status,+ JSON.stringify(changes.providerData ?? current.providerData ?? {}),+ changes.outputPath ?? current.output_path,+ changes.error === undefined ? current.error : changes.error,+ changes.completedAt === undefined ? current.completed_at : changes.completedAt,+ id+ ]+ );+ return this.parseMediaGenerationTask(await this.getRow('SELECT * FROM media_generation_tasks WHERE id = ?', [id]));+ }++ async listMediaGenerationTasks(jobId) {+ const rows = await this.getAllRows('SELECT * FROM media_generation_tasks WHERE job_id = ? ORDER BY scene_index, created_at', [jobId]);+ return rows.map(row => this.parseMediaGenerationTask(row));+ }++ parseMediaGenerationTask(row) {+ return row ? {+ ...row,+ request: JSON.parse(row.request || '{}'),+ providerData: JSON.parse(row.provider_data || '{}')+ } : null;+ }+async markInterruptedJobs() {await this.executeQuery(`UPDATE generation_jobs SET status = 'interrupted',diff --git a/index.js b/index.jsindex 45b61c5..520481c 100644--- a/index.js+++ b/index.js@@ -446,7 +446,8 @@ class YouTubeAutomationAgent {activeJobs: this.activeJobs.size,automationPaused: this.scheduler ? !this.scheduler.isEnabled : true,agents: Object.keys(this.agents),- autonomousRunning: Boolean(await this.db.getActiveOperatorRun())+ autonomousRunning: Boolean(await this.db.getActiveOperatorRun()),+ videoProviders: this.agents.production?.aiVideoGenerator?.mediaGeneration?.listProviders() || []}});} catch (error) {@@ -458,6 +459,7 @@ class YouTubeAutomationAgent {const job = await this.db.getGenerationJob(req.params.jobId);if (!job) return res.status(404).json({ error: 'Job not found' });job.checkpoints = await this.db.listGenerationCheckpoints(job.id);+ job.mediaTasks = await this.db.listMediaGenerationTasks(job.id);job.resumeFrom = this.recovery?.resumePoint(job.checkpoints);return res.json(job);});@@ -479,7 +481,10 @@ class YouTubeAutomationAgent {this.app.post('/api/readiness/run', protect, async (req, res) => {try {if (!this.readiness) return res.status(503).json({ error: 'Readiness service is not initialized' });- const result = await this.readiness.run({ includePaidMedia: req.body?.includePaidMedia === true });+ const result = await this.readiness.run({+ includePaidMedia: req.body?.includePaidMedia === true,+ includePaidVideo: req.body?.includePaidVideo === true+ });return res.json({ success: true, result });} catch (error) {return res.status(error.status || 500).json({ success: false, error: error.message });@@ -742,6 +747,27 @@ class YouTubeAutomationAgent {for (const key of allowed) {if (req.body?.[key] !== undefined) await this.db.setSetting(key, String(req.body[key]));}+ const provider = req.body?.video_provider;+ if (provider !== undefined) {+ const supported = ['slideshow', 'auto', 'seedance', 'minimax_h3', 'google_omni', 'kling', 'wan'];+ if (!supported.includes(provider)) return res.status(400).json({ error: 'Unsupported video provider' });+ await this.db.setSetting('video_provider', provider);+ }+ const mode = req.body?.video_generation_mode;+ if (mode !== undefined) {+ if (!['hybrid', 'slideshow'].includes(mode)) return res.status(400).json({ error: 'Unsupported video generation mode' });+ await this.db.setSetting('video_generation_mode', mode);+ }+ if (req.body?.video_clip_duration !== undefined) {+ const value = Number(req.body.video_clip_duration);+ if (!Number.isInteger(value) || value < 3 || value > 30) return res.status(400).json({ error: 'Clip duration must be between 3 and 30 seconds' });+ await this.db.setSetting('video_clip_duration', String(value));+ }+ if (req.body?.video_max_generated_seconds !== undefined) {+ const value = Number(req.body.video_max_generated_seconds);+ if (!Number.isInteger(value) || value < 0 || value > 600) return res.status(400).json({ error: 'Generated seconds cap must be between 0 and 600' });+ await this.db.setSetting('video_max_generated_seconds', String(value));+ }return res.json({ success: true, result: await this.db.getAllSettings() });});@@ -991,7 +1017,7 @@ class YouTubeAutomationAgent {jobId,'production',62,- () => this.agents.production.processContent({ strategy, script, thumbnail, seo: seoData })+ () => this.agents.production.processContent({ strategy, script, thumbnail, seo: seoData, jobId }));this.logger.info('Production processing complete');diff --git a/test.js b/test.jsindex 9f6cf4b..414440f 100644--- a/test.js+++ b/test.js@@ -26,6 +26,7 @@ class SystemTest {{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },+ { name: 'Durable Multi-Provider Video Generation', test: () => this.testVideoProviderLayer() },{ name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },@@ -599,6 +600,7 @@ class SystemTest {probes: {text: passingProbe('Text'),image: passingProbe('Image'),+ videoProvider: passingProbe('Video provider'),narration: passingProbe('Narration'),videoAssembly: passingProbe('Video'),youtube: passingProbe('YouTube'),@@ -606,7 +608,7 @@ class SystemTest {}});const passed = await service.run({ includePaidMedia: true });- if (passed.status !== 'passed' || passed.checks.length !== 6 || !savedRun) {+ if (passed.status !== 'passed' || passed.checks.length !== 7 || !savedRun) {throw new Error('A successful readiness run was not persisted correctly');}await service.assertReady('Test automation');@@ -615,6 +617,7 @@ class SystemTest {probes: {text: passingProbe('Text'),image: passingProbe('Image'),+ videoProvider: passingProbe('Video provider'),narration: passingProbe('Narration'),videoAssembly: passingProbe('Video'),youtube: async () => { throw new Error('token rejected sk-secret-value'); },@@ -654,7 +657,7 @@ class SystemTest {await persistenceDb.initialize();await persistenceDb.saveReadinessRun(passed);const persisted = await persistenceDb.getLatestReadinessRun();- if (persisted?.id !== passed.id || persisted.checks.length !== 6 || persisted.summary.passed !== 6) {+ if (persisted?.id !== passed.id || persisted.checks.length !== 7 || persisted.summary.passed !== 7) {throw new Error('Readiness evidence did not round-trip through SQLite');}} finally {@@ -664,6 +667,141 @@ class SystemTest {this.logger.info('Production readiness gate test completed successfully');}+ async testVideoProviderLayer() {+ const fs = require('fs').promises;+ const os = require('os');+ const { runFFmpeg, checkFFmpeg } = require('./utils/ffmpeg');+ const { MediaGenerationService } = require('./utils/media-generation-service');+ const {+ VideoProvider, VideoProviderRegistry, SeedanceProvider, MiniMaxH3Provider,+ GoogleOmniProvider, KlingProvider, WanProvider+ } = require('./utils/video-providers');+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-media-provider-'));+ const db = new Database();+ db.dbPath = path.join(directory, 'media.db');+ await db.initialize();+ const job = await db.createGenerationJob({ topic: 'Provider durability test' });+ const source = path.join(directory, 'source.mp4');+ let createCalls = 0;+ let pollCalls = 0;++ try {+ if (!(await checkFFmpeg())) {+ this.logger.warn('Skipping provider MP4 durability assertion because FFmpeg is unavailable');+ return;+ }+ await runFFmpeg(['-y', '-f', 'lavfi', '-i', 'color=c=red:s=320x180:d=1', '-c:v', 'mpeg4', source]);+ const fake = new VideoProvider('seedance', {+ model: 'bytedance/seedance-2.5',+ capabilities: { minDuration: 4, maxDuration: 30, cancellation: true }+ });+ fake.isAvailable = () => true;+ fake.createTask = async () => {+ createCalls++;+ return { externalTaskId: 'prediction-1', status: 'queued' };+ };+ fake.getTask = async id => {+ pollCalls++;+ return { externalTaskId: id, status: 'succeeded', outputUrl: 'fake://video' };+ };+ fake.downloadResult = async (_task, outputPath) => {+ await fs.copyFile(source, outputPath);+ return outputPath;+ };+ const registry = new VideoProviderRegistry({}, { providers: { seedance: fake } });+ const service = new MediaGenerationService(db, {}, { registry, pollIntervalMs: 10, sleep: async () => {} });+ const output = path.join(directory, 'output.mp4');+ const input = {+ jobId: job.id,+ productionId: 'prod-provider-test',+ scene: { index: 0 },+ provider: fake,+ outputPath: output,+ request: { prompt: 'A red frame', duration: 4, resolution: '720p', aspectRatio: '16:9' }+ };+ const first = await service.generateClip(input);+ const second = await service.generateClip(input);+ const tasks = await db.listMediaGenerationTasks(job.id);+ if (createCalls !== 1 || pollCalls !== 1 || !second.reused || tasks.length !== 1) {+ throw new Error('A completed provider task was duplicated instead of being reused');+ }+ if (first.task.external_task_id !== 'prediction-1' || tasks[0].model !== 'bytedance/seedance-2.5') {+ throw new Error('Provider task identity and model evidence did not persist');+ }+ const providers = registry.list();+ for (const id of ['seedance', 'minimax_h3', 'google_omni', 'kling', 'wan', 'slideshow']) {+ if (!providers.find(provider => provider.id === id)) throw new Error(`Missing video provider: ${id}`);+ }+ const shortOnly = new VideoProvider('wan', { model: 'wan-test', capabilities: { minDuration: 2, maxDuration: 15, firstFrame: true } });+ shortOnly.isAvailable = () => true;+ const routed = new VideoProviderRegistry({}, { providers: { seedance: fake, wan: shortOnly } });+ if (routed.select('auto', ['wan', 'seedance'], { duration: 20 }).id !== 'seedance') {+ throw new Error('Automatic video routing ignored the requested duration capability');+ }+ if (routed.select('auto', ['seedance', 'wan'], { duration: 8, generateAudio: true }).id !== 'slideshow') {+ throw new Error('Automatic video routing selected a provider without requested native audio support');+ }+ const listedJob = (await db.listGenerationJobs(10)).find(item => item.id === job.id);+ if (listedJob?.mediaTasks?.length !== 1 || listedJob.mediaTasks[0].external_task_id !== 'prediction-1') {+ throw new Error('Generation job history did not expose its durable provider task');+ }++ let seedanceSubmission;+ const seedance = new SeedanceProvider({}, { client: { predictions: {+ create: async submission => {+ seedanceSubmission = submission;+ return { id: 'seedance-task', status: 'starting' };+ }+ } } });+ const seedanceTask = await seedance.createTask({ prompt: 'Seedance scene', duration: 30, aspectRatio: '16:9' });+ if (seedanceTask.externalTaskId !== 'seedance-task' || seedanceSubmission.model !== 'bytedance/seedance-2.5' || seedanceSubmission.input.duration !== 30) {+ throw new Error('Seedance adapter did not submit the expected Replicate task');+ }+ const fileOutput = seedance.normalizeTask({ id: 'file-output', status: 'succeeded', output: { url: () => new URL('https://example.com/video.mp4') } });+ if (fileOutput.outputUrl !== 'https://example.com/video.mp4') throw new Error('Seedance FileOutput was not normalized');++ let minimaxBody;+ const minimax = new MiniMaxH3Provider({}, { apiKey: 'test', http: {+ post: async (_url, body) => { minimaxBody = body; return { data: { task_id: 'h3-task' } }; }+ } });+ const minimaxTask = await minimax.createTask({ prompt: 'H3 scene', duration: 15, resolution: '2K', aspectRatio: '9:16' });+ if (minimaxTask.externalTaskId !== 'h3-task' || minimaxBody.model !== 'MiniMax-H3' || minimaxBody.content[0].type !== 'text') {+ throw new Error('MiniMax H3 adapter did not submit the expected multimodal task');+ }++ let googleName;+ const google = new GoogleOmniProvider({}, { client: {+ interactions: { create: async () => ({ id: 'omni-task', output_video: { uri: 'https://generativelanguage.googleapis.com/v1beta/files/omni-file:download?alt=media' } }) },+ files: { get: async ({ name }) => { googleName = name; return { state: { name: 'ACTIVE' } }; } }+ } });+ const googleTask = await google.createTask({ prompt: 'Omni scene', aspectRatio: '16:9' });+ await google.getTask(googleTask.externalTaskId);+ if (googleTask.status !== 'queued' || googleName !== 'files/omni-file') throw new Error('Gemini Omni URI task was not normalized for polling');++ let klingBody;+ const kling = new KlingProvider({}, { accessKey: 'access', secretKey: 'secret', http: {+ post: async (_url, body) => { klingBody = body; return { data: { data: { task_id: 'kling-task' } } }; }+ } });+ const klingTask = await kling.createTask({ prompt: 'Kling scene', duration: 8, aspectRatio: '16:9' });+ if (klingTask.externalTaskId !== 'kling-task' || klingBody.model_name !== 'kling-v3-omni' || klingBody.sound !== 'off') {+ throw new Error('Kling adapter did not submit the expected task');+ }++ let wanBody;+ const wan = new WanProvider({}, { apiKey: 'test', http: {+ post: async (_url, body) => { wanBody = body; return { data: { output: { task_id: 'wan-task' } } }; }+ } });+ const wanTask = await wan.createTask({ prompt: 'Wan scene', duration: 10, resolution: '720p', aspectRatio: '16:9' });+ if (wanTask.externalTaskId !== 'wan-task' || wanBody.model !== 'wan2.7-t2v-2026-06-12' || wanBody.parameters.resolution !== '720P') {+ throw new Error('Wan adapter did not submit the expected task-specific model payload');+ }+ } finally {+ await db.close();+ await fs.rm(directory, { recursive: true, force: true });+ }+ this.logger.info('Durable multi-provider video generation test completed successfully');+ }+async testProvenanceDesk() {const fs = require('fs').promises;const os = require('os');@@ -1376,6 +1514,9 @@ class SystemTest {}const generator = new AIVideoGenerator({});+ if (generator.parseDurationSeconds('2:05') !== 125 || generator.parseDurationSeconds('1:02:03') !== 3723) {+ throw new Error('Human-readable production durations are not converted to timeline seconds');+ }const videoPath = path.join(dir, 'out.mp4');await generator.renderSlidesToVideo(stills, 6, videoPath);@@ -1391,6 +1532,14 @@ class SystemTest {if (!finalStats.size) {throw new Error('Silent-audio fallback did not produce a video');}++ const hybridPath = path.join(dir, 'hybrid.mp4');+ await generator.renderMediaTimeline([+ { type: 'video', path: videoPath, duration: 1 },+ { type: 'image', path: stills[0], duration: 1 }+ ], hybridPath);+ const hybridStats = await fs.stat(hybridPath);+ if (!hybridStats.size) throw new Error('Hybrid provider/still timeline did not produce a video');} finally {await fs.rm(dir, { recursive: true, force: true }).catch(() => {});}@@ -1421,7 +1570,7 @@ class SystemTest {}async testWalkthroughModule() {- const { SetupWalkthrough, AI_PROVIDER_GUIDE } = require('./walkthrough');+ const { SetupWalkthrough, AI_PROVIDER_GUIDE, VIDEO_PROVIDER_GUIDE } = require('./walkthrough');const { PROVIDERS, GEMINI_MODELS, GEMINI_DEFAULT_MODEL } = require('./utils/ai-text-service');const walkthrough = new SetupWalkthrough();@@ -1480,6 +1629,18 @@ class SystemTest {}}+ for (const id of ['slideshow', 'seedance', 'minimax_h3', 'google_omni', 'kling', 'wan']) {+ const guide = VIDEO_PROVIDER_GUIDE[id];+ if (!guide?.label) throw new Error(`Walkthrough is missing video provider "${id}"`);+ if (id !== 'slideshow') {+ const credentials = {};+ guide.save(credentials, 'test-key', 'test-secret');+ if (!Object.keys(credentials).length || !guide.keyUrl || !guide.credentialName) {+ throw new Error(`Video provider guide "${id}" cannot save its credentials`);+ }+ }+ }+const currentOpenRouterModels = ['openai/gpt-5.6-sol','anthropic/claude-fable-5',diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.jsindex 25ee080..783f2e2 100644--- a/utils/ai-video-generator.js+++ b/utils/ai-video-generator.js@@ -6,14 +6,18 @@ const { pathToFileURL } = require('url');const axios = require('axios');const { Logger } = require('./logger');const { runFFmpeg, checkFFmpeg, ffmpegInstallHint } = require('./ffmpeg');+const { MediaGenerationService } = require('./media-generation-service');class AIVideoGenerator {- constructor(credentials) {+ constructor(credentials, options = {}) {this.logger = new Logger('AIVideoGenerator');+ const resolvedCredentials = credentials?.credentials || credentials || {};+ this.db = options.db || null;+ this.lastVideoResult = null;// Initialize AI services with graceful fallback- const openaiKey = credentials.openai?.apiKey || process.env.OPENAI_API_KEY;- const replicateKey = credentials.replicate?.apiKey || process.env.REPLICATE_API_KEY;+ const openaiKey = resolvedCredentials.openai?.apiKey || process.env.OPENAI_API_KEY;+ const replicateKey = resolvedCredentials.replicate?.apiKey || process.env.REPLICATE_API_TOKEN || process.env.REPLICATE_API_KEY;if (openaiKey) {this.openai = new OpenAI({ apiKey: openaiKey });@@ -30,7 +34,7 @@ class AIVideoGenerator {}// Gemini media generation (images + native TTS) β free-tier alternative to OpenAI- const geminiKey = credentials.gemini?.apiKey || process.env.GEMINI_API_KEY;+ const geminiKey = resolvedCredentials.gemini?.apiKey || process.env.GEMINI_API_KEY;if (geminiKey) {try {const { GoogleGenAI } = require('@google/genai');@@ -42,12 +46,15 @@ class AIVideoGenerator {}// ElevenLabs configuration- this.elevenLabsApiKey = credentials.elevenLabs?.apiKey || process.env.ELEVENLABS_API_KEY;- this.elevenLabsVoiceId = credentials.elevenLabs?.voiceId || process.env.ELEVENLABS_VOICE_ID;+ this.elevenLabsApiKey = resolvedCredentials.elevenLabs?.apiKey || process.env.ELEVENLABS_API_KEY;+ this.elevenLabsVoiceId = resolvedCredentials.elevenLabs?.voiceId || process.env.ELEVENLABS_VOICE_ID;// Azure Speech configuration- this.azureSpeechKey = credentials.azure?.speechKey || process.env.AZURE_SPEECH_KEY;- this.azureSpeechRegion = credentials.azure?.speechRegion || process.env.AZURE_SPEECH_REGION;+ this.azureSpeechKey = resolvedCredentials.azure?.speechKey || process.env.AZURE_SPEECH_KEY;+ this.azureSpeechRegion = resolvedCredentials.azure?.speechRegion || process.env.AZURE_SPEECH_REGION;+ this.mediaGeneration = options.mediaGeneration || (this.db+ ? new MediaGenerationService(this.db, resolvedCredentials, { logger: this.logger })+ : null);}async generateTTSAudio(text, outputPath) {@@ -267,25 +274,120 @@ class AIVideoGenerator {});}- async generateVideo(script, visualAssets, audioPath, outputPath) {+ async generateVideo(script, visualAssets, audioPath, outputPath, options = {}) {this.logger.info('Generating video from assets...');-+ this.lastVideoResult = null;try {- // Try Replicate for video generation first- if (this.replicate && this.replicate.auth) {- return await this.generateReplicateVideo(script, visualAssets, audioPath, outputPath);+ if (this.mediaGeneration && options.productionId) {+ const generated = await this.mediaGeneration.generateClips({+ jobId: options.jobId || null,+ productionId: options.productionId,+ script,+ visualAssets,+ outputDir: path.dirname(outputPath)+ });+ if (generated.clips.length) {+ const produced = await this.generateHybridVideo(+ generated.clips,+ visualAssets,+ audioPath,+ outputPath,+ options.estimatedDuration || this.calculateScriptDuration(script)+ );+ this.lastVideoResult = {+ requestedProvider: generated.requestedProvider,+ actualProvider: generated.actualProvider,+ model: generated.model,+ mode: generated.settings.mode,+ generatedSeconds: generated.clips.reduce((total, clip) => total + clip.duration, 0),+ tasks: generated.clips.map(clip => ({ scene: clip.index, taskId: clip.taskId, provider: clip.provider, model: clip.model }))+ };+ return produced;+ }}-- // Fallback to simple slideshow with Playwright- return await this.generateSlideshowVideo(script, visualAssets, audioPath, outputPath);++ const produced = await this.generateSlideshowVideo(script, visualAssets, audioPath, outputPath);+ this.lastVideoResult = { requestedProvider: 'slideshow', actualProvider: 'slideshow', model: 'local-ffmpeg', mode: 'slideshow', generatedSeconds: 0, tasks: [] };+ return produced;} catch (error) {// The Logger's console line only shows the message string, so put the real// reason inline. Previously the stack alone went to the file transport and// the console printed "Video generation failed:" with no detail.const reason = error && error.message ? error.message : String(error);- this.logger.error(`Video generation failed: ${reason}`, error);- return await this.simulateVideoGeneration(script, visualAssets, audioPath, outputPath);+ this.logger.error(`Video provider generation failed; using the local slideshow: ${reason}`, error);+ try {+ const produced = await this.generateSlideshowVideo(script, visualAssets, audioPath, outputPath);+ this.lastVideoResult = {+ requestedProvider: this.lastVideoResult?.requestedProvider || 'configured-provider',+ actualProvider: 'slideshow', model: 'local-ffmpeg', mode: 'fallback', generatedSeconds: 0,+ fallbackReason: reason, tasks: []+ };+ return produced;+ } catch (fallbackError) {+ this.logger.error(`Local slideshow fallback failed: ${fallbackError.message}`, fallbackError);+ const produced = await this.simulateVideoGeneration(script, visualAssets, audioPath, outputPath);+ this.lastVideoResult = {+ requestedProvider: 'configured-provider', actualProvider: 'simulation', model: null,+ mode: 'simulation', generatedSeconds: 0, fallbackReason: `${reason}; ${fallbackError.message}`, tasks: []+ };+ return produced;+ }+ }+ }++ async generateHybridVideo(clips, visualAssets, audioPath, outputPath, totalDuration) {+ if (!(await checkFFmpeg())) throw new Error(ffmpegInstallHint());+ const validImages = await this.filterLocalImageAssets(visualAssets);+ const segments = clips.map(clip => ({ type: 'video', path: clip.path, duration: clip.duration }));+ const generatedDuration = segments.reduce((sum, item) => sum + item.duration, 0);+ const remaining = Math.max(0, this.parseDurationSeconds(totalDuration) - generatedDuration);+ if (remaining && validImages.length) {+ const perImage = Math.max(2, remaining / validImages.length);+ for (const imagePath of validImages) segments.push({ type: 'image', path: imagePath, duration: perImage });+ }+ if (!segments.length) throw new Error('No usable provider clips or still images were generated');++ const visualPath = outputPath.replace(/\.mp4$/i, '_hybrid_visual.mp4');+ await this.renderMediaTimeline(segments, visualPath);+ await this.addAudioToVideo(visualPath, audioPath, outputPath, { loopVideo: true });+ await fs.unlink(visualPath).catch(() => {});+ return outputPath;+ }++ async renderMediaTimeline(segments, outputPath) {+ const args = ['-y'];+ for (const segment of segments) {+ if (segment.type === 'image') args.push('-loop', '1', '-t', Number(segment.duration).toFixed(2), '-framerate', '30', '-i', segment.path);+ else args.push('-i', segment.path);}+ const filters = segments.map((segment, index) =>+ `[${index}:v]scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black,fps=30,format=yuv420p,trim=duration=${Number(segment.duration).toFixed(2)},setpts=PTS-STARTPTS[v${index}]`+ );+ filters.push(`${segments.map((_, index) => `[v${index}]`).join('')}concat=n=${segments.length}:v=1:a=0[vout]`);+ args.push('-filter_complex', filters.join(';'), '-map', '[vout]', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', outputPath);+ await runFFmpeg(args);+ return outputPath;+ }++ async filterLocalImageAssets(visualAssets = []) {+ const imageExtensions = new Set(['.png', '.jpg', '.jpeg', '.webp']);+ const images = [];+ for (const asset of visualAssets) {+ if (typeof asset !== 'string' || !imageExtensions.has(path.extname(asset).toLowerCase())) continue;+ try {+ await fs.access(asset);+ images.push(asset);+ } catch (_error) { /* ignore missing assets */ }+ }+ return images;+ }++ parseDurationSeconds(value) {+ if (Number.isFinite(Number(value))) return Math.max(0, Number(value));+ const parts = String(value || '').split(':').map(Number);+ if (parts.length === 2 && parts.every(Number.isFinite)) return Math.max(0, parts[0] * 60 + parts[1]);+ if (parts.length === 3 && parts.every(Number.isFinite)) return Math.max(0, parts[0] * 3600 + parts[1] * 60 + parts[2]);+ return 0;}async generateReplicateVideo(script, visualAssets, audioPath, outputPath) {@@ -649,7 +751,7 @@ class AIVideoGenerator {return Math.max(30, Math.ceil((totalWords / 150) * 60));}- async addAudioToVideo(videoPath, audioPath, outputPath) {+ async addAudioToVideo(videoPath, audioPath, outputPath, options = {}) {const hasRealAudio = await this.isUsableAudioFile(audioPath);if (!hasRealAudio) {@@ -665,7 +767,8 @@ class AIVideoGenerator {? outputPath.replace(/\.mp4$/i, '_muxed.mp4'): outputPath;- await runFFmpeg(['-y', '-i', videoPath, '-i', audioPath, '-c:v', 'copy', '-c:a', 'aac', '-shortest', muxPath]);+ const videoInput = options.loopVideo ? ['-stream_loop', '-1', '-i', videoPath] : ['-i', videoPath];+ await runFFmpeg(['-y', ...videoInput, '-i', audioPath, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-shortest', muxPath]);if (muxPath !== outputPath) {await fs.rename(muxPath, outputPath);@@ -816,4 +919,4 @@ class AIVideoGenerator {}}-module.exports = { AIVideoGenerator };\ No newline at end of file+module.exports = { AIVideoGenerator };diff --git a/utils/media-generation-service.js b/utils/media-generation-service.jsnew file mode 100644index 0000000..73e6090--- /dev/null+++ b/utils/media-generation-service.js@@ -0,0 +1,241 @@+const fs = require('fs').promises;+const path = require('path');+const { VideoProviderRegistry, DEFAULT_PROVIDER_ORDER, safeModelError } = require('./video-providers');+const { Logger } = require('./logger');+const { runFFmpeg } = require('./ffmpeg');++const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']);++class MediaGenerationService {+ constructor(db, credentials = {}, options = {}) {+ this.db = db;+ this.registry = options.registry || new VideoProviderRegistry(credentials, options.providerOptions);+ this.logger = options.logger || new Logger('MediaGeneration');+ this.pollIntervalMs = Math.max(10, Number(options.pollIntervalMs ?? process.env.VIDEO_PROVIDER_POLL_MS ?? 5000));+ this.maxPollMs = Math.max(1000, Number(options.maxPollMs ?? process.env.VIDEO_PROVIDER_TIMEOUT_MS ?? 60 * 60 * 1000));+ this.sleep = options.sleep || (ms => new Promise(resolve => setTimeout(resolve, ms)));+ }++ async settings() {+ const stored = this.db?.getAllSettings ? await this.db.getAllSettings() : {};+ const provider = process.env.VIDEO_PROVIDER || stored.video_provider || 'slideshow';+ const order = String(process.env.VIDEO_PROVIDER_ORDER || stored.video_provider_order || DEFAULT_PROVIDER_ORDER.join(','))+ .split(',').map(value => value.trim()).filter(Boolean);+ return {+ provider,+ order,+ mode: process.env.VIDEO_GENERATION_MODE || stored.video_generation_mode || 'hybrid',+ clipDuration: Math.max(3, Number(process.env.VIDEO_CLIP_DURATION || stored.video_clip_duration || 8)),+ maxGeneratedSeconds: Math.max(0, Number(process.env.VIDEO_MAX_GENERATED_SECONDS || stored.video_max_generated_seconds || 60)),+ generateAudio: false,+ resolution: process.env.VIDEO_RESOLUTION || stored.video_resolution || '720p',+ aspectRatio: process.env.VIDEO_ASPECT_RATIO || stored.video_aspect_ratio || '16:9'+ };+ }++ listProviders() { return this.registry.list(); }++ buildScenePlan(script = {}, visualAssets = [], settings = {}) {+ const prompts = [];+ if (script.hook?.text || script.title) {+ prompts.push({+ label: 'Hook',+ prompt: `${script.hook?.text || script.title}. Cinematic opening shot, clear subject, intentional camera movement, no captions or on-screen text.`+ });+ }+ for (const section of script.mainContent?.sections || []) {+ const detail = typeof section.content === 'string'+ ? section.content+ : (section.items || section.steps || []).map(item => `${item.title || ''} ${item.description || ''}`).join(' ');+ prompts.push({+ label: section.title || 'Scene',+ prompt: `${section.title || ''}. ${detail}`.trim() + '. Cinematic explanatory B-roll, natural motion, coherent lighting, no captions or on-screen text.'+ });+ }+ if (script.conclusion?.finalThought) {+ prompts.push({ label: 'Conclusion', prompt: `${script.conclusion.finalThought}. Memorable cinematic closing shot, no captions or on-screen text.` });+ }++ const clipDuration = Number(settings.clipDuration || 8);+ const maxScenes = Math.max(0, Math.floor(Number(settings.maxGeneratedSeconds || 0) / clipDuration));+ return prompts.slice(0, maxScenes).map((scene, index) => ({+ ...scene,+ index,+ duration: clipDuration,+ firstFrame: visualAssets[index % Math.max(1, visualAssets.length)] || null,+ referenceImages: []+ }));+ }++ async generateClips({ jobId, productionId, script, visualAssets = [], outputDir }) {+ const settings = await this.settings();+ const routingRequest = {+ duration: settings.clipDuration,+ firstFrame: visualAssets[0] || null,+ generateAudio: settings.generateAudio+ };+ const provider = this.registry.select(settings.provider, settings.order, routingRequest);+ const providerInfo = provider.describe();+ if (provider.id === 'slideshow' || settings.mode === 'slideshow' || settings.maxGeneratedSeconds === 0) {+ return { clips: [], requestedProvider: settings.provider, actualProvider: 'slideshow', model: 'local-ffmpeg', settings };+ }++ const normalized = provider.normalizeRequest(routingRequest);+ const effectiveSettings = { ...settings, clipDuration: normalized.duration };+ const scenes = this.buildScenePlan(script, visualAssets, effectiveSettings);+ const clips = [];+ for (const scene of scenes) {+ const outputPath = path.join(outputDir, `${productionId}_${provider.id}_${String(scene.index).padStart(2, '0')}.mp4`);+ const result = await this.generateClip({+ jobId,+ productionId,+ scene,+ provider,+ outputPath,+ request: {+ prompt: scene.prompt,+ duration: scene.duration,+ firstFrame: scene.firstFrame,+ referenceImages: scene.referenceImages,+ resolution: settings.resolution,+ aspectRatio: settings.aspectRatio,+ generateAudio: settings.generateAudio+ }+ });+ clips.push({ ...scene, path: result.outputPath, provider: provider.id, model: result.task.model, taskId: result.task.external_task_id });+ }+ const models = [...new Set(clips.map(clip => clip.model).filter(Boolean))];+ return {+ clips, requestedProvider: settings.provider, actualProvider: provider.id,+ model: models.join(', ') || providerInfo.model, settings: effectiveSettings+ };+ }++ async generateClip({ jobId, productionId, scene, provider, outputPath, request }) {+ let task = this.db?.findMediaGenerationTask+ ? await this.db.findMediaGenerationTask(jobId, scene.index, provider.id)+ : null;++ if (task?.status === 'succeeded' && task.output_path && await this.isValidVideo(task.output_path)) {+ this.logger.info(`Reusing ${provider.id} scene ${scene.index} from ${task.external_task_id}`);+ return { task, outputPath: task.output_path, reused: true };+ }++ if (!task) {+ task = this.db?.createMediaGenerationTask+ ? await this.db.createMediaGenerationTask({+ jobId, productionId, sceneIndex: scene.index, provider: provider.id, model: provider.model,+ status: 'submitting', request: this.safeRequest(request)+ })+ : { id: `media_${Date.now()}_${scene.index}`, status: 'submitting' };+ }++ let remote;+ try {+ if (task.external_task_id && ['queued', 'running', 'submitting'].includes(task.status)) {+ remote = await provider.getTask(task.external_task_id, task.providerData || {});+ } else {+ await this.assertNotCancelled(jobId, provider, task);+ remote = await provider.createTask(request);+ }+ task = await this.updateTask(task, {+ status: remote.status,+ model: remote.model || task.model,+ externalTaskId: remote.externalTaskId,+ providerData: this.providerData(remote),+ error: remote.error || null+ });++ const started = Date.now();+ while (!TERMINAL.has(remote.status)) {+ if (Date.now() - started > this.maxPollMs) {+ const error = new Error(`${provider.id} did not finish within the configured timeout`);+ error.code = 'MEDIA_PROVIDER_TIMEOUT';+ throw error;+ }+ await this.assertNotCancelled(jobId, provider, task);+ await this.sleep(this.pollIntervalMs);+ remote = await provider.getTask(remote.externalTaskId, task.providerData || {});+ task = await this.updateTask(task, {+ status: remote.status,+ providerData: this.providerData(remote),+ error: remote.error || null+ });+ }++ if (remote.status !== 'succeeded') {+ const error = new Error(remote.error || `${provider.id} video generation ${remote.status}`);+ error.code = remote.status === 'cancelled' ? 'JOB_CANCELLED' : 'MEDIA_PROVIDER_FAILED';+ throw error;+ }++ await provider.downloadResult(remote, outputPath);+ if (!await this.isValidVideo(outputPath)) throw new Error(`${provider.id} returned an invalid MP4 asset`);+ task = await this.updateTask(task, {+ status: 'succeeded', outputPath, completedAt: new Date().toISOString(),+ providerData: this.providerData(remote), error: null+ });+ return { task, outputPath, reused: false };+ } catch (error) {+ await this.updateTask(task, {+ status: error.code === 'JOB_CANCELLED' ? 'cancelled' : 'failed',+ error: safeModelError(error), completedAt: new Date().toISOString()+ });+ throw error;+ }+ }++ safeRequest(request) {+ const reference = value => value ? path.basename(String(value)) : null;+ return {+ prompt: String(request.prompt || '').slice(0, 2000),+ duration: request.duration,+ resolution: request.resolution,+ aspectRatio: request.aspectRatio,+ generateAudio: request.generateAudio,+ firstFrame: reference(request.firstFrame),+ lastFrame: reference(request.lastFrame),+ referenceImages: (request.referenceImages || []).map(reference),+ referenceVideos: (request.referenceVideos || []).map(reference),+ referenceAudios: (request.referenceAudios || []).map(reference)+ };+ }++ providerData(remote = {}) {+ return {+ outputUrl: remote.outputUrl || null,+ taskType: remote.taskType || null,+ model: remote.model || null+ };+ }++ async updateTask(task, changes) {+ if (!this.db?.updateMediaGenerationTask) return { ...task, ...changes, external_task_id: changes.externalTaskId || task.external_task_id, providerData: changes.providerData || task.providerData };+ return this.db.updateMediaGenerationTask(task.id, changes);+ }++ async assertNotCancelled(jobId, provider, task) {+ if (!jobId || !this.db?.getGenerationJob) return;+ const job = await this.db.getGenerationJob(jobId);+ if (!job?.cancelRequested) return;+ if (task?.external_task_id && provider.capabilities.cancellation) {+ await provider.cancelTask(task.external_task_id).catch(() => {});+ }+ const error = new Error(job.details?.cancelReason || 'Generation cancelled by operator');+ error.code = 'JOB_CANCELLED';+ throw error;+ }++ async isValidVideo(filePath) {+ try {+ const buffer = await fs.readFile(filePath);+ if (buffer.length < 1000 || !buffer.subarray(4, 32).toString('ascii').includes('ftyp')) return false;+ await runFFmpeg(['-v', 'error', '-i', filePath, '-f', 'null', '-']);+ return true;+ } catch (_error) {+ return false;+ }+ }+}++module.exports = { MediaGenerationService };diff --git a/utils/production-readiness-service.js b/utils/production-readiness-service.jsindex f19486e..0b06da6 100644--- a/utils/production-readiness-service.js+++ b/utils/production-readiness-service.js@@ -6,6 +6,7 @@ const { AIVideoGenerator } = require('./ai-video-generator');const { checkFFmpeg, runFFmpeg } = require('./ffmpeg');const { validateYouTubeMetadata } = require('./youtube-metadata-validator');const { Logger } = require('./logger');+const { MediaGenerationService } = require('./media-generation-service');const STALE_AFTER_MS = 24 * 60 * 60 * 1000;@@ -71,6 +72,7 @@ class ProductionReadinessService {try {checks.push(await this.executeCheck('text_provider', 'AI text provider', true, () => this.probeText()));checks.push(await this.executeCheck('image_provider', 'Image provider', false, () => this.probeImage(tempDir, Boolean(options.includePaidMedia))));+ checks.push(await this.executeCheck('video_provider', 'AI video provider', true, () => this.probeVideoProvider(tempDir, Boolean(options.includePaidVideo))));checks.push(await this.executeCheck('voice_narration', 'Voice narration', true, () => this.probeNarration(tempDir)));checks.push(await this.executeCheck('video_assembly', 'Audio/video assembly', true, () => this.probeVideoAssembly(tempDir)));checks.push(await this.executeCheck('youtube_access', 'YouTube channel access', true, () => this.probeYouTube()));@@ -167,6 +169,51 @@ class ProductionReadinessService {return { message: 'A live narration sample was generated.', details: { bytes: stats.size } };}+ async probeVideoProvider(tempDir, includePaidVideo) {+ if (this.probes.videoProvider) return this.probes.videoProvider({ tempDir, includePaidVideo });+ const service = new MediaGenerationService(this.db, this.credentialManager.credentials || {});+ const settings = await service.settings();+ const requested = settings.provider;+ const configured = requested === 'auto' ? service.registry.select('auto', settings.order) : service.registry.get(requested);+ if (!configured || !configured.isAvailable()) {+ if (requested === 'slideshow') {+ return { message: 'Local slideshow video generation is selected; no paid AI video provider is required.', details: { provider: 'slideshow' } };+ }+ throw new Error(`${requested} is selected but its credentials are not configured`);+ }+ if (configured.id === 'slideshow') {+ return { message: 'Local slideshow video generation is selected; no paid AI video provider is required.', details: { provider: 'slideshow' } };+ }+ if (!includePaidVideo) {+ return {+ status: 'skipped',+ message: `${configured.id} is configured; the paid live video probe was not requested.`,+ remediation: 'Enable βInclude paid video probeβ on the next readiness run to verify the selected model.',+ details: { provider: configured.id, model: configured.model }+ };+ }+ const outputPath = path.join(tempDir, 'readiness-provider.mp4');+ const result = await service.generateClip({+ jobId: null,+ productionId: `readiness_${Date.now()}`,+ scene: { index: Date.now() },+ provider: configured,+ outputPath,+ request: {+ prompt: 'A small red ball rolls slowly across a plain dark studio floor, static camera, no text.',+ duration: configured.capabilities.minDuration || 4,+ resolution: settings.resolution,+ aspectRatio: settings.aspectRatio,+ generateAudio: false+ }+ });+ const stats = await fs.stat(result.outputPath);+ return {+ message: `${configured.id} created and returned a decodable MP4.`,+ details: { provider: configured.id, model: configured.model, bytes: stats.size, taskId: result.task.external_task_id }+ };+ }+async probeVideoAssembly(tempDir) {if (this.probes.videoAssembly) return this.probes.videoAssembly({ tempDir });if (!await checkFFmpeg()) throw new Error('FFmpeg is not available');@@ -233,6 +280,7 @@ class ProductionReadinessService {const messages = {text_provider: 'Run npm run walkthrough, verify the selected model, and confirm provider credits or quota.',image_provider: 'Verify paid image access or rely on the built-in gradient visual fallback.',+ video_provider: 'Configure the selected provider credentials, choose local slideshow, or rerun with the paid video probe enabled.',voice_narration: 'Configure OpenAI, Gemini TTS, ElevenLabs with a voice ID, or Azure Speech, then rerun.',video_assembly: 'Run npm install to restore ffmpeg-static, or configure FFMPEG_PATH to a working binary.',youtube_access: 'Reconnect YouTube in npm run walkthrough and ensure the Google account owns a channel.',diff --git a/utils/provenance-service.js b/utils/provenance-service.jsindex 95e7250..3549361 100644--- a/utils/provenance-service.js+++ b/utils/provenance-service.js@@ -17,7 +17,7 @@ class ProvenanceService {const sources = this.normalizeSources(production.strategy?.researchSources || []);const sourceIdByUrl = new Map(sources.map(source => [source.url, source.id]));const claims = this.normalizeClaims(production.script?.claims || [], sources, sourceIdByUrl);- const provenance = this.build({ sources, claims, containsSyntheticMedia: false });+ const provenance = this.build({ sources, claims, containsSyntheticMedia: production.containsSyntheticMedia === true });await this.db.saveContentProvenance(productionId, provenance);return this.db.getContentProvenance(productionId);}diff --git a/utils/video-providers.js b/utils/video-providers.jsnew file mode 100644index 0000000..71e99f6--- /dev/null+++ b/utils/video-providers.js@@ -0,0 +1,459 @@+const crypto = require('crypto');+const fs = require('fs').promises;+const path = require('path');+const axios = require('axios');+const Replicate = require('replicate');++const DEFAULT_PROVIDER_ORDER = ['seedance', 'minimax_h3', 'google_omni', 'kling', 'wan', 'slideshow'];++const clamp = (value, min, max) => Math.max(min, Math.min(max, Number(value)));++function normalizeCredentials(input = {}) {+ return input.credentials || input;+}++function base64Url(value) {+ return Buffer.from(value).toString('base64url');+}++function safeModelError(error) {+ return String(error?.response?.data?.message || error?.response?.data?.error?.message || error?.message || error || 'Video provider request failed')+ .replace(/Bearer\s+[A-Za-z0-9._~-]+/gi, 'Bearer [redacted]')+ .replace(/(api[_-]?key|token|secret)=([^\s&]+)/gi, '$1=[redacted]')+ .slice(0, 500);+}++async function fileToDataUrl(filePath) {+ if (!filePath) return null;+ if (/^https?:\/\//i.test(filePath) || /^data:/i.test(filePath)) return filePath;+ const extension = path.extname(filePath).toLowerCase();+ const mime = {+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',+ '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.mp3': 'audio/mpeg', '.wav': 'audio/wav'+ }[extension] || 'application/octet-stream';+ return `data:${mime};base64,${(await fs.readFile(filePath)).toString('base64')}`;+}++async function fileToReplicateInput(filePath) {+ if (!filePath || /^https?:\/\//i.test(filePath) || /^data:/i.test(filePath)) return filePath;+ return fs.readFile(filePath);+}++class VideoProvider {+ constructor(id, options = {}) {+ this.id = id;+ this.model = options.model;+ this.capabilities = options.capabilities || {};+ }++ isAvailable() { return false; }++ supports(request = {}) {+ const duration = Number(request.duration || 0);+ if (duration && this.capabilities.minDuration && duration < this.capabilities.minDuration) return false;+ if (duration && Number.isFinite(this.capabilities.maxDuration) && duration > this.capabilities.maxDuration) return false;+ if (request.firstFrame && !this.capabilities.firstFrame) return false;+ if (request.lastFrame && !this.capabilities.lastFrame) return false;+ if (request.generateAudio && !this.capabilities.nativeAudio) return false;+ if ((request.referenceImages || []).length > Number(this.capabilities.referenceImages || 0)) return false;+ if ((request.referenceVideos || []).length > Number(this.capabilities.referenceVideos || 0)) return false;+ if ((request.referenceAudios || []).length > Number(this.capabilities.referenceAudios || 0)) return false;+ return true;+ }++ describe() {+ return {+ id: this.id,+ model: this.model,+ available: this.isAvailable(),+ capabilities: this.capabilities+ };+ }++ normalizeRequest(request = {}) {+ const minimum = this.capabilities.minDuration || 4;+ const maximum = this.capabilities.maxDuration || 10;+ return {+ ...request,+ prompt: String(request.prompt || '').slice(0, this.capabilities.maxPromptLength || 2000),+ duration: clamp(request.duration || minimum, minimum, maximum),+ aspectRatio: request.aspectRatio || '16:9',+ resolution: request.resolution || this.capabilities.defaultResolution || '720p',+ generateAudio: request.generateAudio === true,+ referenceImages: request.referenceImages || [],+ referenceVideos: request.referenceVideos || [],+ referenceAudios: request.referenceAudios || []+ };+ }++ async downloadResult(task, outputPath) {+ if (!task.outputUrl) throw new Error(`${this.id} completed without a downloadable video`);+ const response = await axios.get(task.outputUrl, { responseType: 'arraybuffer', timeout: 120000 });+ await fs.mkdir(path.dirname(outputPath), { recursive: true });+ await fs.writeFile(outputPath, Buffer.from(response.data));+ return outputPath;+ }++ async cancelTask() { return false; }+}++class SeedanceProvider extends VideoProvider {+ constructor(credentials, options = {}) {+ const key = normalizeCredentials(credentials).replicate?.apiKey || process.env.REPLICATE_API_TOKEN || process.env.REPLICATE_API_KEY;+ super('seedance', {+ model: options.model || process.env.SEEDANCE_MODEL || 'bytedance/seedance-2.5',+ capabilities: {+ minDuration: 4, maxDuration: 30, defaultResolution: '720p', maxPromptLength: 2000,+ text: true, firstFrame: true, lastFrame: true, referenceImages: 30,+ referenceVideos: 10, referenceAudios: 10, nativeAudio: true, cancellation: true+ }+ });+ this.client = options.client || (key ? new Replicate({ auth: key }) : null);+ }++ isAvailable() { return Boolean(this.client); }++ async createTask(input) {+ const request = this.normalizeRequest(input);+ const firstFrame = await fileToReplicateInput(request.firstFrame);+ const lastFrame = await fileToReplicateInput(request.lastFrame);+ const hasFrames = Boolean(firstFrame || lastFrame);+ const payload = {+ prompt: request.prompt,+ duration: request.duration,+ resolution: request.resolution,+ aspect_ratio: hasFrames ? 'adaptive' : request.aspectRatio,+ output_format: 'mp4',+ generate_audio: request.generateAudio,+ watermark: request.watermark === true,+ ...(request.seed === undefined ? {} : { seed: request.seed })+ };+ if (firstFrame) payload.image = firstFrame;+ if (lastFrame) payload.last_frame_image = lastFrame;+ if (!hasFrames) {+ payload.reference_images = await Promise.all(request.referenceImages.slice(0, 30).map(fileToReplicateInput));+ payload.reference_videos = await Promise.all(request.referenceVideos.slice(0, 10).map(fileToReplicateInput));+ payload.reference_audios = await Promise.all(request.referenceAudios.slice(0, 10).map(fileToReplicateInput));+ }+ const prediction = await this.client.predictions.create({ model: this.model, input: payload });+ return this.normalizeTask(prediction);+ }++ async getTask(id) { return this.normalizeTask(await this.client.predictions.get(id)); }++ async cancelTask(id) {+ await this.client.predictions.cancel(id);+ return true;+ }++ normalizeTask(task = {}) {+ const status = { starting: 'queued', processing: 'running', succeeded: 'succeeded', successful: 'succeeded', failed: 'failed', canceled: 'cancelled' }[task.status] || task.status || 'queued';+ const output = task.output;+ const outputUrl = typeof output === 'string'+ ? output+ : Array.isArray(output) ? String(output[0] || '')+ : typeof output?.url === 'function' ? String(output.url()) : output?.url || null;+ return { externalTaskId: task.id, status, outputUrl, error: task.error ? safeModelError(task.error) : null };+ }+}++class MiniMaxH3Provider extends VideoProvider {+ constructor(credentials, options = {}) {+ const creds = normalizeCredentials(credentials);+ super('minimax_h3', {+ model: options.model || process.env.MINIMAX_VIDEO_MODEL || 'MiniMax-H3',+ capabilities: {+ minDuration: 4, maxDuration: 15, defaultResolution: '768P', maxPromptLength: 7000,+ text: true, firstFrame: true, lastFrame: true, referenceImages: 9,+ referenceVideos: 3, referenceAudios: 3, nativeAudio: true, resolution2k: true+ }+ });+ this.apiKey = options.apiKey || creds.minimax?.apiKey || process.env.MINIMAX_API_KEY;+ this.baseUrl = options.baseUrl || process.env.MINIMAX_API_BASE || 'https://api.minimax.io';+ this.http = options.http || axios;+ }++ isAvailable() { return Boolean(this.apiKey); }+ headers() { return { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }; }++ async createTask(input) {+ const request = this.normalizeRequest(input);+ const content = [{ type: 'text', text: request.prompt }];+ const add = async (type, role, item) => content.push({ type, [type]: { url: await fileToDataUrl(item) }, role });+ if (request.firstFrame) await add('image_url', 'first_frame', request.firstFrame);+ if (request.lastFrame) await add('image_url', 'last_frame', request.lastFrame);+ for (const item of request.referenceImages.slice(0, 9)) await add('image_url', 'reference_image', item);+ for (const item of request.referenceVideos.slice(0, 3)) await add('video_url', 'reference_video', item);+ for (const item of request.referenceAudios.slice(0, 3)) await add('audio_url', 'reference_audio', item);+ const body = { model: this.model, content, duration: request.duration, resolution: request.resolution };+ if (!request.firstFrame && !request.lastFrame) body.ratio = request.aspectRatio;+ const response = await this.http.post(`${this.baseUrl}/v2/video_generation`, body, { headers: this.headers(), timeout: 120000 });+ return { externalTaskId: response.data.task_id, status: 'queued', outputUrl: null, error: null };+ }++ async getTask(id) {+ const response = await this.http.get(`${this.baseUrl}/v2/query/video_generation/${id}`, { headers: this.headers(), timeout: 30000 });+ const task = response.data.task || response.data;+ return {+ externalTaskId: id,+ status: { success: 'succeeded', succeeded: 'succeeded', failed: 'failed', processing: 'running', running: 'running', queued: 'queued' }[task.status] || task.status,+ outputUrl: task.content?.url || task.video_url || null,+ error: task.error ? safeModelError(task.error) : null+ };+ }+}++class GoogleOmniProvider extends VideoProvider {+ constructor(credentials, options = {}) {+ const creds = normalizeCredentials(credentials);+ super('google_omni', {+ model: options.model || process.env.GEMINI_VIDEO_MODEL || 'gemini-omni-flash-preview',+ capabilities: {+ minDuration: 3, maxDuration: 10, defaultResolution: '720p', maxPromptLength: 7000,+ text: true, firstFrame: true, referenceImages: 8, referenceVideos: 1,+ nativeAudio: true, conversationalEditing: true+ }+ });+ const key = options.apiKey || creds.gemini?.apiKey || process.env.GEMINI_API_KEY;+ if (options.client) this.client = options.client;+ else if (key) {+ const { GoogleGenAI } = require('@google/genai');+ this.client = new GoogleGenAI({ apiKey: key });+ }+ }++ isAvailable() { return Boolean(this.client); }++ async createTask(input) {+ const request = this.normalizeRequest(input);+ const media = [request.firstFrame, ...request.referenceImages].filter(Boolean).slice(0, 8);+ const content = [];+ for (const item of media) {+ const dataUrl = await fileToDataUrl(item);+ const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);+ content.push(match ? { type: 'image', mime_type: match[1], data: match[2] } : { type: 'image', uri: dataUrl });+ }+ content.push({ type: 'text', text: request.prompt });+ const interaction = await this.client.interactions.create({+ model: this.model,+ input: content.length === 1 ? request.prompt : content,+ response_format: { type: 'video', aspect_ratio: request.aspectRatio, delivery: 'uri' }+ });+ const video = interaction.output_video || interaction.outputVideo || this.findVideo(interaction.steps);+ const outputUrl = video?.uri || null;+ const inlineData = video?.data || null;+ return {+ externalTaskId: outputUrl || interaction.id,+ status: inlineData ? 'succeeded' : 'queued',+ outputUrl,+ inlineData,+ error: null+ };+ }++ findVideo(steps = []) {+ for (const step of steps || []) {+ const found = (step.content || []).find(item => item.type === 'video');+ if (found) return found;+ }+ return null;+ }++ async getTask(id) {+ if (!String(id).includes('files/')) return { externalTaskId: id, status: 'running', outputUrl: null, error: null };+ const match = String(id).match(/files\/([A-Za-z0-9_-]+)/);+ if (!match) return { externalTaskId: id, status: 'failed', outputUrl: null, error: 'Gemini returned an invalid file URI' };+ const name = `files/${match[1]}`;+ const file = await this.client.files.get({ name });+ const state = String(file.state?.name || file.state || '').toUpperCase();+ return {+ externalTaskId: id,+ status: state === 'ACTIVE' ? 'succeeded' : state === 'FAILED' ? 'failed' : 'running',+ outputUrl: id,+ error: state === 'FAILED' ? 'Gemini video processing failed' : null+ };+ }++ async downloadResult(task, outputPath) {+ await fs.mkdir(path.dirname(outputPath), { recursive: true });+ if (task.inlineData) {+ await fs.writeFile(outputPath, Buffer.from(task.inlineData, 'base64'));+ return outputPath;+ }+ await this.client.files.download({ file: { uri: task.outputUrl, mimeType: 'video/mp4' }, downloadPath: outputPath });+ return outputPath;+ }+}++class KlingProvider extends VideoProvider {+ constructor(credentials, options = {}) {+ const creds = normalizeCredentials(credentials);+ super('kling', {+ model: options.model || process.env.KLING_VIDEO_MODEL || 'kling-v3-omni',+ capabilities: {+ minDuration: 3, maxDuration: 15, defaultResolution: '1080p', maxPromptLength: 2500,+ text: true, firstFrame: true, lastFrame: true, referenceImages: 4,+ referenceVideos: 1, nativeAudio: true, storyboard: true+ }+ });+ this.accessKey = options.accessKey || creds.kling?.accessKey || process.env.KLING_ACCESS_KEY;+ this.secretKey = options.secretKey || creds.kling?.secretKey || process.env.KLING_SECRET_KEY;+ this.baseUrl = options.baseUrl || process.env.KLING_API_BASE_URL || 'https://api.klingai.com';+ this.http = options.http || axios;+ }++ isAvailable() { return Boolean(this.accessKey && this.secretKey); }++ token() {+ const now = Math.floor(Date.now() / 1000);+ const header = base64Url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));+ const payload = base64Url(JSON.stringify({ iss: this.accessKey, exp: now + 1800, nbf: now - 5 }));+ const signature = crypto.createHmac('sha256', this.secretKey).update(`${header}.${payload}`).digest('base64url');+ return `${header}.${payload}.${signature}`;+ }++ headers() { return { Authorization: `Bearer ${this.token()}`, 'Content-Type': 'application/json' }; }++ async createTask(input) {+ const request = this.normalizeRequest(input);+ const imageMode = Boolean(request.firstFrame);+ const endpoint = imageMode ? 'image2video' : 'text2video';+ const body = {+ model_name: this.model,+ prompt: request.prompt,+ duration: String(request.duration),+ aspect_ratio: request.aspectRatio,+ mode: request.resolution === '4k' ? 'pro' : 'std',+ sound: request.generateAudio ? 'on' : 'off'+ };+ if (imageMode) body.image = (await fileToDataUrl(request.firstFrame)).replace(/^data:[^;]+;base64,/, '');+ if (request.lastFrame) body.image_tail = (await fileToDataUrl(request.lastFrame)).replace(/^data:[^;]+;base64,/, '');+ const response = await this.http.post(`${this.baseUrl}/v1/videos/${endpoint}`, body, { headers: this.headers(), timeout: 120000 });+ const data = response.data.data || response.data;+ return { externalTaskId: data.task_id, status: 'queued', outputUrl: null, error: null, taskType: endpoint };+ }++ async getTask(id, context = {}) {+ const taskType = context.taskType || 'text2video';+ const response = await this.http.get(`${this.baseUrl}/v1/videos/${taskType}/${id}`, { headers: this.headers(), timeout: 30000 });+ const data = response.data.data || response.data;+ const status = { submitted: 'queued', processing: 'running', succeed: 'succeeded', succeeded: 'succeeded', failed: 'failed' }[data.task_status] || data.task_status;+ return {+ externalTaskId: id,+ status,+ outputUrl: data.task_result?.videos?.[0]?.url || null,+ error: data.task_status_msg || null,+ taskType+ };+ }+}++class WanProvider extends VideoProvider {+ constructor(credentials, options = {}) {+ const creds = normalizeCredentials(credentials);+ super('wan', {+ model: options.model || process.env.WAN_VIDEO_MODEL || 'wan2.7-t2v-2026-06-12',+ capabilities: {+ minDuration: 2, maxDuration: 15, defaultResolution: '720P', maxPromptLength: 2000,+ text: true, firstFrame: true, lastFrame: true, referenceImages: 4,+ referenceVideos: 3, referenceAudios: 3, nativeAudio: true, continuation: true+ }+ });+ this.apiKey = options.apiKey || creds.wan?.apiKey || process.env.DASHSCOPE_API_KEY;+ this.baseUrl = (options.baseUrl || process.env.DASHSCOPE_VIDEO_ENDPOINT || 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis').replace(/\/$/, '');+ this.taskBaseUrl = (options.taskBaseUrl || process.env.DASHSCOPE_TASK_ENDPOINT || 'https://dashscope-intl.aliyuncs.com/api/v1/tasks').replace(/\/$/, '');+ this.http = options.http || axios;+ }++ isAvailable() { return Boolean(this.apiKey); }+ headers() { return { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', 'X-DashScope-Async': 'enable' }; }++ async createTask(input) {+ const request = this.normalizeRequest(input);+ const references = [...request.referenceImages, ...request.referenceVideos, ...request.referenceAudios];+ let model = 'wan2.7-t2v-2026-06-12';+ if (references.length) model = 'wan2.7-r2v-2026-06-12';+ else if (request.firstFrame || request.lastFrame) model = 'wan2.7-i2v-2026-04-25';+ const media = [];+ if (request.firstFrame) media.push({ type: 'first_frame', url: await fileToDataUrl(request.firstFrame) });+ if (request.lastFrame) media.push({ type: 'last_frame', url: await fileToDataUrl(request.lastFrame) });+ for (const item of request.referenceImages) media.push({ type: 'reference_image', url: await fileToDataUrl(item) });+ for (const item of request.referenceVideos) media.push({ type: 'reference_video', url: await fileToDataUrl(item) });+ for (let index = 0; index < request.referenceAudios.length; index++) {+ if (!media[index] || !['reference_image', 'reference_video'].includes(media[index].type)) break;+ media[index].reference_voice = await fileToDataUrl(request.referenceAudios[index]);+ }+ const body = {+ model,+ input: { prompt: request.prompt, ...(media.length ? { media } : {}) },+ parameters: {+ resolution: String(request.resolution).toUpperCase(), duration: request.duration,+ ratio: request.aspectRatio, prompt_extend: true, watermark: request.watermark === true+ }+ };+ const response = await this.http.post(this.baseUrl, body, { headers: this.headers(), timeout: 120000 });+ const data = response.data.output || response.data;+ return { externalTaskId: data.task_id, status: 'queued', outputUrl: null, error: null, model };+ }++ async getTask(id) {+ const response = await this.http.get(`${this.taskBaseUrl}/${id}`, { headers: { Authorization: `Bearer ${this.apiKey}` }, timeout: 30000 });+ const data = response.data.output || response.data;+ const status = { PENDING: 'queued', RUNNING: 'running', SUCCEEDED: 'succeeded', FAILED: 'failed', CANCELED: 'cancelled', UNKNOWN: 'failed' }[data.task_status] || String(data.task_status || '').toLowerCase();+ return {+ externalTaskId: id,+ status,+ outputUrl: data.video_url || data.results?.[0]?.url || null,+ error: data.message || null+ };+ }+}++class SlideshowProvider extends VideoProvider {+ constructor() {+ super('slideshow', { model: 'local-ffmpeg', capabilities: { local: true, text: true, maxDuration: Infinity } });+ }+ isAvailable() { return true; }+}++class VideoProviderRegistry {+ constructor(credentials = {}, options = {}) {+ const injected = options.providers || {};+ this.providers = new Map([+ ['seedance', injected.seedance || new SeedanceProvider(credentials, options.seedance)],+ ['minimax_h3', injected.minimax_h3 || new MiniMaxH3Provider(credentials, options.minimax_h3)],+ ['google_omni', injected.google_omni || new GoogleOmniProvider(credentials, options.google_omni)],+ ['kling', injected.kling || new KlingProvider(credentials, options.kling)],+ ['wan', injected.wan || new WanProvider(credentials, options.wan)],+ ['slideshow', injected.slideshow || new SlideshowProvider()]+ ]);+ }++ get(id) { return this.providers.get(id); }+ list() { return Array.from(this.providers.values()).map(provider => provider.describe()); }++ select(requested = 'slideshow', order = DEFAULT_PROVIDER_ORDER, request = {}) {+ if (requested && requested !== 'auto') {+ const provider = this.get(requested);+ return provider?.isAvailable() ? provider : this.get('slideshow');+ }+ for (const id of order) {+ const provider = this.get(id);+ if (provider?.isAvailable() && provider.supports(request)) return provider;+ }+ return this.get('slideshow');+ }+}++module.exports = {+ DEFAULT_PROVIDER_ORDER,+ VideoProvider,+ VideoProviderRegistry,+ SeedanceProvider,+ MiniMaxH3Provider,+ GoogleOmniProvider,+ KlingProvider,+ WanProvider,+ SlideshowProvider,+ safeModelError+};diff --git a/walkthrough.js b/walkthrough.jsindex 0b94e6c..4437966 100644--- a/walkthrough.js+++ b/walkthrough.js@@ -14,6 +14,7 @@ const {} = require('./utils/ai-text-service');const { Database } = require('./database/db');const { checkFFmpeg, ffmpegInstallHint } = require('./utils/ffmpeg');+const { VideoProviderRegistry } = require('./utils/video-providers');// Everything a beginner needs to know about each provider, in one placeconst AI_PROVIDER_GUIDE = {@@ -108,10 +109,49 @@ const AI_PROVIDER_GUIDE = {}};+const VIDEO_PROVIDER_GUIDE = {+ slideshow: {+ label: 'Local slideshow β no external video charges',+ keyUrl: null,+ covers: 'local FFmpeg assembly using generated stills and narration'+ },+ seedance: {+ label: 'ByteDance Seedance 2.5 β cinematic 30-second multimodal scenes',+ keyUrl: 'https://replicate.com/account/api-tokens',+ credentialName: 'Replicate API token',+ save(credentials, value) { credentials.replicate = { ...(credentials.replicate || {}), apiKey: value }; }+ },+ minimax_h3: {+ label: 'MiniMax H3 β multimodal native-audio video up to 2K',+ keyUrl: 'https://platform.minimax.io/user-center/basic-information/interface-key',+ credentialName: 'MiniMax API key',+ save(credentials, value) { credentials.minimax = { apiKey: value }; }+ },+ google_omni: {+ label: 'Google Gemini Omni Flash β fast conversational video generation',+ keyUrl: 'https://aistudio.google.com/apikey',+ credentialName: 'Gemini API key',+ save(credentials, value) { credentials.gemini = { ...(credentials.gemini || {}), apiKey: value }; }+ },+ kling: {+ label: 'Kuaishou Kling 3.0 Omni β storyboards and character performance',+ keyUrl: 'https://kling.ai/global/dev',+ credentialName: 'Kling access key',+ secretName: 'Kling secret key',+ save(credentials, value, secret) { credentials.kling = { accessKey: value, secretKey: secret }; }+ },+ wan: {+ label: 'Alibaba Wan 2.7 β efficient multimodal and continuation workflows',+ keyUrl: 'https://modelstudio.console.alibabacloud.com/',+ credentialName: 'DashScope API key',+ save(credentials, value) { credentials.wan = { apiKey: value }; }+ }+};+class SetupWalkthrough {constructor() {this.cm = new CredentialManager();- this.totalSteps = 5;+ this.totalSteps = 6;}header(step, title) {@@ -143,6 +183,7 @@ class SetupWalkthrough {try {await this.stepSystemCheck();await this.stepAIProvider();+ await this.stepVideoProvider();await this.stepYouTube();await this.stepChannelBasics();await this.stepFinish();@@ -305,9 +346,49 @@ class SetupWalkthrough {}}- // ββ Step 3: YouTube ββββββββββββββββββββββββββββββββββββββββββββββββββββ+ async stepVideoProvider() {+ this.header(3, 'Video generation provider');+ console.log(chalk.white('Long-form videos use hybrid assembly: selected AI clips plus local FFmpeg rendering.'));+ console.log(chalk.white('Local slideshow stays available and is the default so setup never spends credits unexpectedly.'));+ const { providerId } = await inquirer.prompt([{+ type: 'list',+ name: 'providerId',+ message: 'Which video provider should Lumen use?',+ choices: Object.entries(VIDEO_PROVIDER_GUIDE).map(([value, guide]) => ({ name: guide.label, value }))+ }]);+ const guide = VIDEO_PROVIDER_GUIDE[providerId];+ const db = new Database();+ await db.initialize();+ try {+ if (providerId === 'slideshow') {+ await db.setSetting('video_provider', 'slideshow');+ console.log(chalk.green(' β Local slideshow selected.'));+ return;+ }+ console.log(chalk.white(` β ${chalk.blue(guide.keyUrl)} (opening in your browser)`));+ this.openBrowser(guide.keyUrl);+ const answers = await inquirer.prompt([+ { type: 'password', name: 'key', mask: '*', message: `Paste your ${guide.credentialName} (empty to skip):` },+ { type: 'password', name: 'secret', mask: '*', message: `Paste your ${guide.secretName}:`, when: current => Boolean(guide.secretName && current.key) }+ ]);+ if (!answers.key?.trim()) {+ console.log(chalk.yellow(' Skipped β local slideshow remains selected.'));+ await db.setSetting('video_provider', 'slideshow');+ return;+ }+ guide.save(this.cm.credentials, answers.key.trim(), answers.secret?.trim());+ await this.cm.saveCredentials();+ await db.setSetting('video_provider', providerId);+ console.log(chalk.green(` β ${guide.label} selected.`));+ console.log(chalk.gray(' Run the paid video probe in Production readiness before enabling autonomous generation.'));+ } finally {+ await db.close();+ }+ }++ // ββ Step 4: YouTube ββββββββββββββββββββββββββββββββββββββββββββββββββββasync stepYouTube() {- this.header(3, 'Connecting your YouTube channel');+ this.header(4, 'Connecting your YouTube channel');if (this.cm.credentials.youtube && this.cm.tokens.youtube) {const { redo } = await inquirer.prompt([{@@ -396,9 +477,9 @@ class SetupWalkthrough {}}- // ββ Step 4: channel basics βββββββββββββββββββββββββββββββββββββββββββββ+ // ββ Step 5: channel basics βββββββββββββββββββββββββββββββββββββββββββββasync stepChannelBasics() {- this.header(4, 'Channel & content basics');+ this.header(5, 'Channel & content basics');const existing = this.cm.credentials.channel || {};const answers = await inquirer.prompt([@@ -448,9 +529,9 @@ class SetupWalkthrough {console.log(chalk.gray(' set DEFAULT_PRIVACY_STATUS=public in .env when you\'re confident.'));}- // ββ Step 5: summary ββββββββββββββββββββββββββββββββββββββββββββββββββββ+ // ββ Step 6: summary ββββββββββββββββββββββββββββββββββββββββββββββββββββasync stepFinish() {- this.header(5, 'All set β here\'s what your pipeline can do');+ this.header(6, 'All set β here\'s what your pipeline can do');await this.cm.loadCredentials();await this.cm.loadTokens();@@ -461,12 +542,15 @@ class SetupWalkthrough {const hasMedia = Boolean(creds.openai?.apiKey || process.env.OPENAI_API_KEY || hasGemini);const hasFFmpeg = await checkFFmpeg();const hasUpload = Boolean(creds.youtube && this.cm.tokens.youtube);+ const videoProviders = new VideoProviderRegistry(creds).list();+ const hasVideoProvider = videoProviders.some(provider => provider.available && provider.id !== 'slideshow');const rows = [{ ok: hasText, name: 'Write scripts & pick topics', fix: 'step 2 (AI provider)' },{ ok: hasMedia, name: 'Generate images & voice narration', fix: 'step 2 β use a Gemini or OpenAI key' },{ ok: hasFFmpeg, name: 'Assemble real .mp4 videos', fix: ffmpegInstallHint() },- { ok: hasUpload, name: 'Upload to YouTube', fix: 'step 3 (YouTube connection)' }+ { ok: hasVideoProvider, name: 'Generate AI video clips', fix: 'step 3 β or keep the local slideshow provider' },+ { ok: hasUpload, name: 'Upload to YouTube', fix: 'step 4 (YouTube connection)' }];for (const row of rows) {@@ -492,4 +576,4 @@ if (require.main === module) {});}-module.exports = { SetupWalkthrough, AI_PROVIDER_GUIDE };+module.exports = { SetupWalkthrough, AI_PROVIDER_GUIDE, VIDEO_PROVIDER_GUIDE };