Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ DEFAULT_DELAY_BETWEEN_POSTS=60000
# Optional. If set, mutating API routes require this value in the x-api-key header.
API_KEY=

# ELENA integration (optional; enables only the two documented research/draft endpoints)
# Generate a unique random token with at least 32 UTF-8 bytes. Never reuse API_KEY.
# ELENA_INTEGRATION_TOKEN=
# Bind this installation to exactly one ELENA workspace; requests must send this exact ID.
# ELENA_WORKSPACE_ID=

# Optional. Generation jobs run one at a time by default to control API spend.
MAX_CONCURRENT_JOBS=1

Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ Open `http://localhost:3456`. The walkthrough explains each provider choice, tes

Already know what you are doing? `npm run setup` offers a shorter classic flow, and `.env.example` documents every setting.

### ELENA integration

This repository exposes an optional, permission-bounded ELENA seam for content research and unapproved script drafts only. It does not add a Discord bot or give ELENA publish, schedule, job, or autonomous-operator controls. See the [ELENA integration contract](docs/integrations/elena.md) for authentication, workspace binding, request/response schemas, and network requirements.

### Verify production readiness

Before activating autonomous production, open **Production readiness** in the dashboard and choose **Run verified check**. The gate makes small live text and narration requests, verifies access to the connected YouTube channel, creates and decodes a temporary MP4 containing audio and video, and validates every queued upload's metadata. It never creates or uploads a YouTube video, and temporary probe assets are deleted after the run.
Expand Down
128 changes: 128 additions & 0 deletions docs/integrations/elena.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# ELENA integration contract

AgentTube provides two fixed mission tools for an ELENA instance. ELENA remains the control plane; this service does not add a bot, webhook listener, generic tool dispatcher, or workspace-management API.

## Enablement and binding

Set both values in the AgentTube `.env` file:

```dotenv
ELENA_INTEGRATION_TOKEN=<unique random secret, at least 32 UTF-8 bytes>
ELENA_WORKSPACE_ID=<the one ELENA workspace allowed to use this AgentTube installation>
```

The integration is disabled with HTTP `503` if the token is missing, malformed, or shorter than 32 bytes, or if the workspace binding is missing. Generate a unique secret and keep it in the ELENA and AgentTube secret stores. Do not reuse `API_KEY`; the integration token is independent of the dashboard API key.

This is a **single-workspace binding, not tenant isolation**. Every request must include the exact configured `workspaceId`; other IDs receive HTTP `403`. The application still uses its one local database, credential set, and connected YouTube channel. Do not bind multiple ELENA workspaces to one AgentTube installation or treat the request ID as a per-workspace database boundary.

## Authentication

Send the integration token only as a bearer credential over HTTPS:

```http
Authorization: Bearer <ELENA_INTEGRATION_TOKEN>
Content-Type: application/json
```

Missing or invalid credentials receive HTTP `401`. Do not place the token in URLs, mission arguments, logs, or client-visible output. Keep this API on a private network or behind a TLS-terminating reverse proxy; do not expose it over plain HTTP.

## Allowlisted mission tools

Only these exact `POST` routes are ELENA integration tools. Unknown request properties are rejected. There is no route for arbitrary method dispatch. At the network edge, allow the ELENA service identity to reach only these two paths and deny it access to the rest of the dashboard/API; the shared AgentTube listener also serves other existing routes.

### `POST /api/elena/research`

Request:

```json
{
"workspaceId": "configured-workspace-id",
"topic": "battery recycling"
}
```

`topic` must be a non-empty string of at most 200 characters. This action refreshes the existing YouTube trend and configured-competitor analysis, then returns up to five matching trend signals with verified YouTube evidence URLs. It is not a general web search, and an empty result means no matching current signal was found.

Successful response (`200`):

```json
{
"success": true,
"workspaceId": "configured-workspace-id",
"result": {
"requestedTopic": "battery recycling",
"generatedAt": "2026-10-19T16:00:00.000Z",
"signals": [
{
"topic": "Example matching signal",
"score": 1.25,
"sources": ["trending"],
"evidence": [
{
"title": "Example public YouTube video",
"url": "https://www.youtube.com/watch?v=example",
"publisher": "Example publisher"
}
]
}
],
"note": "Signals are current YouTube trend and configured-competitor evidence; they are not a comprehensive topic search."
}
}
```

### `POST /api/elena/drafts`

Request:

