π¬ 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
require('dotenv').config();
const inquirer = require('inquirer');
const chalk = require('chalk');
const fs = require('fs').promises;
const path = require('path');
const { exec } = require('child_process');
const { CredentialManager } = require('./utils/credential-manager');
const {
AITextService,
PROVIDERS,
GEMINI_MODELS,
GEMINI_DEFAULT_MODEL
} = 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 place
const AI_PROVIDER_GUIDE = {
gemini: {
label: 'Google Gemini β free text/TTS tiers; paid AI images',
keyUrl: 'https://aistudio.google.com/apikey',
keyHint: 'starts with "AIza"',
instructions: [
'Sign in with any Google account',
'Click "Create API key"',
'Copy the key it shows you'
],
models: [...GEMINI_MODELS],
defaultModel: GEMINI_DEFAULT_MODEL,
covers: 'scripts + voice narration on supported free tiers; AI images require paid access',
save(credentials, apiKey, model) {
credentials.gemini = { apiKey, model };
},
validationCreds: (apiKey, model) => ({ gemini: { apiKey, model } })
},
openai: {
label: 'OpenAI β paid text, image, and voice models',
keyUrl: 'https://platform.openai.com/api-keys',
keyHint: 'starts with "sk-"',
instructions: [
'Sign in (or create an account) and add billing',
'Click "Create new secret key"',
'Copy the key β it is shown only once'
],
models: [...PROVIDERS.openai.models],
defaultModel: PROVIDERS.openai.defaultModel,
covers: 'scripts + images + voice narration',
save(credentials, apiKey, model) {
credentials.openai = { apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'openai', apiKey, model } })
},
openrouter: {
label: 'OpenRouter β one key, 400+ models (pay per use)',
keyUrl: 'https://openrouter.ai/keys',
keyHint: 'starts with "sk-or-"',
instructions: [
'Sign in and add a few dollars of credit',
'Create a key and copy it'
],
models: [...PROVIDERS.openrouter.models],
defaultModel: 'google/gemini-3.8-flash',
covers: 'scripts only (add a Gemini or OpenAI key for images/voice)',
save(credentials, apiKey, model) {
credentials.aiProvider = { provider: 'openrouter', apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'openrouter', apiKey, model } })
},
kimi: {
label: 'Kimi (Moonshot AI) β K3 and K2 family text models',
keyUrl: 'https://platform.kimi.ai',
keyHint: 'from the Moonshot platform console',
instructions: ['Create an account', 'Open the API keys page and create a key'],
models: [...PROVIDERS.kimi.models],
defaultModel: PROVIDERS.kimi.defaultModel,
covers: 'scripts only (add a Gemini or OpenAI key for images/voice)',
save(credentials, apiKey, model) {
credentials.aiProvider = { provider: 'kimi', apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'kimi', apiKey, model } })
},
mimo: {
label: 'MiMo (Xiaomi) β competitive pricing',
keyUrl: 'https://mimo.mi.com',
keyHint: 'from the MiMo console',
instructions: ['Create an account', 'Create an API key in the console'],
models: [...PROVIDERS.mimo.models],
defaultModel: PROVIDERS.mimo.defaultModel,
covers: 'scripts only (add a Gemini or OpenAI key for images/voice)',
save(credentials, apiKey, model) {
credentials.aiProvider = { provider: 'mimo', apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'mimo', apiKey, model } })
},
glm: {
label: 'GLM (Zhipu AI) β GLM-5 family text models',
keyUrl: 'https://z.ai',
keyHint: 'from the Z.ai console',
instructions: ['Create an account', 'Create an API key in the console'],
models: [...PROVIDERS.glm.models],
defaultModel: PROVIDERS.glm.defaultModel,
covers: 'scripts only (add a Gemini or OpenAI key for images/voice)',
save(credentials, apiKey, model) {
credentials.aiProvider = { provider: 'glm', apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'glm', apiKey, model } })
},
deepseek: {
label: 'DeepSeek β low-cost V4.1 Flash and V4 Pro text models',
keyUrl: 'https://platform.deepseek.com/api_keys',
keyHint: 'starts with "sk-"',
instructions: ['Create an account and add credit', 'Create an API key and copy it'],
models: [...PROVIDERS.deepseek.models],
defaultModel: PROVIDERS.deepseek.defaultModel,
covers: 'scripts only (add a Gemini or OpenAI key for images/voice)',
save(credentials, apiKey, model) {
credentials.aiProvider = { provider: 'deepseek', apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'deepseek', apiKey, model } })
},
minimax: {
label: 'MiniMax β M3 family text models',
keyUrl: 'https://platform.minimax.io/user-center/basic-information/interface-key',
keyHint: 'from the MiniMax platform console',
instructions: ['Create an account', 'Open Interface Key and create a key'],
models: [...PROVIDERS.minimax.models],
defaultModel: PROVIDERS.minimax.defaultModel,
covers: 'scripts only (add a Gemini or OpenAI key for images/voice)',
save(credentials, apiKey, model) {
credentials.aiProvider = { provider: 'minimax', apiKey, model };
},
validationCreds: (apiKey, model) => ({ aiProvider: { provider: 'minimax', apiKey, model } })
}
};
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 = 6;
}
header(step, title) {
console.log(chalk.cyan.bold(`\nβββ Step ${step} of ${this.totalSteps}: ${title} `.padEnd(62, 'β')));
}
openBrowser(url) {
const commands = {
win32: `start "" "${url}"`,
darwin: `open "${url}"`,
linux: `xdg-open "${url}"`
};
const command = commands[process.platform];
if (command) {
exec(command, () => {}); // best effort β the URL is printed either way
}
}
async run() {
console.log(chalk.cyan.bold('\nπ§ YouTube Automation Agent β Guided Walkthrough'));
console.log(chalk.gray('β'.repeat(60)));
console.log(chalk.white('This takes about 10β15 minutes and explains everything as you go.'));
console.log(chalk.white('Every step can be skipped and finished later β your progress is'));
console.log(chalk.white('saved after each step. Re-run any time with: ') + chalk.cyan('npm run walkthrough'));
await this.cm.loadCredentials();
await this.cm.loadTokens();
try {
await this.stepSystemCheck();
await this.stepAIProvider();
await this.stepVideoProvider();
await this.stepYouTube();
await this.stepChannelBasics();
await this.stepFinish();
} catch (error) {
if (error && (error.isTtyError || /User force closed/i.test(error.message || ''))) {
console.log(chalk.yellow('\n\nπ No problem β everything you completed is saved.'));
console.log(chalk.cyan('Pick up where you left off with: npm run walkthrough'));
return;
}
throw error;
}
}
// ββ Step 1: environment ββββββββββββββββββββββββββββββββββββββββββββββββ
async stepSystemCheck() {
this.header(1, 'Checking your system');
const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
console.log(nodeMajor >= 18
? chalk.green(` β Node.js ${process.versions.node}`)
: chalk.red(` β Node.js ${process.versions.node} β version 18+ is required (https://nodejs.org)`));
const ffmpegOk = await checkFFmpeg();
console.log(ffmpegOk
? chalk.green(' β FFmpeg (video assembly)')
: chalk.yellow(` β FFmpeg β ${ffmpegInstallHint()}`));
const directories = [
'config', 'logs', 'data', 'data/production', 'data/assets', 'data/videos',
'data/audio', 'data/scripts', 'data/captions', 'temp/processing', 'uploads/thumbnails'
];
for (const dir of directories) {
await fs.mkdir(path.join(__dirname, dir), { recursive: true });
}
console.log(chalk.green(' β Project folders'));
const db = new Database();
await db.initialize();
await db.close();
console.log(chalk.green(' β Database'));
// Create .env from a minimal template if the user doesn't have one yet
try {
await fs.access(path.join(__dirname, '.env'));
console.log(chalk.green(' β .env file'));
} catch (error) {
await fs.writeFile(path.join(__dirname, '.env'), [
'# Created by the guided walkthrough β see .env.example for every option',
'NODE_ENV=production',
'PORT=3456',
'LOG_LEVEL=info',
'DEFAULT_PRIVACY_STATUS=private',
''
].join('\n'));
console.log(chalk.green(' β .env file created'));
}
}
// ββ Step 2: AI provider ββββββββββββββββββββββββββββββββββββββββββββββββ
async stepAIProvider() {
this.header(2, 'Your AI provider (writes scripts, makes images & narration)');
if (this.cm.hasAITextProvider()) {
const { redo } = await inquirer.prompt([{
type: 'confirm',
name: 'redo',
message: 'An AI provider is already configured. Set up a different one?',
default: false
}]);
if (!redo) return;
} else {
console.log(chalk.white('The agent needs one AI service. If you don\'t want to spend money,'));
console.log(chalk.white('Google Gemini offers free tiers for supported text and TTS usage.'));
console.log(chalk.white('AI image generation requires paid access; gradient visuals are the fallback.'));
}
const { providerId } = await inquirer.prompt([{
type: 'list',
name: 'providerId',
message: 'Which AI provider do you want to use?',
choices: Object.entries(AI_PROVIDER_GUIDE).map(([value, guide]) => ({ name: guide.label, value }))
}]);
const guide = AI_PROVIDER_GUIDE[providerId];
console.log(chalk.cyan(`\nHow to get your key (${guide.keyHint}):`));
guide.instructions.forEach((line, i) => console.log(chalk.white(` ${i + 1}. ${line}`)));
console.log(chalk.white(` β ${chalk.blue(guide.keyUrl)} (opening in your browser)`));
console.log(chalk.gray(` This key covers: ${guide.covers}`));
this.openBrowser(guide.keyUrl);
while (true) {
const { apiKey } = await inquirer.prompt([{
type: 'password',
name: 'apiKey',
mask: '*',
message: `Paste your ${providerId} API key (or leave empty to skip this step):`
}]);
if (!apiKey.trim()) {
console.log(chalk.yellow(' Skipped β configure later with: npm run walkthrough'));
return;
}
const { model } = await inquirer.prompt([{
type: 'list',
name: 'model',
message: 'Model to use:',
choices: guide.models,
default: guide.defaultModel
}]);
console.log(chalk.gray(' Testing your key with a tiny request...'));
const ok = await this.validateAIKey(guide, apiKey.trim(), model);
if (ok) {
guide.save(this.cm.credentials, apiKey.trim(), model);
await this.cm.saveCredentials();
console.log(chalk.green(' β Key works! Saved.'));
return;
}
const { retry } = await inquirer.prompt([{
type: 'confirm',
name: 'retry',
message: 'That key didn\'t work. Try pasting it again?',
default: true
}]);
if (!retry) {
console.log(chalk.yellow(' Skipped β configure later with: npm run walkthrough'));
return;
}
}
}
async validateAIKey(guide, apiKey, model) {
// Temporarily clear provider env keys so the test hits exactly the pasted key
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 {
const service = new AITextService(guide.validationCreds(apiKey, model));
const reply = await service.generateText('Reply with the single word OK.', { maxTokens: 256, temperature: 0 });
return typeof reply === 'string' && reply.length > 0;
} catch (error) {
console.log(chalk.red(` β ${error.message}`));
return false;
} finally {
for (const key of envKeys) {
if (savedEnv[key] === undefined) {
delete process.env[key];
} else {
process.env[key] = savedEnv[key];
}
}
}
}
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 YouTube Automation Agent 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(4, 'Connecting your YouTube channel');
if (this.cm.credentials.youtube && this.cm.tokens.youtube) {
const { redo } = await inquirer.prompt([{
type: 'confirm',
name: 'redo',
message: 'YouTube is already connected. Reconnect?',
default: false
}]);
if (!redo) return;
} else {
console.log(chalk.white('This lets the agent upload to your channel. It\'s the fiddliest step,'));
console.log(chalk.white('but it\'s free and you only do it once. You can also skip it β videos'));
console.log(chalk.white('will still be generated locally in data/videos/.'));
}
const { action } = await inquirer.prompt([{
type: 'list',
name: 'action',
message: 'How do you want to proceed?',
choices: [
{ name: 'π§ Walk me through creating the Google credentials (~5 min)', value: 'guided' },
{ name: 'β‘ I already have a Client ID and Client Secret', value: 'have' },
{ name: 'βοΈ Skip for now', value: 'skip' }
]
}]);
if (action === 'skip') {
console.log(chalk.yellow(' Skipped β connect later with: npm run walkthrough'));
return;
}
if (action === 'guided') {
console.log(chalk.cyan('\nDo this in the browser tab that just opened:'));
console.log(chalk.white(' 1. Create a project (any name) β top bar β "New project"'));
console.log(chalk.white(' 2. Menu β "APIs & Services" β "Library" β search "YouTube Data API v3" β Enable'));
console.log(chalk.white(' 3. "APIs & Services" β "OAuth consent screen" β External β fill the 3 required'));
console.log(chalk.white(' fields β add YOUR OWN email under "Test users"'));
console.log(chalk.white(' 4. "APIs & Services" β "Credentials" β "Create credentials" β "OAuth client ID"'));
console.log(chalk.white(' β Application type: "Desktop app"'));
console.log(chalk.white(' 5. Copy the Client ID and Client Secret it shows you'));
console.log(chalk.white(` β ${chalk.blue('https://console.cloud.google.com/')}`));
this.openBrowser('https://console.cloud.google.com/');
}
const answers = await inquirer.prompt([
{
type: 'input',
name: 'clientId',
message: 'Paste your Client ID (ends in .apps.googleusercontent.com, empty to skip):'
},
{
type: 'password',
name: 'clientSecret',
mask: '*',
message: 'Paste your Client Secret:',
when: (a) => a.clientId.trim().length > 0
}
]);
if (!answers.clientId.trim()) {
console.log(chalk.yellow(' Skipped β connect later with: npm run walkthrough'));
return;
}
this.cm.credentials.youtube = {
client_id: answers.clientId.trim(),
client_secret: (answers.clientSecret || '').trim(),
redirect_uris: ['http://127.0.0.1']
};
await this.cm.saveCredentials();
console.log(chalk.cyan('\nNow let\'s sign in. A Google page will open β approve the access.'));
console.log(chalk.gray('(You may see "Google hasn\'t verified this app" β click "Continue".'));
console.log(chalk.gray(' That\'s expected: the "app" is your own Cloud project.)'));
try {
const { ModernAuth } = require('./modern-auth');
const auth = new ModernAuth();
await auth.authenticate();
await this.cm.loadTokens();
console.log(chalk.gray(' Checking which channel this is...'));
await auth.testAuthentication();
} catch (error) {
console.log(chalk.red(` β Sign-in failed: ${error.message}`));
console.log(chalk.yellow(' Your Client ID/Secret are saved β retry with: npm run walkthrough'));
}
}
// ββ Step 5: channel basics βββββββββββββββββββββββββββββββββββββββββββββ
async stepChannelBasics() {
this.header(5, 'Channel & content basics');
const existing = this.cm.credentials.channel || {};
const answers = await inquirer.prompt([
{
type: 'input',
name: 'channelName',
message: 'What\'s your channel called?',
default: existing.channelName || 'My Automated Channel'
},
{
type: 'list',
name: 'postingFrequency',
message: 'How often should it post?',
choices: [
{ name: 'Daily', value: 'daily' },
{ name: 'Every other day', value: 'every-2-days' },
{ name: '3 times per week', value: '3-per-week' },
{ name: 'Weekly', value: 'weekly' }
],
default: this.cm.credentials.content?.postingFrequency || 'daily'
},
{
type: 'input',
name: 'targetAudience',
message: 'Describe your target audience in one line:',
default: this.cm.credentials.content?.targetAudience || 'General audience interested in educational content'
}
]);
this.cm.credentials.channel = {
...existing,
channelName: answers.channelName,
channelDescription: existing.channelDescription || 'Automated content channel',
defaultCategory: existing.defaultCategory || '22',
defaultPrivacy: existing.defaultPrivacy || 'private'
};
this.cm.credentials.content = {
contentTypes: this.cm.credentials.content?.contentTypes || ['tutorial', 'explainer', 'list'],
competitorChannels: this.cm.credentials.content?.competitorChannels || [],
targetAudience: answers.targetAudience,
postingFrequency: answers.postingFrequency,
preferredPostTime: this.cm.credentials.content?.preferredPostTime || '14:00'
};
await this.cm.saveCredentials();
console.log(chalk.green(' β Saved.') + chalk.gray(' Uploads default to PRIVATE so you can review them first β'));
console.log(chalk.gray(' set DEFAULT_PRIVACY_STATUS=public in .env when you\'re confident.'));
}
// ββ Step 6: summary ββββββββββββββββββββββββββββββββββββββββββββββββββββ
async stepFinish() {
this.header(6, 'All set β here\'s what your pipeline can do');
await this.cm.loadCredentials();
await this.cm.loadTokens();
const creds = this.cm.credentials;
const hasText = this.cm.hasAITextProvider();
const hasGemini = Boolean(creds.gemini?.apiKey || process.env.GEMINI_API_KEY);
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: 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) {
console.log(row.ok
? chalk.green(` β ${row.name}`)
: chalk.yellow(` β ${row.name} β re-run the walkthrough: ${row.fix}`));
}
console.log(chalk.cyan.bold('\nπ Next steps:'));
console.log(chalk.white(' 1. npm start'));
console.log(chalk.white(' 2. Open http://localhost:3456 and press "Generate Content"'));
console.log(chalk.white(' (or wait β it generates automatically every day at 6 AM)'));
console.log(chalk.white(' 3. Finished videos land in data/videos/ and upload as PRIVATE'));
console.log(chalk.gray('\nChanged your mind about anything? Just run: npm run walkthrough'));
}
}
if (require.main === module) {
new SetupWalkthrough().run().catch(error => {
console.error(chalk.red('\nWalkthrough failed:'), error.message);
console.log(chalk.yellow('Your progress so far is saved β re-run: npm run walkthrough'));
process.exit(1);
});
}
module.exports = { SetupWalkthrough, AI_PROVIDER_GUIDE, VIDEO_PROVIDER_GUIDE };