π¬ 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
v2.2: Resolve all open issues β provider-agnostic credentials, bundled FFmpeg, publish-queue wiring, honest simulation status
darkzOGx179ef224bb0a
diff --git a/README.md b/README.mdindex 5062f7d..df3cda2 100644--- a/README.md+++ b/README.md@@ -1,5 +1,17 @@# YouTube Automation Agent+## What's New in v2.2++This release resolves every open GitHub issue (#1, #2, #3, #4, #8, #9, #13):++- **Gemini (and every other provider) now passes credential validation** β startup and setup no longer demand an OpenAI key. Any one configured AI provider (OpenAI, Gemini, OpenRouter, Kimi, MiMo, or GLM) is enough. (#3, #9)+- **FFmpeg is bundled** β `npm install` now pulls a prebuilt FFmpeg binary via `ffmpeg-static`, so `'ffmpeg' is not recognized` is gone. A system install on your PATH or `FFMPEG_PATH` in `.env` still takes precedence. (#1)+- **Generated content actually reaches the publish queue** β the `/generate` pipeline previously produced a video and then never scheduled it, so "Processing publish queue" ran forever with nothing to do. It now queues every successful production. (#2)+- **Real .mp4 output without paid keys** β if TTS isn't configured, the slideshow renders as a silent video instead of dying on a placeholder file. Placeholder `.info` assets are filtered out of slides. (#4)+- **No more silent failures** β a capability check at startup shows exactly which pipeline stages will run for real (β) vs. what's missing and how to fix it (β). Productions that only produced placeholders are marked `simulated`, are never scheduled for upload, and log a loud warning. (#4, #8, #13)+- **Setup wizard no longer hard-aborts** β missing credentials or FFmpeg produce warnings with fix instructions instead of `β Setup failed!`. (#9)+- **Publish-queue logging is informative** β shows how many items are waiting and when the next publish happens, instead of an identical line every 15 minutes. (#2)+## What's New in v2.1- **Real AI generation wired in** β the Content Strategy, Script Writer, and SEO agents now call your configured AI provider (OpenAI, OpenRouter, Kimi, MiMo, GLM, or Gemini) for topics, scripts, titles, descriptions, and tags. If no provider key is set, they fall back to the built-in templates so the pipeline still runs.@@ -106,9 +118,10 @@ Dashboard runs at `http://localhost:3456`.### Prerequisites- Node.js 18+-- [FFmpeg](https://ffmpeg.org/download.html) on your PATH (used for video assembly and audio muxing)+- FFmpeg β bundled automatically via `ffmpeg-static` on `npm install`; a system install on your PATH or an `FFMPEG_PATH` env var takes precedence- Google account (YouTube Data API β free)-- At least one AI provider key (OpenAI or Gemini) β without one, agents fall back to template-based generation+- At least one AI provider key (OpenAI, Gemini, OpenRouter, Kimi, MiMo, or GLM) β without one, agents fall back to template-based generation+- Optional: an OpenAI key for image generation and a TTS provider (OpenAI / ElevenLabs / Azure) for narration β without them you get gradient slides and silent video## Configuration@@ -300,6 +313,10 @@ youtube-automation-agent/| Problem | Fix ||---------|-----|+| `Missing credentials for: an AI provider` | Configure any one provider with `npm run credentials:setup` β OpenAI is not required |+| `'ffmpeg' is not recognized` / no .mp4 produced | Run `npm install` (fetches the bundled binary), or install FFmpeg and set `FFMPEG_PATH` |+| Video marked `simulated`, nothing uploads | Check the β lines in the startup capability check β a key or FFmpeg is missing |+| "Processing publish queue" but nothing publishes | The queue log now shows what's waiting; content publishes at its scheduled time (default: next day 2 PM) || YouTube API quota exceeded | Check quotas in Google Cloud Console; reduce posting frequency || Content generation failed | Verify API keys and credits; check `logs/` || Publishing failed | Re-authenticate YouTube OAuth tokens; check video format |diff --git a/agents/production-management-agent.js b/agents/production-management-agent.jsindex 282cc2e..138e83c 100644--- a/agents/production-management-agent.js+++ b/agents/production-management-agent.js@@ -99,14 +99,20 @@ class ProductionManagementAgent {// Final assemblyawait this.assembleVideo(productionData);-- // Mark as ready- productionData.status = 'ready';- productionData.timeline.readyForUpload = new Date().toISOString();-++ // Mark as ready β or simulated, when no real video could be produced+ const simulated = Boolean(productionData.assets.finalVideo?.simulated);+ if (simulated) {+ productionData.status = 'simulated';+ this.logger.warn(`Content ${productionId} produced PLACEHOLDER assets only β it will NOT be uploaded. Check your AI provider keys and FFmpeg installation.`);+ } else {+ productionData.status = 'ready';+ productionData.timeline.readyForUpload = new Date().toISOString();+ }+await this.db.updateProductionData(productionData);-- this.logger.info(`Content processing complete: ${productionId}`);++ this.logger.info(`Content processing complete: ${productionId} (status: ${productionData.status})`);return productionData;} catch (error) {this.logger.error('Failed to process content:', error);@@ -548,15 +554,20 @@ class ProductionManagementAgent {try {const finalVideoPath = path.join(__dirname, '..', 'data', 'videos', `${productionData.id}_final.mp4`);-+// Use AI Video Generator to create the final video- await this.aiVideoGenerator.generateVideo(+ const producedPath = await this.aiVideoGenerator.generateVideo(productionData.script,productionData.assets.video.visualAssets || [],productionData.assets.audio.path,finalVideoPath);-++ // The generator falls back to a placeholder .info file when it cannot render+ if (!producedPath || path.extname(producedPath).toLowerCase() !== '.mp4') {+ return await this.simulateVideoAssembly(productionData);+ }+// Get file statsconst stats = await fs.stat(finalVideoPath);diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.jsindex 38b4e41..9a07059 100644--- a/agents/publishing-scheduling-agent.js+++ b/agents/publishing-scheduling-agent.js@@ -43,8 +43,14 @@ class PublishingSchedulingAgent {async scheduleContent(productionData) {try {+ const finalVideo = productionData.assets?.finalVideo;+ if (!finalVideo || finalVideo.simulated || path.extname(finalVideo.path || '').toLowerCase() !== '.mp4') {+ this.logger.warn(`Not scheduling ${productionData.id}: no real video file was produced (placeholder/simulated output). Fix your AI provider keys and FFmpeg, then regenerate.`);+ return null;+ }+this.logger.info(`Scheduling content: ${productionData.id}`);-+const scheduleEntry = {productionId: productionData.id,title: productionData.script.title,@@ -207,14 +213,23 @@ class PublishingSchedulingAgent {}async processPublishQueue() {- this.logger.info('Processing publish queue...');-const now = new Date();- const readyToPublish = this.publishQueue.filter(entry => {- const publishTime = new Date(entry.publishTime);- return publishTime <= now && entry.status === 'scheduled';- });-+ const scheduled = this.publishQueue+ .filter(entry => entry.status === 'scheduled')+ .sort((a, b) => new Date(a.publishTime) - new Date(b.publishTime));+ const readyToPublish = scheduled.filter(entry => new Date(entry.publishTime) <= now);++ if (readyToPublish.length === 0) {+ if (scheduled.length > 0) {+ this.logger.info(`Publish queue: ${scheduled.length} item(s) waiting, next publish at ${scheduled[0].publishTime}`);+ } else {+ this.logger.info('Publish queue is empty β nothing scheduled yet.');+ }+ return 0;+ }++ this.logger.info(`Processing publish queue: ${readyToPublish.length} item(s) ready to publish...`);+for (const entry of readyToPublish) {try {await this.publishContent(entry.productionId);diff --git a/index.js b/index.jsindex b4092cb..fe00824 100644--- a/index.js+++ b/index.js@@ -47,6 +47,9 @@ class YouTubeAutomationAgent {// Initialize agentsthis.logger.info('Initializing agents...');await this.initializeAgents();++ // Show which pipeline stages will run for real vs. be simulated+ await this.logCapabilitySummary();// Setup API endpointsthis.setupAPI();@@ -84,6 +87,43 @@ class YouTubeAutomationAgent {}}+ async logCapabilitySummary() {+ const { checkFFmpeg, ffmpegInstallHint } = require('./utils/ffmpeg');+ const creds = this.credentials.credentials || {};++ const hasText = this.credentials.hasAITextProvider();+ const hasImages = Boolean(creds.openai?.apiKey || process.env.OPENAI_API_KEY);+ const hasTTS = Boolean(+ creds.openai?.apiKey || process.env.OPENAI_API_KEY ||+ creds.elevenLabs?.apiKey || process.env.ELEVENLABS_API_KEY ||+ creds.azureSpeech?.subscriptionKey || process.env.AZURE_SPEECH_KEY+ );+ const hasFFmpeg = await checkFFmpeg();+ const hasUpload = Boolean(creds.youtube && this.credentials.tokens?.youtube);++ const capabilities = [+ { name: 'Script & strategy generation', ok: hasText, hint: 'configure an AI provider (npm run credentials:setup)' },+ { name: 'Image generation (visuals/thumbnails)', ok: hasImages, hint: 'requires an OpenAI API key β otherwise gradient slides are used' },+ { name: 'Voice narration (TTS)', ok: hasTTS, hint: 'configure OpenAI, ElevenLabs, or Azure Speech β otherwise videos are silent' },+ { name: 'Video assembly (FFmpeg)', ok: hasFFmpeg, hint: ffmpegInstallHint() },+ { name: 'YouTube upload', ok: hasUpload, hint: 'run: npm run credentials:setup' }+ ];++ console.log(chalk.cyan('\nπ Capability check:'));+ for (const cap of capabilities) {+ if (cap.ok) {+ console.log(chalk.green(` β ${cap.name}`));+ } else {+ console.log(chalk.yellow(` β ${cap.name} β ${cap.hint}`));+ }+ }++ if (!hasFFmpeg) {+ this.logger.warn('FFmpeg is missing: no .mp4 files can be produced until it is installed.');+ }+ console.log('');+ }+requireAPIKey() {return (req, res, next) => {if (!process.env.API_KEY) {@@ -247,15 +287,22 @@ class YouTubeAutomationAgent {seo: seoData});this.logger.info('Production processing complete');-+// Step 6: Save to databaseconst contentId = await this.db.saveProductionData(productionData);this.logger.info(`Content saved with ID: ${contentId}`);-++ // Step 7: Add to the publish queue (skipped automatically for simulated output)+ const scheduleEntry = await this.agents.publishing.scheduleContent(productionData);+ if (scheduleEntry) {+ this.logger.info(`Content queued for publishing at ${scheduleEntry.publishTime}`);+ }+return {contentId,title: script.title,- scheduledFor: productionData.scheduledPublishTime+ status: productionData.status,+ scheduledFor: scheduleEntry ? scheduleEntry.publishTime : null};}diff --git a/package-lock.json b/package-lock.jsonindex 0cacee1..f9ea297 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "youtube-automation-agent",- "version": "2.0.0",+ "version": "2.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "youtube-automation-agent",- "version": "2.0.0",+ "version": "2.2.0","dependencies": {"@google-cloud/local-auth": "^3.0.0","@google/genai": "^2.9.0",@@ -34,6 +34,9 @@},"engines": {"node": ">=18.0.0"+ },+ "optionalDependencies": {+ "ffmpeg-static": "^5.2.0"}},"node_modules/@colors/colors": {@@ -56,6 +59,22 @@"kuler": "^2.0.0"}},+ "node_modules/@derhuerst/http-basic": {+ "version": "8.2.4",+ "resolved": "https://registry.npmjs.org/@derhuerst/http-basic/-/http-basic-8.2.4.tgz",+ "integrity": "sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "caseless": "^0.12.0",+ "concat-stream": "^2.0.0",+ "http-response-object": "^3.0.1",+ "parse-cache-control": "^1.0.1"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },"node_modules/@emnapi/runtime": {"version": "1.11.1","resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",@@ -1472,6 +1491,13 @@"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==","license": "BSD-3-Clause"},+ "node_modules/buffer-from": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",+ "license": "MIT",+ "optional": true+ },"node_modules/bytes": {"version": "3.1.2","resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",@@ -1762,6 +1788,22 @@"devOptional": true,"license": "MIT"},+ "node_modules/concat-stream": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",+ "engines": [+ "node >= 6.0"+ ],+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "buffer-from": "^1.0.0",+ "inherits": "^2.0.3",+ "readable-stream": "^3.0.2",+ "typedarray": "^0.0.6"+ }+ },"node_modules/console-control-strings": {"version": "1.1.0","resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",@@ -2446,6 +2488,75 @@"node": "^12.20 || >= 14.13"}},+ "node_modules/ffmpeg-static": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/ffmpeg-static/-/ffmpeg-static-5.3.0.tgz",+ "integrity": "sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==",+ "hasInstallScript": true,+ "license": "GPL-3.0-or-later",+ "optional": true,+ "dependencies": {+ "@derhuerst/http-basic": "^8.2.0",+ "env-paths": "^2.2.0",+ "https-proxy-agent": "^5.0.0",+ "progress": "^2.0.3"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/ffmpeg-static/node_modules/agent-base": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "debug": "4"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },+ "node_modules/ffmpeg-static/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/ffmpeg-static/node_modules/https-proxy-agent": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "agent-base": "6",+ "debug": "4"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/ffmpeg-static/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT",+ "optional": true+ },"node_modules/figures": {"version": "3.2.0","resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz",@@ -3287,6 +3398,23 @@"license": "MIT","optional": true},+ "node_modules/http-response-object": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/http-response-object/-/http-response-object-3.0.2.tgz",+ "integrity": "sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@types/node": "^10.0.3"+ }+ },+ "node_modules/http-response-object/node_modules/@types/node": {+ "version": "10.17.60",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz",+ "integrity": "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==",+ "license": "MIT",+ "optional": true+ },"node_modules/https-proxy-agent": {"version": "7.0.6","resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",@@ -4711,6 +4839,12 @@"node": ">=6"}},+ "node_modules/parse-cache-control": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/parse-cache-control/-/parse-cache-control-1.0.1.tgz",+ "integrity": "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==",+ "optional": true+ },"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",@@ -4889,6 +5023,16 @@"node": ">= 0.6.0"}},+ "node_modules/progress": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=0.4.0"+ }+ },"node_modules/promise-inflight": {"version": "1.0.1","resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz",@@ -5916,6 +6060,13 @@"node": ">= 0.6"}},+ "node_modules/typedarray": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",+ "license": "MIT",+ "optional": true+ },"node_modules/undefsafe": {"version": "2.0.5","resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",diff --git a/package.json b/package.jsonindex 299844c..b080d02 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "youtube-automation-agent",- "version": "2.1.0",+ "version": "2.2.0","description": "Fully automated YouTube channel management system with specialized AI agents","main": "index.js","scripts": {@@ -38,6 +38,9 @@"winston": "^3.11.0","sharp": "^0.33.0"},+ "optionalDependencies": {+ "ffmpeg-static": "^5.2.0"+ },"devDependencies": {"nodemon": "^3.0.2","eslint": "9.39.4",diff --git a/schedules/daily-automation.js b/schedules/daily-automation.jsindex ffc12c1..f74fa0a 100644--- a/schedules/daily-automation.js+++ b/schedules/daily-automation.js@@ -125,9 +125,13 @@ class DailyAutomation {});this.logger.info(`Production completed: ${productionData.id}`);- // Schedule for publishing- await this.agents.publishing.scheduleContent(productionData);- this.logger.info('Content scheduled for publishing');+ // Schedule for publishing (returns null when only placeholder assets were produced)+ const scheduleEntry = await this.agents.publishing.scheduleContent(productionData);+ if (scheduleEntry) {+ this.logger.info('Content scheduled for publishing');+ } else {+ this.logger.warn('Content was NOT scheduled β production produced placeholder assets. See warnings above.');+ }timer.end();this.logger.success('Daily content generation completed successfully');diff --git a/setup.js b/setup.jsindex e44d919..2d43ed1 100644--- a/setup.js+++ b/setup.js@@ -219,12 +219,13 @@ node index.js`;async validateSetup() {console.log(chalk.cyan('\nπ Validating setup...'));-+const validation = {directories: true,database: false,credentials: false,- environment: false+ environment: false,+ ffmpeg: false};// Check directories@@ -255,6 +256,10 @@ node index.js`;validation.environment = false;}+ // Check FFmpeg (needed for video assembly)+ const { checkFFmpeg, ffmpegInstallHint } = require('./utils/ffmpeg');+ validation.ffmpeg = await checkFFmpeg();+// Display validation resultsObject.entries(validation).forEach(([component, valid]) => {const icon = valid ? 'β ' : 'β';@@ -262,13 +267,24 @@ node index.js`;console.log(color(` ${icon} ${component}`));});- const allValid = Object.values(validation).every(Boolean);-- if (!allValid) {+ // Only broken infrastructure is fatal β missing credentials/FFmpeg can be fixed later+ if (!validation.directories || !validation.database || !validation.environment) {throw new Error('Setup validation failed. Please check the errors above.');}- console.log(chalk.green('β All validations passed'));+ if (!validation.credentials) {+ console.log(chalk.yellow('\nβ οΈ Credentials are incomplete. Finish them any time with: npm run credentials:setup'));+ }++ if (!validation.ffmpeg) {+ console.log(chalk.yellow(`\nβ οΈ ${ffmpegInstallHint()}`));+ }++ if (validation.credentials && validation.ffmpeg) {+ console.log(chalk.green('β All validations passed'));+ } else {+ console.log(chalk.yellow('β Core setup complete (with warnings above)'));+ }}async createSampleContent() {diff --git a/test.js b/test.jsindex ce5cf6d..2c73f46 100644--- a/test.js+++ b/test.js@@ -20,6 +20,9 @@ class SystemTest {{ name: 'Automation Events Table', test: () => this.testAutomationEventsTable() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },+ { name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },+ { name: 'Placeholder Scheduling Guard', test: () => this.testPlaceholderSchedulingGuard() },+ { name: 'FFmpeg Resolution', test: () => this.testFFmpegResolution() },{ name: 'Logger System', test: () => this.testLogger() },{ name: 'Directory Structure', test: () => this.testDirectories() },{ name: 'Agent Loading', test: () => this.testAgentLoading() },@@ -248,6 +251,113 @@ class SystemTest {this.logger.info('Publishing safety test completed successfully');}++ async testCredentialValidation() {+ const { PROVIDERS } = require('./utils/ai-text-service');+ const manager = new CredentialManager();++ // Isolate the test from any API keys set in the environment+ const envKeys = [...Object.values(PROVIDERS).map(p => p.envKey), 'GEMINI_API_KEY'];+ const savedEnv = {};+ for (const key of envKeys) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }++ try {+ manager.credentials = { youtube: { client_id: 'x' }, gemini: { apiKey: 'gm-test' } };+ if (manager.getMissingCredentials().length !== 0) {+ throw new Error('Gemini-only configuration was incorrectly reported as missing credentials');+ }++ manager.credentials = { youtube: { client_id: 'x' }, aiProvider: { provider: 'openrouter', apiKey: 'sk-or-test' } };+ if (manager.getMissingCredentials().length !== 0) {+ throw new Error('OpenRouter configuration was incorrectly reported as missing credentials');+ }++ manager.credentials = { youtube: { client_id: 'x' } };+ const missingProvider = manager.getMissingCredentials();+ if (missingProvider.length !== 1 || !/AI provider/.test(missingProvider[0])) {+ throw new Error('Missing AI provider was not detected');+ }++ manager.credentials = { openai: { apiKey: 'sk-test' } };+ const missingYouTube = manager.getMissingCredentials();+ if (missingYouTube.length !== 1 || missingYouTube[0] !== 'youtube') {+ throw new Error('Missing YouTube credentials were not detected');+ }+ } finally {+ for (const key of envKeys) {+ if (savedEnv[key] === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = savedEnv[key];+ }+ }+ }++ this.logger.info('Credential validation test completed successfully');+ }++ async testPlaceholderSchedulingGuard() {+ const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-agent');+ const agent = new PublishingSchedulingAgent({+ saveScheduleEntry: async () => {}+ }, {});++ const simulated = await agent.scheduleContent({+ id: 'prod-simulated',+ script: { title: 'Simulated' },+ assets: { finalVideo: { path: 'video.mp4.assembly.json', simulated: true } }+ });+ if (simulated !== null) {+ throw new Error('Simulated production was scheduled for publishing');+ }++ const missingVideo = await agent.scheduleContent({+ id: 'prod-missing',+ script: { title: 'Missing' },+ assets: {}+ });+ if (missingVideo !== null) {+ throw new Error('Production without a final video was scheduled for publishing');+ }++ const real = await agent.scheduleContent({+ id: 'prod-real',+ script: { title: 'Real' },+ priority: 50,+ scheduledPublishTime: new Date().toISOString(),+ assets: { finalVideo: { path: 'video.mp4' }, thumbnail: {}, captions: {} },+ seo: {}+ });+ if (!real || agent.publishQueue.length !== 1) {+ throw new Error('Real production was not scheduled for publishing');+ }++ this.logger.info('Placeholder scheduling guard test completed successfully');+ }++ async testFFmpegResolution() {+ const { getFFmpegPath, checkFFmpeg, ffmpegInstallHint } = require('./utils/ffmpeg');++ const ffmpegPath = getFFmpegPath();+ if (typeof ffmpegPath !== 'string' || ffmpegPath.length === 0) {+ throw new Error('getFFmpegPath did not return a usable path');+ }++ const available = await checkFFmpeg();+ if (typeof available !== 'boolean') {+ throw new Error('checkFFmpeg did not return a boolean');+ }++ if (!/FFmpeg/i.test(ffmpegInstallHint())) {+ throw new Error('ffmpegInstallHint did not return install guidance');+ }++ this.logger.info(`FFmpeg resolution test completed (binary: ${ffmpegPath}, available: ${available})`);+ }+async testLogger() {const testLogger = new Logger('TestLogger');diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.jsindex be6ca8c..b1c3495 100644--- a/utils/ai-video-generator.js+++ b/utils/ai-video-generator.js@@ -1,13 +1,11 @@const OpenAI = require('openai');const Replicate = require('replicate');-const { exec } = require('child_process');-const { promisify } = require('util');const fs = require('fs').promises;const path = require('path');+const { pathToFileURL } = require('url');const axios = require('axios');const { Logger } = require('./logger');--const execAsync = promisify(exec);+const { runFFmpeg, checkFFmpeg, ffmpegInstallHint } = require('./ffmpeg');class AIVideoGenerator {constructor(credentials) {@@ -225,13 +223,18 @@ class AIVideoGenerator {async generateSlideshowVideo(script, visualAssets, audioPath, outputPath) {this.logger.info('Creating slideshow video...');-++ if (!(await checkFFmpeg())) {+ throw new Error(ffmpegInstallHint());+ }+const { chromium } = require('playwright');const browser = await chromium.launch();const page = await browser.newPage();- // Create HTML for slideshow- const slideshowHtml = this.createSlideshowHTML(script, visualAssets);+ // Create HTML for slideshow (only real image files can be embedded)+ const imageAssets = await this.filterImageAssets(visualAssets);+ const slideshowHtml = this.createSlideshowHTML(script, imageAssets);// Set page contentawait page.setContent(slideshowHtml);@@ -270,8 +273,14 @@ class AIVideoGenerator {await browser.close();// Convert frames to video using FFmpeg- const ffmpegCommand = `ffmpeg -framerate 30 -i "${framesDir}/frame_%06d.png" -c:v libx264 -pix_fmt yuv420p "${videoPath}"`;- await execAsync(ffmpegCommand);+ await runFFmpeg([+ '-y',+ '-framerate', '30',+ '-i', path.join(framesDir, 'frame_%06d.png'),+ '-c:v', 'libx264',+ '-pix_fmt', 'yuv420p',+ videoPath+ ]);// Add audioawait this.addAudioToVideo(videoPath, audioPath, outputPath);@@ -282,6 +291,26 @@ class AIVideoGenerator {return outputPath;}+ async filterImageAssets(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(pathToFileURL(asset).href);+ } catch (error) {+ // Skip missing files+ }+ }++ return images;+ }+createSlideshowHTML(script, visualAssets) {return `<!DOCTYPE html>@@ -503,9 +532,42 @@ class AIVideoGenerator {}async addAudioToVideo(videoPath, audioPath, outputPath) {- const command = `ffmpeg -i "${videoPath}" -i "${audioPath}" -c:v copy -c:a aac -shortest "${outputPath}"`;- await execAsync(command);+ const hasRealAudio = await this.isUsableAudioFile(audioPath);++ if (!hasRealAudio) {+ this.logger.warn('No narration audio available β producing silent video. Configure OpenAI, ElevenLabs, or Azure Speech for narration.');+ if (videoPath !== outputPath) {+ await fs.copyFile(videoPath, outputPath);+ }+ return outputPath;+ }++ // FFmpeg cannot write to its own input, so mux to a temp file when paths collide+ const muxPath = outputPath === videoPath+ ? outputPath.replace(/\.mp4$/i, '_muxed.mp4')+ : outputPath;++ await runFFmpeg(['-y', '-i', videoPath, '-i', audioPath, '-c:v', 'copy', '-c:a', 'aac', '-shortest', muxPath]);++ if (muxPath !== outputPath) {+ await fs.rename(muxPath, outputPath);+ }+this.logger.info('Audio added to video successfully');+ return outputPath;+ }++ async isUsableAudioFile(audioPath) {+ if (typeof audioPath !== 'string' || audioPath.endsWith('.info')) {+ return false;+ }++ try {+ const stats = await fs.stat(audioPath);+ return stats.isFile() && stats.size > 0;+ } catch (error) {+ return false;+ }}async downloadVideo(url, outputPath) {diff --git a/utils/credential-manager.js b/utils/credential-manager.jsindex 4da3c3c..9351961 100644--- a/utils/credential-manager.js+++ b/utils/credential-manager.js@@ -518,6 +518,31 @@ class CredentialManager {process.env[key] = String(value);}// Validation methods+ hasAITextProvider() {+ if (this.credentials.openai?.apiKey || this.credentials.gemini?.apiKey || this.credentials.aiProvider?.apiKey) {+ return true;+ }++ // Environment-variable based configuration (see utils/ai-text-service.js)+ const { PROVIDERS } = require('./ai-text-service');+ const envKeys = [...Object.values(PROVIDERS).map(p => p.envKey), 'GEMINI_API_KEY'];+ return envKeys.some(key => process.env[key]);+ }++ getMissingCredentials() {+ const missing = [];++ if (!this.credentials.youtube) {+ missing.push('youtube');+ }++ if (!this.hasAITextProvider()) {+ missing.push('an AI provider (OpenAI, Gemini, OpenRouter, Kimi, MiMo, or GLM)');+ }++ return missing;+ }+async validateAll() {try {await this.loadCredentials();@@ -526,17 +551,11 @@ class CredentialManager {// Files might not exist yet}- const requiredCredentials = ['youtube', 'openai'];- const missing = [];-- for (const service of requiredCredentials) {- if (!this.credentials[service]) {- missing.push(service);- }- }+ const missing = this.getMissingCredentials();if (missing.length > 0) {console.log(chalk.yellow(`\nβ οΈ Missing credentials for: ${missing.join(', ')}`));+ console.log(chalk.gray('Any one AI provider is enough β run: npm run credentials:setup'));return false;}diff --git a/utils/ffmpeg.js b/utils/ffmpeg.jsnew file mode 100644index 0000000..48ab2c5--- /dev/null+++ b/utils/ffmpeg.js@@ -0,0 +1,58 @@+const { execFile } = require('child_process');+const { promisify } = require('util');++const execFileAsync = promisify(execFile);++let cachedPath = null;++/**+ * Resolve the FFmpeg binary to use, in order of preference:+ * 1. FFMPEG_PATH environment variable+ * 2. Bundled binary from the optional ffmpeg-static package+ * 3. `ffmpeg` on the system PATH+ */+function getFFmpegPath() {+ if (cachedPath) {+ return cachedPath;+ }++ if (process.env.FFMPEG_PATH) {+ cachedPath = process.env.FFMPEG_PATH;+ return cachedPath;+ }++ try {+ cachedPath = require('ffmpeg-static');+ } catch (error) {+ cachedPath = null;+ }++ cachedPath = cachedPath || 'ffmpeg';+ return cachedPath;+}++async function checkFFmpeg() {+ try {+ await execFileAsync(getFFmpegPath(), ['-version']);+ return true;+ } catch (error) {+ return false;+ }+}++async function runFFmpeg(args) {+ return execFileAsync(getFFmpegPath(), args, { maxBuffer: 32 * 1024 * 1024 });+}++function ffmpegInstallHint() {+ const hints = {+ win32: 'winget install Gyan.FFmpeg (then restart your terminal)',+ darwin: 'brew install ffmpeg',+ linux: 'sudo apt install ffmpeg (or your distro equivalent)'+ };++ const platformHint = hints[process.platform] || 'https://ffmpeg.org/download.html';+ return `FFmpeg not found. Install it with: ${platformHint} β or run "npm install" again to fetch the bundled ffmpeg-static binary, or set FFMPEG_PATH to your ffmpeg executable.`;+}++module.exports = { getFFmpegPath, checkFFmpeg, runFFmpeg, ffmpegInstallHint };