```json
{
"workspaceId": "configured-workspace-id",
"topic": "battery recycling",
"angle": "Explain the tradeoffs for municipal programs",
"contentType": "explainer",
"length": "medium"
}
```

Only `workspaceId` and `topic` are required. `angle` is optional, at most 500 characters. `contentType` is optional and must be `explainer`, `tutorial`, `list`, `review`, or `story`. `length` is optional and must be `short`, `medium`, or `long`.

Successful response (`201`) contains a saved script draft and explicit approval state:

```json
{
"success": true,
"workspaceId": "configured-workspace-id",
"result": {
"status": "draft",
"approvalRequired": true,
"approved": false,
"script": {
"title": "Example script title",
"hook": "Example opening hook",
"fullScript": "Draft script text",
"duration": 480,
"keywords": ["battery recycling"],
"claims": [],
"generatedAt": "2026-10-19T16:00:00.000Z"
}
}
}
```

The draft action may call the configured text-generation provider and saves a content strategy and script in the existing local database. The saved script remains an unapproved draft. It does not create a video, generation job, production, approval, schedule, or upload.

## Permission and control boundary

ELENA requests can invoke only the two routes above. They cannot publish, schedule or reschedule, approve content, start/resume/cancel generation jobs, modify channel settings, pause/resume automation, or start/resume/cancel the Autonomous Channel Operator. Those controls remain outside this integration and under the existing human-review workflow. The application may initialize its existing scheduler at normal application startup; neither ELENA endpoint starts or controls that scheduler.

Invalid input returns `400`; a workspace mismatch returns `403`; unavailable setup or integration configuration returns `503`; provider/research failures return a generic `502`; a concurrent ELENA request returns `429`. Provider errors are logged locally rather than returned to ELENA.

## Required network permissions and secrets

- **ELENA runtime → AgentTube:** allow outbound HTTPS to this AgentTube installation's private/reverse-proxied host and port, only for `POST /api/elena/research` and `POST /api/elena/drafts`. The service uses the configured `HOST`/`PORT` listener; keep it network-restricted.
- **AgentTube → YouTube/Google:** research uses the connected YouTube Data API (`youtube.googleapis.com`) for public trend and configured-competitor data. The existing OAuth credential/token setup must be valid; normal OAuth token refresh may contact `oauth2.googleapis.com`.
- **AgentTube → configured AI text provider:** draft strategy/script generation uses the configured provider when available. The supported provider hosts are `api.openai.com`, `generativelanguage.googleapis.com`, `openrouter.ai`, `api.moonshot.ai`, `api.xiaomimimo.com`, or `api.z.ai`; permit only the host selected/configured for this installation. No video, image, TTS, or publishing-provider access is needed by these ELENA routes.
- Store `ELENA_INTEGRATION_TOKEN`, existing AI provider keys, and YouTube OAuth credentials as secrets. `ELENA_WORKSPACE_ID` is a binding identifier, not an authentication secret.

If the service is hosted remotely, enforce TLS, source-network restrictions, and secret rotation at the deployment/reverse-proxy layer. The integration itself does not provide per-user authorization or multi-tenant data isolation.
151 changes: 151 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ const { AudienceEngagementService } = require('./utils/audience-engagement-servi
const { GrowthExperimentService } = require('./utils/growth-experiment-service');
const { AITextService } = require('./utils/ai-text-service');
const { DiscoverabilityService } = require('./utils/discoverability-service');
const {
requireElenaIntegrationToken,
validateResearchRequest,
validateDraftRequest
} = require('./utils/elena-integration');
const { version } = require('./package.json');
const chalk = require('chalk');

Expand Down Expand Up @@ -55,6 +60,7 @@ class YouTubeAutomationAgent {
this.engagement = null;
this.experiments = null;
this.discoverability = null;
this.elenaRequestInFlight = false;
this.setupRequired = false;
}

Expand Down Expand Up @@ -482,9 +488,154 @@ class YouTubeAutomationAgent {
}
});

this.setupElenaAPI();
this.setupOperatorAPI();
}

