π¬ 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
fix: resolve readiness, image-error, and local-safety issues (#68)
Haithum Abdelfattah9d197192303d
diff --git a/.env.example b/.env.exampleindex df82836..d598928 100644--- a/.env.example+++ b/.env.example@@ -68,6 +68,9 @@# Application SettingsNODE_ENV=productionPORT=3456+# The dashboard listens on this machine only by default. Use HOST=0.0.0.0 to+# reach it from other devices, and set API_KEY below when you do.+# HOST=127.0.0.1LOG_LEVEL=info# Channel Settingsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a214e1..699860b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,12 @@## Unreleased+- Fixed the readiness text probe failing on thinking Gemini models (`gemini-3.7-flash`, `gemini-3.1-pro-preview`): the probe budget now leaves room for thoughts, and a Gemini response that runs out of tokens before writing text is retried once with a larger budget (#63)+- Image generation failures now show the provider's actual error and a concrete fix (billing, invalid key, unavailable model, region) instead of a bare "failed:" line, including when `NODE_ENV=production` (#65)+- Image generation now falls back to Gemini when OpenAI image generation fails (and the other way round) instead of dropping straight to simulated visuals (#65)+- Added a whole-channel YouTube snapshot to Analytics (lifetime subscribers, views, and videos, plus 28-day views, watch hours, and subscriber change) that covers videos published outside Lumen and reports a disabled YouTube Analytics API instead of showing zeroes (#66)+- The dashboard server now listens on `127.0.0.1` by default; set `HOST=0.0.0.0` (with `API_KEY`) for network access (#66)+- Credential and OAuth token files are now written owner-only (`0600`), and FFmpeg inputs for looped provider clips are bounded to their timeline slot (#66)- Bundled the DarkzSEO-compatible content audit so the preflight no longer depends on the unpublished 1.4 Python package; external 1.4+ checkouts remain opt-in through `DARKZSEO_PATH`- Fixed regenerated narration timing, CTA metadata and template-placeholder speech leaks, configured visual-style propagation, and null manual strategy contexts- Added explicit reschedule, publish-now, and delete-schedule controls while keeping generated content when a schedule is removeddiff --git a/README.md b/README.mdindex d51f8da..4f0aa6c 100644--- a/README.md+++ b/README.md@@ -332,6 +332,7 @@ OPENAI_API_KEY=sk-...# App configNODE_ENV=productionPORT=3456+# HOST=127.0.0.1 # default: this machine only; use 0.0.0.0 for LAN access (set API_KEY too)CHANNEL_NAME=Your Channel NameTARGET_AUDIENCE=Your target audienceYOUTUBE_REGION=USdiff --git a/agents/analytics-optimization-agent.js b/agents/analytics-optimization-agent.jsindex 031398b..d53af72 100644--- a/agents/analytics-optimization-agent.js+++ b/agents/analytics-optimization-agent.js@@ -2,6 +2,27 @@ const { google } = require('googleapis');const { Logger } = require('../utils/logger');const { ChannelLearningEngine } = require('../utils/channel-learning-engine');+const CHANNEL_SNAPSHOT_CACHE_MS = 3 * 60 * 1000;++// Explains a googleapis failure in operator terms. A Google Cloud project must+// enable each API separately; OAuth consent alone is not enough.+function describeGoogleApiError(error, apiName) {+ const body = error?.response?.data?.error || {};+ const message = String(body.message || error?.message || 'Unknown error');+ const reasons = (body.errors || []).map(item => item.reason).concat(body.status || []);+ const activationUrl = (message.match(/https:\/\/console\.(?:developers|cloud)\.google\.com\/[^\s"']+/) || [])[0] || null;+ if (activationUrl || reasons.some(reason => /accessNotConfigured|SERVICE_DISABLED/i.test(reason)) || /has not been used|is disabled/i.test(message)) {+ return { reason: `${apiName} is not enabled for your Google Cloud project. Enable it, wait a minute, then refresh.`, activationUrl };+ }+ if (/insufficient.*scope/i.test(message) || reasons.some(reason => /insufficientPermissions|ACCESS_TOKEN_SCOPE_INSUFFICIENT/i.test(reason))) {+ return { reason: `YouTube was connected without ${apiName} access. Reconnect YouTube with npm run walkthrough and approve every requested permission.`, activationUrl: null };+ }+ if (/invalid_grant/i.test(message)) {+ return { reason: 'The YouTube authorization expired or was revoked. Reconnect YouTube with npm run walkthrough.', activationUrl: null };+ }+ return { reason: `${apiName} request failed: ${message.slice(0, 240)}`, activationUrl: null };+}+class AnalyticsOptimizationAgent {constructor(db, credentials) {this.db = db;@@ -769,6 +790,85 @@ class AnalyticsOptimizationAgent {};}+ // Channel-wide totals read straight from YouTube, whichever tool published+ // the videos. getRecentAnalytics only covers videos this agent analyzed, which+ // reads as "0" for an established channel. Unavailable data is reported with+ // a reason and null values, never as a zero.+ async getChannelSnapshot({ refresh = false } = {}) {+ const cached = this.channelSnapshotCache;+ if (!refresh && cached && Date.now() - cached.cachedAt < CHANNEL_SNAPSHOT_CACHE_MS) return cached.value;+ if (!this.youtube) {+ return { available: false, reason: 'Connect YouTube with npm run walkthrough to see channel statistics.' };+ }++ let channel;+ try {+ const response = await this.youtube.channels.list({ part: ['snippet', 'statistics'], mine: true });+ channel = response.data.items?.[0];+ } catch (error) {+ return { available: false, reason: describeGoogleApiError(error, 'YouTube Data API').reason };+ }+ if (!channel) {+ return { available: false, reason: 'The connected Google account does not own a YouTube channel.' };+ }++ const stats = channel.statistics || {};+ const count = value => (value === undefined || value === null ? null : Number(value));+ const value = {+ available: true,+ fetchedAt: new Date().toISOString(),+ channel: {+ id: channel.id,+ title: channel.snippet?.title || null,+ subscribers: stats.hiddenSubscriberCount ? null : count(stats.subscriberCount),+ subscribersHidden: Boolean(stats.hiddenSubscriberCount),+ views: count(stats.viewCount),+ videos: count(stats.videoCount)+ },+ recent: await this.getChannelRecentMetrics()+ };+ this.channelSnapshotCache = { cachedAt: Date.now(), value };+ return value;+ }++ async getChannelRecentMetrics() {+ // YouTube Analytics lags about two days, so the 28-day window ends two days ago.+ const day = 24 * 60 * 60 * 1000;+ const end = new Date(Date.now() - 2 * day);+ const startDate = new Date(end.getTime() - 27 * day).toISOString().split('T')[0];+ const endDate = end.toISOString().split('T')[0];+ try {+ const response = await this.youtubeAnalytics.reports.query({+ ids: 'channel==MINE',+ startDate,+ endDate,+ metrics: 'views,estimatedMinutesWatched,subscribersGained,subscribersLost'+ });+ const headers = (response.data.columnHeaders || []).map(header => header.name);+ const row = response.data.rows?.[0] || [];+ const metric = name => {+ const position = headers.indexOf(name);+ return position >= 0 ? Number(row[position] || 0) : 0;+ };+ const gained = metric('subscribersGained');+ const lost = metric('subscribersLost');+ return {+ available: true,+ startDate,+ endDate,+ views: metric('views'),+ watchHours: Math.round(metric('estimatedMinutesWatched') / 6) / 10,+ subscribersGained: gained,+ subscribersLost: lost,+ netSubscribers: gained - lost+ };+ } catch (error) {+ const { reason, activationUrl } = describeGoogleApiError(error, 'YouTube Analytics API');+ this.logger.warn(`Channel analytics unavailable: ${reason}`);+ return { available: false, startDate, endDate, reason, activationUrl };+ }+ }+async getAudienceRetention(videoId, period = null, isoDuration = null) {const endDate = period?.endDate || new Date().toISOString().split('T')[0];const startDate = period?.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];diff --git a/dashboard/app.js b/dashboard/app.jsindex f4b44d0..5bfba6d 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -321,6 +321,52 @@ function renderAnalytics(analytics, learning = {}) {renderRetention(learning.retention || {});}+async function loadChannelSnapshot(refresh = false) {+ const button = $('#channel-snapshot-refresh');+ button.disabled = true;+ try {+ const data = await api(`/api/analytics/channel${refresh ? '?refresh=1' : ''}`);+ renderChannelSnapshot(data.result || {});+ } catch (error) {+ renderChannelSnapshot({ available: false, reason: error.message });+ } finally {+ button.disabled = false;+ }+}++function renderChannelSnapshot(snapshot) {+ const container = $('#channel-snapshot');+ const note = $('#channel-snapshot-note');+ if (!snapshot.available) {+ $('#channel-snapshot-title').textContent = 'Channel snapshot';+ container.innerHTML = empty(snapshot.reason || 'Channel statistics are unavailable.');+ note.textContent = 'Whole-channel totals from YouTube, including videos published outside Lumen.';+ return;+ }+ // null means YouTube did not provide the value; it is shown as unavailable, never as 0.+ const count = value => (value === null || value === undefined ? 'Unavailable' : Number(value).toLocaleString());+ const tile = (name, value, hint = '') => `<div><span>${escapeHTML(name)}</span><strong>${escapeHTML(value)}</strong>${hint ? `<small>${escapeHTML(hint)}</small>` : ''}</div>`;+ const { channel, recent = {} } = snapshot;+ $('#channel-snapshot-title').textContent = channel.title || 'Channel snapshot';+ let html = '<p class="channel-snapshot-section">Lifetime</p>'+ + tile('Subscribers', channel.subscribersHidden ? 'Hidden' : count(channel.subscribers), channel.subscribersHidden ? 'hidden on this channel' : '')+ + tile('Views', count(channel.views))+ + tile('Videos', count(channel.videos))+ + tile('Updated', timeAgo(snapshot.fetchedAt) || 'just now');+ html += `<p class="channel-snapshot-section">Last 28 days${recent.startDate ? ` Β· ${escapeHTML(recent.startDate)} to ${escapeHTML(recent.endDate)}` : ''}</p>`;+ if (recent.available) {+ const net = Number(recent.netSubscribers);+ html += tile('Views', count(recent.views))+ + tile('Watch hours', count(recent.watchHours))+ + tile('Subscribers gained', count(recent.subscribersGained), `${count(recent.subscribersLost)} lost`)+ + tile('Net subscribers', `${net > 0 ? '+' : ''}${count(net)}`);+ } else {+ html += `<div class="empty">${escapeHTML(recent.reason || '28-day analytics are unavailable.')}${recent.activationUrl ? ` <a href="${escapeHTML(recent.activationUrl)}" target="_blank" rel="noopener noreferrer">Enable YouTube Analytics API</a>` : ''}</div>`;+ }+ container.innerHTML = html;+ note.textContent = 'Whole-channel totals from YouTube, including videos published outside Lumen. Analytics data lags about two days.';+}+function formatOutcomeValue(value, kind = 'number', currency = 'USD') {if (value === null || value === undefined) return 'Unavailable';const number = Number(value);@@ -797,6 +843,8 @@ function switchView(view) {$('#view-eyebrow').textContent = titles[view][0];$('#view-title').textContent = titles[view][1];location.hash = view;+ // Loaded on demand rather than in the 8-second dashboard poll to spare API quota.+ if (view === 'analytics') loadChannelSnapshot();}function selectOptions(options, selected) {@@ -1626,6 +1674,7 @@ document.addEventListener('change', event => {$('#generate-button').addEventListener('click', () => $('#generate-dialog').showModal());$('#add-idea-button').addEventListener('click', () => $('#idea-dialog').showModal());$('#refresh-button').addEventListener('click', () => refreshDashboard());+$('#channel-snapshot-refresh').addEventListener('click', () => loadChannelSnapshot(true));$('#pipeline-filter').addEventListener('change', () => renderPipeline(ui.state?.pipeline || []));$('#experiment-create-form').addEventListener('submit', async event => {diff --git a/dashboard/index.html b/dashboard/index.htmlindex b49f492..3a56296 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -137,8 +137,13 @@<section id="analytics-view" class="view"><div class="section-intro"><div><h2>Performance signals</h2><p>Data translated into decisions, not vanity metrics.</p></div></div>+ <article class="panel channel-snapshot">+ <div class="panel-heading"><div><p class="eyebrow">YOUR CHANNEL ON YOUTUBE</p><h2 id="channel-snapshot-title">Channel snapshot</h2></div><button id="channel-snapshot-refresh" class="button secondary small" type="button">Refresh</button></div>+ <div id="channel-snapshot" class="baseline-grid channel-snapshot-grid"></div>+ <p id="channel-snapshot-note" class="callout">Whole-channel totals from YouTube, including videos published outside Lumen.</p>+ </article><div class="stats-grid analytics-stats">- <article class="stat"><span>Analyzed videos</span><strong id="analytics-total">β</strong><small>last 30 days</small></article>+ <article class="stat"><span>Analyzed videos</span><strong id="analytics-total">β</strong><small>analyzed by Lumen, last 7 days</small></article><article class="stat"><span>Performance score</span><strong id="analytics-score">β</strong><small>channel average</small></article><article class="stat wide"><span>Recommended action</span><strong id="analytics-action" class="recommendation">Collecting enough data to recommend a move.</strong></article></div>diff --git a/dashboard/styles.css b/dashboard/styles.cssindex 09c5acf..5e4e45e 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -427,6 +427,10 @@ label:has(input:disabled) > span { color: var(--muted); }.date-chip small { color: var(--red); font-size: 8.5px; text-transform: uppercase; letter-spacing: .16em; font-family: var(--font-mono); font-weight: 700; }/* ============ Analytics ============ */+.channel-snapshot { margin-bottom: 16px; }+.baseline-grid.channel-snapshot-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }+.channel-snapshot-grid small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; }+.channel-snapshot-section { grid-column: 1 / -1; margin: 6px 0 -2px; color: var(--muted); font-size: 9px; text-transform: uppercase; letter-spacing: .12em; font-family: var(--font-mono); font-weight: 600; }.analytics-stats { grid-template-columns: 1fr 1fr 2fr; }.stat.wide strong.recommendation { font-size: 18px; line-height: 1.4; letter-spacing: -.02em; font-family: var(--font-sans); -webkit-text-fill-color: var(--text); background: none; font-weight: 650; }@@ -720,7 +724,7 @@ label:has(input:disabled) > span { color: var(--muted); }.sidebar-footer { display: none; }main { width: 100%; max-width: 100vw; padding: 0 18px 60px; }.loading-bar { left: 0; }- .stats-grid { grid-template-columns: 1fr 1fr; }+ .stats-grid, .baseline-grid.channel-snapshot-grid { grid-template-columns: 1fr 1fr; }.overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid, .retention-scene-list, .outcome-breakdowns, .experiment-create-form { grid-template-columns: 1fr; }.experiment-arm-list { grid-template-columns: 1fr; }.overview-grid, .card-list, .job-card { min-width: 0; max-width: 100%; }diff --git a/index.js b/index.jsindex ad96736..0db132d 100644--- a/index.js+++ b/index.js@@ -30,6 +30,10 @@ const { DiscoverabilityService } = require('./utils/discoverability-service');const { version } = require('./package.json');const chalk = require('chalk');+function isLoopbackHost(host) {+ return ['127.0.0.1', '::1', 'localhost'].includes(String(host).toLowerCase()) || /^127\./.test(String(host));+}+class YouTubeAutomationAgent {constructor() {this.logger = new Logger('MainAgent');@@ -428,6 +432,18 @@ class YouTubeAutomationAgent {}});+ this.app.get('/api/analytics/channel', async (req, res) => {+ try {+ if (!this.agents.analytics?.getChannelSnapshot) {+ return res.json({ success: true, result: { available: false, reason: 'Connect YouTube with npm run walkthrough to see channel statistics.' } });+ }+ const result = await this.agents.analytics.getChannelSnapshot({ refresh: req.query.refresh === '1' });+ return res.json({ success: true, result });+ } catch (error) {+ return res.status(500).json({ success: false, error: error.message });+ }+ });+this.app.get('/api/outcomes', async (_req, res) => {try {const learning = this.agents.analytics?.getLearningSummary@@ -1832,8 +1848,14 @@ class YouTubeAutomationAgent {}const PORT = process.env.PORT || 3456;- this.app.listen(PORT, () => {- console.log(chalk.green(`\nβ YouTube Automation Agent running on port ${PORT}`));+ // Loopback by default: mutating routes are open whenever API_KEY is unset,+ // so the dashboard must not be reachable from the network unless asked.+ const HOST = process.env.HOST || '127.0.0.1';+ this.app.listen(PORT, HOST, () => {+ console.log(chalk.green(`\nβ YouTube Automation Agent running on ${HOST}:${PORT}`));+ if (!isLoopbackHost(HOST) && !process.env.API_KEY) {+ console.log(chalk.yellow(`β οΈ HOST=${HOST} exposes the dashboard to your network without API_KEY. Set API_KEY in .env to protect generation, approval, and publishing routes.`));+ }console.log(chalk.gray('β'.repeat(50)));console.log(chalk.white('π Dashboard: ') + chalk.cyan(`http://localhost:${PORT}`));console.log(chalk.white('π§ API Health: ') + chalk.cyan(`http://localhost:${PORT}/health`));diff --git a/modern-auth.js b/modern-auth.jsindex d451cfd..caaad42 100644--- a/modern-auth.js+++ b/modern-auth.js@@ -134,7 +134,8 @@ class ModernAuth {// Save tokensconst tokenData = { youtube: tokens };- fs.writeFileSync(this.tokensPath, JSON.stringify(tokenData, null, 2));+ fs.writeFileSync(this.tokensPath, JSON.stringify(tokenData, null, 2), { mode: 0o600 });+ fs.chmodSync(this.tokensPath, 0o600);res.writeHead(200, { 'Content-Type': 'text/html' });res.end(`diff --git a/oauth-server.js b/oauth-server.jsindex 33cebe9..802d1a3 100644--- a/oauth-server.js+++ b/oauth-server.js@@ -84,7 +84,8 @@ class OAuthServer {youtube: tokens};- fs.writeFileSync(tokensPath, JSON.stringify(tokenData, null, 2));+ fs.writeFileSync(tokensPath, JSON.stringify(tokenData, null, 2), { mode: 0o600 });+ fs.chmodSync(tokensPath, 0o600);console.log(chalk.green('β Tokens saved successfully!'));}@@ -104,7 +105,7 @@ class OAuthServer {}start() {- this.server = this.app.listen(8080, () => {+ this.server = this.app.listen(8080, '127.0.0.1', () => {console.log(chalk.cyan('\nπ OAuth callback server started on http://localhost:8080'));this.generateAuthUrl();});diff --git a/test.js b/test.jsindex d526934..f494240 100644--- a/test.js+++ b/test.js@@ -38,6 +38,7 @@ class SystemTest {{ name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },{ name: 'DarkzSEO Discoverability Preflight', test: () => this.testDiscoverabilityPreflight() },{ name: 'Open Issue Regressions', test: () => this.testOpenIssueRegressions() },+ { name: 'Reported Issue Fixes (#63, #65, #66)', test: () => this.testReportedIssueFixes() },{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },@@ -1894,6 +1895,223 @@ class SystemTest {this.logger.info('DarkzSEO discoverability preflight test completed successfully');}+ async testReportedIssueFixes() {+ const fs = require('fs').promises;+ const os = require('os');+ const sharp = require('sharp');+ const { AITextService } = require('./utils/ai-text-service');+ const { AIVideoGenerator, describeImageProviderError } = require('./utils/ai-video-generator');+ const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');+ const { CredentialManager } = require('./utils/credential-manager');+ const { YouTubeAutomationAgent } = require('./index');++ const envKeys = ['OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'GEMINI_API_KEY', 'MOONSHOT_API_KEY', 'MIMO_API_KEY', 'GLM_API_KEY', 'HOST', 'API_KEY', 'NODE_ENV'];+ const savedEnv = {};+ for (const key of envKeys) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-issue-fixes-'));+ const originalGenerateText = AITextService.prototype.generateText;++ try {+ // #63: a thinking model that spends the whole budget on thoughts is retried+ // once with room for the answer, and the readiness probe budget fits thoughts.+ const gemini = new AITextService({ gemini: { apiKey: 'test-key', model: 'gemini-3.7-flash' } });+ const geminiCalls = [];+ gemini.gemini.models.generateContent = async request => {+ geminiCalls.push(request);+ if (geminiCalls.length === 1) {+ return { text: undefined, candidates: [{ finishReason: 'MAX_TOKENS' }], usageMetadata: { thoughtsTokenCount: 13 } };+ }+ return { text: 'READY', candidates: [{ finishReason: 'STOP' }] };+ };+ const ready = await gemini.generateText('Reply with exactly READY.', { maxTokens: 16, temperature: 0 });+ if (ready !== 'READY' || geminiCalls.length !== 2 || geminiCalls[1].config.maxOutputTokens < 1024) {+ throw new Error('A thinking-model MAX_TOKENS response was not retried with a larger output budget');+ }++ geminiCalls.length = 0;+ gemini.gemini.models.generateContent = async request => {+ geminiCalls.push(request);+ return { text: undefined, candidates: [{ finishReason: 'MAX_TOKENS' }], usageMetadata: { thoughtsTokenCount: 900 } };+ };+ let budgetMessage = '';+ try { await gemini.generateText('prompt', { maxTokens: 64 }); } catch (error) { budgetMessage = error.message; }+ if (geminiCalls.length !== 2 || !/output budget/.test(budgetMessage) || /API key/.test(budgetMessage)) {+ throw new Error('An exhausted thinking budget must retry once and then explain the budget, not blame the API key');+ }++ geminiCalls.length = 0;+ gemini.gemini.models.generateContent = async request => {+ geminiCalls.push(request);+ return { text: '', candidates: [{ finishReason: 'SAFETY' }] };+ };+ let safetyMessage = '';+ try { await gemini.generateText('prompt'); } catch (error) { safetyMessage = error.message; }+ if (geminiCalls.length !== 1 || !/blocked the response \(SAFETY\)/.test(safetyMessage)) {+ throw new Error('A blocked Gemini response must not be retried and must report the block reason');+ }++ let probeOptions = null;+ AITextService.prototype.generateText = async function (_prompt, options) {+ probeOptions = options;+ return 'READY';+ };+ const readiness = new ProductionReadinessService({}, { credentials: { gemini: { apiKey: 'test-key' } } });+ await readiness.probeText();+ if (!probeOptions || probeOptions.maxTokens < 256) {+ throw new Error('The readiness text probe budget is too small for thinking models');+ }+ AITextService.prototype.generateText = originalGenerateText;++ // #65: the cause of a failure reaches the console even when NODE_ENV=production.+ const logger = new Logger('IssueFixTest');+ if (logger.withDetail('Visual asset generation failed:', new Error('quota exhausted')) !== 'Visual asset generation failed: quota exhausted') {+ throw new Error('Error details were not appended to the console line');+ }+ if (logger.withDetail('Fallback failed: boom', new Error('boom')) !== 'Fallback failed: boom') {+ throw new Error('An already-interpolated error message was duplicated');+ }+ if (logger.withDetail('Saved', { id: 1 }) !== 'Saved') {+ throw new Error('Structured log metadata must not be appended to the console line');+ }+ process.env.NODE_ENV = 'production';+ const printed = [];+ const originalConsoleLog = console.log;+ console.log = line => printed.push(String(line));+ try {+ logger.error('Thumbnail generation failed:', new Error('limit: 0'));+ logger.warn('Failed to initialize Gemini media service:', 'module missing');+ } finally {+ console.log = originalConsoleLog;+ delete process.env.NODE_ENV;+ }+ if (!printed.some(line => line.includes('Thumbnail generation failed: limit: 0')) || !printed.some(line => line.includes('module missing'))) {+ throw new Error('Production console output hid the failure cause');+ }++ const quotaError = Object.assign(new Error(JSON.stringify({ error: {+ code: 429,+ message: 'Quota exceeded for metric: generate_content_free_tier_requests, limit: 0, model: gemini-3.1-flash-image',+ status: 'RESOURCE_EXHAUSTED'+ } })), { status: 429 });+ const quota = describeImageProviderError('Gemini', 'gemini-3.1-flash-image', quotaError);+ if (!/429 RESOURCE_EXHAUSTED/.test(quota) || !/billing/.test(quota) || /\{"error"/.test(quota)) {+ throw new Error('A Gemini zero-quota error was not translated into a readable billing fix');+ }++ // #65: a failing image provider falls through to the next configured one.+ const generator = new AIVideoGenerator({ openai: { apiKey: 'test-key' }, gemini: { apiKey: 'test-key' } });+ let openAIAttempts = 0;+ generator.openai.images.generate = async () => {+ openAIAttempts++;+ throw Object.assign(new Error('401 Incorrect API key provided'), { status: 401 });+ };+ const image = await sharp({ create: { width: 320, height: 180, channels: 3, background: '#224488' } }).png().toBuffer();+ generator.gemini.models.generateContent = async () => ({+ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: image.toString('base64') } }] } }]+ });+ const imagePath = path.join(directory, 'fallback.png');+ await generator.generateImage('A blue test image', imagePath);+ if (openAIAttempts !== 1 || (await sharp(imagePath).metadata()).width !== 320) {+ throw new Error('A failed OpenAI image request did not fall back to Gemini');+ }+ generator.gemini.models.generateContent = async () => { throw quotaError; };+ let combined = '';+ try { await generator.generateImage('A blue test image', path.join(directory, 'none.png')); } catch (error) { combined = error.message; }+ if (!/OpenAI image generation/.test(combined) || !/Gemini image generation/.test(combined) || !/rejected/.test(combined)) {+ throw new Error('When every image provider fails, each provider failure and fix must be reported');+ }++ // #66: whole-channel statistics come from YouTube, cache briefly, and report a+ // disabled Analytics API with an activation link instead of zeroes.+ const analytics = new AnalyticsOptimizationAgent({}, {});+ let channelCalls = 0;+ analytics.youtube = { channels: { list: async () => {+ channelCalls++;+ return { data: { items: [{ id: 'UC123', snippet: { title: 'Existing Channel' }, statistics: { subscriberCount: '1200', viewCount: '45000', videoCount: '38', hiddenSubscriberCount: false } }] } };+ } } };+ analytics.youtubeAnalytics = { reports: { query: async () => ({ data: {+ columnHeaders: [{ name: 'views' }, { name: 'estimatedMinutesWatched' }, { name: 'subscribersGained' }, { name: 'subscribersLost' }],+ rows: [[3100, 5400, 40, 6]]+ } }) } };+ const snapshot = await analytics.getChannelSnapshot();+ if (!snapshot.available || snapshot.channel.title !== 'Existing Channel' || snapshot.channel.subscribers !== 1200 || snapshot.channel.videos !== 38) {+ throw new Error('Channel snapshot did not report the channel-wide YouTube totals');+ }+ if (!snapshot.recent.available || snapshot.recent.watchHours !== 90 || snapshot.recent.netSubscribers !== 34) {+ throw new Error('Channel snapshot did not report 28-day analytics');+ }+ const day = 24 * 60 * 60 * 1000;+ if ((new Date(snapshot.recent.endDate) - new Date(snapshot.recent.startDate)) / day !== 27) {+ throw new Error('Channel analytics window is not 28 days');+ }+ await analytics.getChannelSnapshot();+ if (channelCalls !== 1) throw new Error('Channel snapshot was not cached between dashboard visits');++ analytics.youtubeAnalytics = { reports: { query: async () => {+ const error = new Error('YouTube Analytics API has not been used in project 42 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtubeanalytics.googleapis.com/overview?project=42 then retry.');+ error.response = { data: { error: { code: 403, message: error.message, errors: [{ reason: 'accessNotConfigured' }] } } };+ throw error;+ } } };+ const disabled = await analytics.getChannelSnapshot({ refresh: true });+ if (channelCalls !== 2 || disabled.recent.available || !/not enabled/.test(disabled.recent.reason) ||+ !/youtubeanalytics\.googleapis\.com/.test(disabled.recent.activationUrl || '') || 'views' in disabled.recent) {+ throw new Error('A disabled YouTube Analytics API must be reported with an activation link, not as zero');+ }+ const hidden = new AnalyticsOptimizationAgent({}, {});+ hidden.youtube = { channels: { list: async () => ({ data: { items: [{ id: 'UC9', snippet: {}, statistics: { viewCount: '1', videoCount: '1', hiddenSubscriberCount: true } }] } }) } };+ hidden.youtubeAnalytics = analytics.youtubeAnalytics;+ const hiddenSnapshot = await hidden.getChannelSnapshot();+ if (hiddenSnapshot.channel.subscribers !== null || !hiddenSnapshot.channel.subscribersHidden) {+ throw new Error('Hidden subscriber counts must be unavailable, not zero');+ }+ const disconnected = await new AnalyticsOptimizationAgent({}, {}).getChannelSnapshot();+ if (disconnected.available !== false || !/Connect YouTube/.test(disconnected.reason)) {+ throw new Error('A missing YouTube connection must be explained');+ }++ // #66: the dashboard listens on loopback unless HOST says otherwise.+ const server = new YouTubeAutomationAgent();+ server.initialize = async () => true;+ let listenArgs = null;+ server.app = { listen: (port, host, callback) => { listenArgs = { port, host }; if (callback) callback(); } };+ const quietLog = console.log;+ console.log = () => {};+ try {+ await server.start();+ if (listenArgs?.host !== '127.0.0.1') throw new Error(`Dashboard server bound to ${listenArgs?.host} instead of loopback by default`);+ process.env.HOST = '0.0.0.0';+ await server.start();+ if (listenArgs?.host !== '0.0.0.0') throw new Error('HOST did not override the dashboard bind address');+ } finally {+ console.log = quietLog;+ delete process.env.HOST;+ }++ // #66: credential and token files are owner-only.+ if (process.platform !== 'win32') {+ const credentials = new CredentialManager();+ credentials.tokensPath = path.join(directory, 'tokens.json');+ await fs.writeFile(credentials.tokensPath, '{}', { mode: 0o644 });+ credentials.tokens = { youtube: { refresh_token: 'test' } };+ await credentials.saveTokens();+ const mode = (await fs.stat(credentials.tokensPath)).mode & 0o777;+ if (mode !== 0o600) throw new Error(`Token file mode is ${mode.toString(8)}, expected 600`);+ }+ } finally {+ AITextService.prototype.generateText = originalGenerateText;+ for (const key of envKeys) {+ if (savedEnv[key] === undefined) delete process.env[key];+ else process.env[key] = savedEnv[key];+ }+ await fs.rm(directory, { recursive: true, force: true }).catch(() => {});+ }++ this.logger.info('Reported issue fix tests completed successfully');+ }+async testOpenIssueRegressions() {const { ModernAuth } = require('./modern-auth');const { ProductionManagementAgent } = require('./agents/production-management-agent');@@ -2766,6 +2984,22 @@ class SystemTest {], hybridPath);const hybridStats = await fs.stat(hybridPath);if (!hybridStats.size) throw new Error('Hybrid provider/still timeline did not produce a video');++ // A clip shorter than its slot is looped, but the looped input is bounded+ // to the slot so FFmpeg stops decoding once the timeline is filled.+ const shortClipPath = path.join(dir, 'short-clip.mp4');+ await generator.renderMediaTimeline([{ type: 'image', path: stills[1], duration: 1 }], shortClipPath);+ const loopedPath = path.join(dir, 'looped.mp4');+ const loopStarted = Date.now();+ await generator.renderMediaTimeline([+ { type: 'video', path: shortClipPath, duration: 2.5 },+ { type: 'image', path: stills[2], duration: 1 }+ ], loopedPath);+ const loopedDuration = await getMediaDuration(loopedPath);+ if (loopedDuration < 3.3 || loopedDuration > 3.7) {+ throw new Error(`Looped provider clip did not fill its 2.5s slot exactly; timeline is ${loopedDuration}s`);+ }+ if (Date.now() - loopStarted > 60000) throw new Error('Looped provider clip input was not bounded');} finally {await fs.rm(dir, { recursive: true, force: true }).catch(() => {});}diff --git a/utils/ai-text-service.js b/utils/ai-text-service.jsindex a123df5..2c90ba7 100644--- a/utils/ai-text-service.js+++ b/utils/ai-text-service.js@@ -7,6 +7,8 @@ const GEMINI_MODELS = ['gemini-3.5-flash-lite',];const GEMINI_DEFAULT_MODEL = GEMINI_MODELS[0];+// Floor for the single retry after a thinking model exhausts a small budget.+const GEMINI_THINKING_RETRY_MIN_TOKENS = 1024;const PROVIDERS = {openai: {@@ -108,16 +110,28 @@ class AITextService {if (this.gemini) {const config = { maxOutputTokens: maxTokens };if (!/^gemini-3\.(?:[5-9]|\d{2,})-/.test(model)) config.temperature = temperature;- const response = await this.gemini.models.generateContent({+ let response = await this.gemini.models.generateContent({model,contents: prompt,config,});- const text = response && response.text;- if (typeof text !== 'string' || !text.trim()) {- throw new Error(- `${this.providerName} returned an empty response. Check the API key and model quota β free-tier Gemini keys are rate-limited and can return empty output.`- );+ let text = response && response.text;++ // Thinking models (gemini-3.x flash/pro) count thoughts against+ // maxOutputTokens, so a small budget can be spent before any text is+ // written. Retry once with room for the thoughts plus the answer.+ if (!this._hasText(text) && this._geminiFinishReason(response) === 'MAX_TOKENS') {+ const retryTokens = Math.max(maxTokens * 4, GEMINI_THINKING_RETRY_MIN_TOKENS);+ response = await this.gemini.models.generateContent({+ model,+ contents: prompt,+ config: { ...config, maxOutputTokens: retryTokens },+ });+ text = response && response.text;+ }++ if (!this._hasText(text)) {+ throw new Error(this._geminiEmptyResponseMessage(response));}return text;}@@ -178,6 +192,27 @@ class AITextService {throw lastError;}+ _hasText(text) {+ return typeof text === 'string' && text.trim().length > 0;+ }++ _geminiFinishReason(response) {+ return response?.candidates?.[0]?.finishReason || null;+ }++ _geminiEmptyResponseMessage(response) {+ const finishReason = this._geminiFinishReason(response);+ const blockReason = response?.promptFeedback?.blockReason;+ if (finishReason === 'MAX_TOKENS') {+ const thoughts = response?.usageMetadata?.thoughtsTokenCount;+ return `${this.providerName} spent its whole output budget${thoughts ? ` (${thoughts} thinking tokens)` : ''} before writing any text. Raise maxTokens, or choose a model that does not think, such as gemini-3.5-flash-lite.`;+ }+ if (blockReason || ['SAFETY', 'PROHIBITED_CONTENT', 'BLOCKLIST', 'SPII', 'RECITATION'].includes(finishReason)) {+ return `${this.providerName} blocked the response (${blockReason || finishReason}). Rephrase the prompt or topic and try again.`;+ }+ return `${this.providerName} returned an empty response${finishReason ? ` (finishReason: ${finishReason})` : ''}. Check the API key and model quota β free-tier Gemini keys are rate-limited and can return empty output.`;+ }+_extractContent(response) {const content =response &&diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.jsindex a33e5db..0094d81 100644--- a/utils/ai-video-generator.js+++ b/utils/ai-video-generator.js@@ -8,6 +8,59 @@ const { Logger } = require('./logger');const { runFFmpeg, getMediaDuration, checkFFmpeg, ffmpegInstallHint } = require('./ffmpeg');const { MediaGenerationService } = require('./media-generation-service');+const OPENAI_IMAGE_MODEL = 'gpt-image-2';++// Turns an image provider SDK error into one readable line that leads with the+// fix when the cause is recognisable. @google/genai puts the raw JSON error+// body in error.message, which is unreadable on a console.+function describeImageProviderError(provider, model, error) {+ const raw = String(error?.message || error || 'Unknown error');+ let status = Number(error?.status) || null;+ let code = String(error?.code || '');+ let detail = raw;+ try {+ const body = JSON.parse(raw.slice(raw.indexOf('{')));+ if (body?.error) {+ status = status || Number(body.error.code) || null;+ code = body.error.status || code;+ detail = body.error.message || raw;+ }+ } catch (_error) { /* not a JSON error body */ }++ const text = `${code} ${detail}`;+ let fix = null;+ if (provider === 'Gemini') {+ if (/limit:\s*0\b/i.test(text) || (status === 429 && /free.?tier/i.test(text))) {+ fix = `this key has no quota for ${model}. Gemini image models are not on the free tier: turn on billing for the Google Cloud project that owns this API key (AI Studio β API keys β Set up billing). A paid account does not help if the key belongs to a different project.`;+ } else if (status === 429 || /RESOURCE_EXHAUSTED/i.test(code)) {+ fix = 'Gemini rate-limited this key. Wait a minute and retry, or raise the project quota.';+ } else if (/API key not valid|API key expired|API_KEY_INVALID/i.test(text)) {+ fix = 'the Gemini API key was rejected. Create a new key in Google AI Studio and save it in Settings.';+ } else if (/location is not supported|user location/i.test(text)) {+ fix = 'Gemini image generation is not available in your region for this key.';+ } else if (status === 404 || /NOT_FOUND|not supported for generateContent/i.test(text)) {+ fix = `${model} is not available to this key. Set GEMINI_IMAGE_MODEL to an image model your key can use (for example gemini-3.1-flash-image).`;+ } else if (status === 403 || /PERMISSION_DENIED|SERVICE_DISABLED/i.test(text)) {+ fix = "this key's Google Cloud project cannot call the Gemini API. Enable the Generative Language API for that project, or create the key in Google AI Studio.";+ }+ } else if (provider === 'OpenAI') {+ if (status === 401 || /invalid_api_key|Incorrect API key/i.test(text)) {+ fix = 'the OpenAI API key was rejected. Check the key in Settings.';+ } else if (/insufficient_quota|billing/i.test(text)) {+ fix = 'the OpenAI account has no remaining credit. Add billing at platform.openai.com.';+ } else if (status === 403 && /verif/i.test(text)) {+ fix = `${model} requires a verified OpenAI organization (platform.openai.com β Settings β Organization β Verify).`;+ } else if (status === 429) {+ fix = 'OpenAI rate-limited this key. Wait a minute and retry.';+ }+ }++ const label = [status, code && code !== String(status) ? code : null].filter(Boolean).join(' ');+ const summary = `${provider} image generation (${model}) failed${label ? ` [${label}]` : ''}.`;+ const shortDetail = detail.replace(/\s+/g, ' ').trim().slice(0, 220);+ return fix ? `${summary} Fix: ${fix} Details: ${shortDetail}` : `${summary} ${shortDetail}`;+}+class AIVideoGenerator {constructor(credentials, options = {}) {this.logger = new Logger('AIVideoGenerator');@@ -220,20 +273,44 @@ class AIVideoGenerator {async generateImage(prompt, imagePath) {await fs.mkdir(path.dirname(imagePath), { recursive: true });+ const providers = [];if (this.openai) {- return await this.generateOpenAIImage(prompt, imagePath);+ providers.push({ name: 'OpenAI', model: OPENAI_IMAGE_MODEL, run: () => this.generateOpenAIImage(prompt, imagePath) });}-if (this.gemini) {- return await this.generateGeminiImage(prompt, imagePath);+ providers.push({ name: 'Gemini', model: this.geminiImageModel(), run: () => this.generateGeminiImage(prompt, imagePath) });+ }+ if (!providers.length) {+ throw new Error('No image generation provider configured');}- throw new Error('No image generation provider configured');+ // Try every configured provider before giving up, so a broken OpenAI key+ // does not hide a working Gemini key (or the reverse).+ const failures = [];+ for (const [index, provider] of providers.entries()) {+ try {+ return await provider.run();+ } catch (error) {+ const description = describeImageProviderError(provider.name, provider.model, error);+ failures.push(description);+ if (index < providers.length - 1) {+ this.logger.warn(`${description} Trying ${providers[index + 1].name} instead.`);+ }+ }+ }++ const error = new Error(failures.join(' | '));+ error.providerFailures = failures;+ throw error;+ }++ geminiImageModel() {+ return process.env.GEMINI_IMAGE_MODEL || 'gemini-3.1-flash-image';}async generateOpenAIImage(prompt, imagePath) {const response = await this.openai.images.generate({- model: "gpt-image-2",+ model: OPENAI_IMAGE_MODEL,prompt: prompt,n: 1,size: "1536x1024",@@ -251,7 +328,7 @@ class AIVideoGenerator {}async generateGeminiImage(prompt, imagePath) {- const model = process.env.GEMINI_IMAGE_MODEL || 'gemini-3.1-flash-image';+ const model = this.geminiImageModel();const response = await this.gemini.models.generateContent({model,@@ -410,8 +487,11 @@ class AIVideoGenerator {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('-stream_loop', '-1', '-i', segment.path);+ const duration = Number(segment.duration).toFixed(2);+ if (segment.type === 'image') args.push('-loop', '1', '-t', duration, '-framerate', '30', '-i', segment.path);+ // Loop short clips to fill their slot, but bound the input: an unbounded+ // -stream_loop keeps FFmpeg decoding long after trim has what it needs.+ else args.push('-stream_loop', '-1', '-t', duration, '-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}]`@@ -995,4 +1075,4 @@ class AIVideoGenerator {}}-module.exports = { AIVideoGenerator };+module.exports = { AIVideoGenerator, describeImageProviderError };diff --git a/utils/credential-manager.js b/utils/credential-manager.jsindex b060f5f..1fe37fd 100644--- a/utils/credential-manager.js+++ b/utils/credential-manager.js@@ -6,6 +6,13 @@ const chalk = require('chalk');const { Logger } = require('./logger');const { PROVIDERS, GEMINI_MODELS, GEMINI_DEFAULT_MODEL } = require('./ai-text-service');+// API keys and OAuth tokens are owner-only (0600). writeFile's mode applies only+// when the file is created, so files written by older versions are tightened too.+async function writePrivateFile(filePath, contents) {+ await fs.writeFile(filePath, contents, { mode: 0o600 });+ await fs.chmod(filePath, 0o600).catch(() => {});+}+class CredentialManager {constructor() {this.logger = new Logger('CredentialManager');@@ -46,12 +53,12 @@ class CredentialManager {async saveCredentials() {await fs.mkdir(path.dirname(this.credentialsPath), { recursive: true });- await fs.writeFile(this.credentialsPath, JSON.stringify(this.credentials, null, 2));+ await writePrivateFile(this.credentialsPath, JSON.stringify(this.credentials, null, 2));}async saveTokens() {await fs.mkdir(path.dirname(this.tokensPath), { recursive: true });- await fs.writeFile(this.tokensPath, JSON.stringify(this.tokens, null, 2));+ await writePrivateFile(this.tokensPath, JSON.stringify(this.tokens, null, 2));}// YouTube API Authenticationdiff --git a/utils/logger.js b/utils/logger.jsindex d92bde2..782ba4a 100644--- a/utils/logger.js+++ b/utils/logger.js@@ -57,21 +57,36 @@ class Logger {warn(message, ...args) {this.winston.warn(message, ...args);- console.log(this.formatConsoleMessage('WARN', message, chalk.yellow));+ console.log(this.formatConsoleMessage('WARN', this.withDetail(message, args[0]), chalk.yellow));}error(message, error = null, ...args) {- if (error) {+ if (error instanceof Error || typeof error?.message === 'string') {this.winston.error(message, { error: error.message, stack: error.stack, ...args });+ } else if (error !== null && error !== undefined) {+ this.winston.error(message, { error, ...args });} else {this.winston.error(message, ...args);}- console.log(this.formatConsoleMessage('ERROR', message, chalk.red));- if (error && process.env.NODE_ENV !== 'production') {+ // The cause must reach the console even when NODE_ENV=production hides+ // the stack; otherwise "X failed:" is printed with no reason at all.+ console.log(this.formatConsoleMessage('ERROR', this.withDetail(message, error), chalk.red));+ if (error?.stack && process.env.NODE_ENV !== 'production') {console.error(chalk.red(error.stack));}}+ // Appends an error's message (or a plain string/number detail) to a console+ // line unless the caller already interpolated it.+ withDetail(message, detail) {+ let text = null;+ if (typeof detail === 'string' || typeof detail === 'number') text = String(detail);+ else if (detail instanceof Error || typeof detail?.message === 'string') text = detail.message;+ text = text && text.trim();+ if (!text || String(message).includes(text)) return message;+ return /[:β-]\s*$/.test(message) ? `${message.trimEnd()} ${text}` : `${message}: ${text}`;+ }+debug(message, ...args) {this.winston.debug(message, ...args);if (process.env.NODE_ENV !== 'production') {diff --git a/utils/production-readiness-service.js b/utils/production-readiness-service.jsindex 0b06da6..9324296 100644--- a/utils/production-readiness-service.js+++ b/utils/production-readiness-service.js@@ -138,7 +138,9 @@ class ProductionReadinessService {if (this.probes.text) return this.probes.text();const service = new AITextService(this.credentialManager.credentials || {});if (!service.isAvailable()) throw new Error('No AI text provider is configured');- const response = await service.generateText('Reply with exactly READY.', { maxTokens: 16, temperature: 0 });+ // Thinking models use ~100 output tokens on thoughts even for a one-word+ // reply, so the budget must leave room beyond the answer itself.+ const response = await service.generateText('Reply with exactly READY.', { maxTokens: 256, temperature: 0 });return { message: `${service.providerName} returned a live response.`, details: { provider: service.providerName, responseReceived: Boolean(response) } };}diff --git a/walkthrough.js b/walkthrough.jsindex 686bc78..0a0d7b9 100644--- a/walkthrough.js+++ b/walkthrough.js@@ -330,7 +330,7 @@ class SetupWalkthrough {try {const service = new AITextService(guide.validationCreds(apiKey, model));- const reply = await service.generateText('Reply with the single word OK.', { maxTokens: 20, temperature: 0 });+ 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}`));