setupElenaAPI() {
const authenticate = requireElenaIntegrationToken();
const singleRequest = (req, res, next) => {
if (this.elenaRequestInFlight) {
return res.status(429).json({ success: false, error: 'Another ELENA request is in progress' });
}

this.elenaRequestInFlight = true;
let released = false;
const release = () => {
if (released) return;
released = true;
this.elenaRequestInFlight = false;
};
res.once('finish', release);
res.once('close', release);
return next();
};

this.app.post('/api/elena/research', authenticate, singleRequest, async (req, res) => {
const validation = validateResearchRequest(req.body, process.env.ELENA_WORKSPACE_ID);
if (!validation.valid) {
return res.status(validation.status).json({ success: false, error: validation.error });
}
if (this.setupRequired || !this.agents.strategy) {
return res.status(503).json({ success: false, error: 'Content research is not configured' });
}

try {
const strategyAgent = this.agents.strategy;
await strategyAgent.analyzeTrends();
const terms = validation.value.topic.toLowerCase().match(/[a-z0-9]{3,}/g) || [];
const signals = (strategyAgent.trendingTopics || [])
.filter(signal => {
const signalTopic = String(signal.topic || '').toLowerCase();
return terms.some(term => signalTopic.includes(term));
})
.slice(0, 5)
.map(signal => ({
topic: String(signal.topic || '').slice(0, 200),
score: Number.isFinite(Number(signal.score)) ? Number(signal.score) : 0,
sources: [...new Set((signal.sources || []).filter(source => ['trending', 'competitor'].includes(source)))],
evidence: (signal.evidence || [])
.filter(source => {
try {
const url = new URL(source.url);
return url.protocol === 'https:' && ['youtube.com', 'www.youtube.com'].includes(url.hostname);
} catch (_error) {
return false;
}
})
.slice(0, 5)
.map(source => ({
title: String(source.title || '').slice(0, 200),
url: source.url,
publisher: String(source.publisher || '').slice(0, 100)
}))
}));

return res.json({
success: true,
workspaceId: validation.value.workspaceId,
result: {
requestedTopic: validation.value.topic,
generatedAt: new Date().toISOString(),
signals,
note: signals.length
? 'Signals are current YouTube trend and configured-competitor evidence; they are not a comprehensive topic search.'
: 'No matching current YouTube trend or configured-competitor signals were found.'
}
});
} catch (error) {
this.logger.error('ELENA research request failed:', error);
return res.status(502).json({ success: false, error: 'Content research failed' });
}
});

this.app.post('/api/elena/drafts', authenticate, singleRequest, async (req, res) => {
const validation = validateDraftRequest(req.body, process.env.ELENA_WORKSPACE_ID);
if (!validation.valid) {
return res.status(validation.status).json({ success: false, error: validation.error });
}
if (this.setupRequired || !this.agents.strategy || !this.agents.scriptWriter) {
return res.status(503).json({ success: false, error: 'Content drafting is not configured' });
}

try {
const strategyAgent = this.agents.strategy;
await strategyAgent.analyzeTrends();
const topicTerms = validation.value.topic.toLowerCase().match(/[a-z0-9]{3,}/g) || [];
const researchSources = (strategyAgent.trendingTopics || [])
.filter(signal => topicTerms.some(term => String(signal.topic || '').toLowerCase().includes(term)))
.flatMap(signal => signal.evidence || [])
.map(source => source.url)
.filter(url => {
try {
const parsed = new URL(url);
return parsed.protocol === 'https:' && ['youtube.com', 'www.youtube.com'].includes(parsed.hostname);
} catch (_error) {
return false;
}
})
.slice(0, 10);
const strategy = await strategyAgent.generateContentStrategy(validation.value.topic);
const requestedLength = validation.value.length || 'medium';
Object.assign(strategy, {
topic: validation.value.topic,
targetAudience: process.env.TARGET_AUDIENCE || strategy.targetAudience,
contentType: validation.value.contentType || strategy.contentType,
angle: validation.value.angle || strategy.angle,
requestedLength: {
short: '3-5 minutes',
medium: '8-12 minutes',
long: '15-20 minutes'
}[requestedLength],
researchSources
});
const script = await this.agents.scriptWriter.generateScript(strategy);

return res.status(201).json({
success: true,
workspaceId: validation.value.workspaceId,
result: {
status: 'draft',
approvalRequired: true,
approved: false,
script: {
title: script.title,
hook: script.hook,
fullScript: script.fullScript,
duration: script.duration,
keywords: script.keywords || [],
claims: script.claims || [],
generatedAt: script.metadata?.generatedAt || new Date().toISOString()
}
}
});
} catch (error) {
this.logger.error('ELENA draft request failed:', error);
return res.status(502).json({ success: false, error: 'Content draft generation failed' });
}
});
}

setupOperatorAPI() {
const protect = this.requireAPIKey();

Expand Down
Loading