Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: scope section regeneration and wait for long API requests (#10564)

[._.]/ Adam Eivy1c144e6c8b1b
diff --git a/docs/AGENT_API_KEY.md b/docs/AGENT_API_KEY.md
index 8cb3894a7d..690f4df53b 100644
--- a/docs/AGENT_API_KEY.md
+++ b/docs/AGENT_API_KEY.md
@@ -39,6 +39,8 @@ node <repo-root>/scripts/portos-api.js get /api/api-docs/catalog.json
`PORTOS_API_TOKEN` and `PORTOS_URL`, when set, win over the key file, so the same command works inside a PortOS-spawned agent.
+Requests wait up to 30 minutes for long-running AI routes, including reading the response body. Pass `--timeout <seconds>` to change that deadline, for example `portos-api post /api/music-video/autonomous @brief.json --timeout 3600`. A timeout closes the client connection and reports the elapsed limit; the server may still be working, so check the outcome before submitting the same operation again.
+
Plain `curl` works too:
```bash
diff --git a/scripts/portos-api.js b/scripts/portos-api.js
index ab5fff0f60..2292104fa5 100644
--- a/scripts/portos-api.js
+++ b/scripts/portos-api.js
@@ -24,18 +24,22 @@
*/
import { readFile } from 'node:fs/promises';
+import { request as httpRequest } from 'node:http';
+import { request as httpsRequest } from 'node:https';
import { resolveAgentKeyFile } from '../lib/agentKeyFile.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
const DEFAULT_URL = 'http://127.0.0.1:5555';
+export const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete']);
const PRIORITIES = new Set(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']);
export const USAGE = `Usage:
- portos-api whoami
- portos-api <get|post|put|patch|delete> <path> [json | @file | -]
- portos-api task "<description>" [--app <id>] [--priority LOW|MEDIUM|HIGH|CRITICAL] [--context "<note>"]
+ portos-api whoami [--timeout <seconds>]
+ portos-api <get|post|put|patch|delete> <path> [json | @file | -] [--timeout <seconds>]
+ portos-api task "<description>" [--app <id>] [--priority LOW|MEDIUM|HIGH|CRITICAL] [--context "<note>"] [--timeout <seconds>]
+Requests wait up to 30 minutes by default, including the response body.
Discover endpoints: portos-api get /api/api-docs/catalog.json`;
/** `/cos/tasks` → `/api/cos/tasks`; `/api/...` and `/data/...` pass through. */
@@ -67,12 +71,18 @@ const splitFlags = (args) => {
* read.
*/
export const parseArgs = (argv) => {
- const [command, ...rest] = argv;
+ const [command, ...args] = argv;
if (!command || command === '--help' || command === '-h' || command === 'help') return { help: true };
- if (command === 'whoami') return { method: 'GET', path: '/api/auth/whoami', body: null };
+ const { flags, positional: rest } = splitFlags(args);
+ const timeout = {};
+ if (flags.timeout !== undefined) {
+ const seconds = Number(flags.timeout);
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds * 1000 > 2 ** 31 - 1) throw new Error('--timeout must be positive seconds within the timer limit');
+ timeout.timeoutMs = seconds * 1000;
+ }
+ if (command === 'whoami') return { method: 'GET', path: '/api/auth/whoami', body: null, ...timeout };
if (command === 'task') {
- const { flags, positional } = splitFlags(rest);
- const description = positional.join(' ').trim();
+ const description = rest.join(' ').trim();
if (!description) throw new Error('task needs a description');
const task = { description };
if (flags.app) task.app = flags.app;
@@ -82,7 +92,7 @@ export const parseArgs = (argv) => {
if (!PRIORITIES.has(priority)) throw new Error(`--priority must be one of ${[...PRIORITIES].join(', ')}`);
task.priority = priority;
}
- return { method: 'POST', path: '/api/cos/tasks', body: JSON.stringify(task) };
+ return { method: 'POST', path: '/api/cos/tasks', body: JSON.stringify(task), ...timeout };
}
if (!METHODS.has(command.toLowerCase())) throw new Error(`Unknown command: ${command}`);
const [path, payload] = rest;
@@ -91,7 +101,7 @@ export const parseArgs = (argv) => {
if (payload === '-') body = { stdin: true };
else if (payload?.startsWith('@')) body = { file: payload.slice(1) };
else if (payload !== undefined) body = payload;
- return { method: command.toUpperCase(), path: normalizePath(path), body };
+ return { method: command.toUpperCase(), path: normalizePath(path), body, ...timeout };
};
/** `{ url, token }` from the environment and the key file (see header). */
@@ -119,28 +129,46 @@ const resolveBody = async (body) => {
return text;
};
-const main = async () => {
- const parsed = parseArgs(process.argv.slice(2));
+// Builtin HTTP has no hidden five-minute headers limit. One deadline covers
+// connection, headers and body, and destroying the request also closes its socket.
+const requestApi = (url, { method, headers, body, timeoutMs }) => {
+ const target = new URL(url);
+ if (!['http:', 'https:'].includes(target.protocol)) throw new Error('PORTOS_URL must use HTTP or HTTPS');
+ let timer;
+ return new Promise((resolve, reject) => {
+ const request = (target.protocol === 'https:' ? httpsRequest : httpRequest)(target, { method, headers }, (response) => {
+ const chunks = [];
+ response.on('data', (chunk) => chunks.push(chunk));
+ response.on('error', reject);
+ response.on('end', () => resolve({ status: response.statusCode, text: Buffer.concat(chunks).toString('utf8') }));
+ });
+ request.on('error', reject);
+ timer = setTimeout(() => request.destroy(new Error(`Request timed out after ${timeoutMs / 1000} seconds; server work may still be running.`)), timeoutMs);
+ request.end(body);
+ }).finally(() => clearTimeout(timer));
+};
+
+export const main = async (argv = process.argv.slice(2), env = process.env) => {
+ const parsed = parseArgs(argv);
if (parsed.help) {
console.log(USAGE);
return 0;
}
- const { url, token } = await resolveCredentials();
+ const { url, token } = await resolveCredentials(env);
const body = await resolveBody(parsed.body);
const headers = { Accept: 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
if (body !== null) headers['Content-Type'] = 'application/json';
- const res = await fetch(`${url}${parsed.path}`, { method: parsed.method, headers, body });
- const text = await res.text();
+ const { status, text } = await requestApi(`${url}${parsed.path}`, { method: parsed.method, headers, body, timeoutMs: parsed.timeoutMs ?? DEFAULT_TIMEOUT_MS });
let out = text;
try { out = JSON.stringify(JSON.parse(text), null, 2); } catch { /* not JSON: print as-is */ }
- if (res.ok) {
+ if (status >= 200 && status < 300) {
if (out) console.log(out);
return 0;
}
- console.error(`❌ ${parsed.method} ${parsed.path} → ${res.status}`);
+ console.error(`❌ ${parsed.method} ${parsed.path} → ${status}`);
if (out) console.error(out);
- if (res.status === 401 && !token) {
+ if (status === 401 && !token) {
console.error('No credential found. Turn on Settings > Security > Agent API key in PortOS, or set PORTOS_API_TOKEN.');
}
return 1;
diff --git a/scripts/portos-api.test.js b/scripts/portos-api.test.js
index 26e922e295..adff96d35d 100644
--- a/scripts/portos-api.test.js
+++ b/scripts/portos-api.test.js
@@ -3,11 +3,12 @@
* that never reaches the request, or a path missing its /api prefix) and which
* credential wins when both the spawn env and the key file are present.
*/
-import { describe, it, expect, afterEach } from 'vitest';
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import { createServer } from 'node:http';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
-import { parseArgs, resolveCredentials } from './portos-api.js';
+import { main, parseArgs, resolveCredentials } from './portos-api.js';
describe('parseArgs', () => {
it('builds a CoS task from the task shorthand', () => {
@@ -29,6 +30,89 @@ describe('parseArgs', () => {
expect(() => parseArgs(['task', 'x', '--priority', 'urgent'])).toThrow(/priority/);
expect(() => parseArgs(['fetch', '/api/x'])).toThrow(/Unknown command/);
expect(() => parseArgs(['post'])).toThrow(/needs a path/);
+ for (const timeout of ['0', '-1', 'NaN', 'Infinity', '2147484']) {
+ expect(() => parseArgs(['get', '/api/x', '--timeout', timeout])).toThrow(/--timeout/);
+ }
+ });
+
+ it('accepts a seconds deadline for every command without putting it into the task body', () => {
+ expect(parseArgs(['get', '/api/x', '--timeout', '3600']).timeoutMs).toBe(3_600_000);
+ expect(parseArgs(['whoami', '--timeout', '10']).timeoutMs).toBe(10_000);
+ const task = parseArgs(['task', 'Example task', '--timeout', '60']);
+ expect(task.timeoutMs).toBe(60_000);
+ expect(JSON.parse(task.body)).toEqual({ description: 'Example task' });
+ });
+});
+
+describe('API request lifecycle', () => {
+ let server;
+ afterEach(async () => {
+ server?.closeAllConnections();
+ if (server?.listening) await new Promise(resolve => server.close(resolve));
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('waits beyond five minutes for headers and body, then enforces and cleans up an explicit deadline', async () => {
+ // Advance only the request deadline; a real local HTTP socket exercises the transport.
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ let received;
+ const nextRequest = () => new Promise(resolve => { received = resolve; });
+ server = createServer((request, response) => {
+ const chunks = [];
+ request.on('data', chunk => chunks.push(chunk));
+ request.on('end', () => received({ request, response, body: Buffer.concat(chunks).toString('utf8') }));
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const env = {
+ PORTOS_URL: `http://127.0.0.1:${server.address().port}`,
+ PORTOS_API_TOKEN: 'synthetic-agent-token',
+ PORTOS_AGENT_KEY_FILE: join(tmpdir(), 'portos-missing-key.json'),
+ };
+ const incoming = nextRequest();
+ let complete = false;
+ const command = main(['post', '/api/example', '{"example":true}'], env).then(code => { complete = true; return code; });
+ const { request, response, body } = await incoming;
+ expect(request.headers.authorization).toBe('Bearer synthetic-agent-token');
+ expect(request.headers['content-type']).toBe('application/json');
+ expect(body).toBe('{"example":true}');
+ await vi.advanceTimersByTimeAsync(300_001);
+ expect(complete).toBe(false);
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.write('{"done":');
+ await vi.advanceTimersByTimeAsync(300_001);
+ expect(complete).toBe(false);
+ response.end('true}');
+ await expect(command).resolves.toBe(0);
+ expect(log).toHaveBeenCalledWith(JSON.stringify({ done: true }, null, 2));
+ expect(vi.getTimerCount()).toBe(0);
+
+ const stalled = nextRequest();
+ const timeout = expect(main(['get', '/api/example', '--timeout', '30'], env))
+ .rejects.toThrow('Request timed out after 30 seconds; server work may still be running.');
+ const pending = await stalled;
+ pending.response.writeHead(200);
+ pending.response.write('unfinished body');
+ await vi.advanceTimersByTimeAsync(30_000);
+ await timeout;
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reports a refusal and missing credentials without presenting it as a transport failure', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ server = createServer((_request, response) => {
+ response.writeHead(401, { 'Content-Type': 'application/json' });
+ response.end('{"code":"AUTH_REQUIRED"}');
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ await expect(main(['whoami'], {
+ PORTOS_URL: `http://127.0.0.1:${server.address().port}`,
+ PORTOS_AGENT_KEY_FILE: join(tmpdir(), 'portos-missing-key.json'),
+ })).resolves.toBe(1);
+ expect(error).toHaveBeenCalledWith('❌ GET /api/auth/whoami → 401');
+ expect(error).toHaveBeenCalledWith(expect.stringContaining('AUTH_REQUIRED'));
+ expect(error).toHaveBeenCalledWith(expect.stringContaining('No credential found'));
});
});
diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.js
index 7d720bb910..2ed5f6b991 100644
--- a/server/services/musicVideo/documentGeneration.js
+++ b/server/services/musicVideo/documentGeneration.js
@@ -310,9 +310,9 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =
};
const promptFor = (batchIds) => {
const sections = context.song.sections.filter((section) => batchIds.includes(section.id));
- // Only the scenes (and storyboard shots) a batch's sections cover: a long storyboard would
- // otherwise put every shot in each batch and push it past a local model's budget.
- const scoped = batchIds.length < ids.length;
+ // Section regenerates and partial batches need only their overlapping scenes and shots.
+ // A whole-song request retains all of its direction context.
+ const scoped = Boolean(sectionId) || batchIds.length < ids.length;
const scenes = scoped ? batchScenes(context.scenes, sections) : context.scenes;
return buildMixedMediaDocumentPrompt({
renderer: musicVideoDocumentRenderer(project), mediaMode: musicVideoMediaMode(project),
diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.js
index ab87b3afdd..8c35ce4933 100644
--- a/server/services/musicVideo/documentGeneration.test.js
+++ b/server/services/musicVideo/documentGeneration.test.js
@@ -404,15 +404,25 @@ describe('treatment-driven mixed-media document authoring', () => {
it('revises one section, preserves the other functions, and refuses a stale acceptance', async () => {
const id = await fixture();
const motionLanguage = 'Energy: playful. 0–10s unfold on downbeats; 20–30s expand the chorus gesture.';
- await projects.mutateProjectRecord(id, current => ({ project: { ...current, productionReview: { draft: { motionLanguage, implementationPlan: 'Hinged paper rig and analytic camera arc.' } } } }));
+ await projects.mutateProjectRecord(id, current => ({ project: { ...current, productionReview: { draft: {
+ motionLanguage, implementationPlan: 'Hinged paper rig and analytic camera arc.',
+ storyboard: ['s-intro', 's-still', 's-clip'].map((sceneId) => ({ sceneId, action: `choreography for ${sceneId}` })),
+ } } } }));
const first = (await generateMixedMediaDocument(id)).document;
expect(h.prompt).toContain(motionLanguage);
+ for (const sceneId of ['s-intro', 's-still', 's-clip']) expect(h.prompt).toContain(`choreography for ${sceneId}`);
const before = await manifestAt(first);
h.response = response({ still: '#00ff00' });
const second = (await regenerateMixedMediaSection(id, 'still', { expectedDraft: first.directory })).document;
const after = await manifestAt(second);
expect(h.prompt).toContain(motionLanguage);
expect(h.prompt).toContain('Hinged paper rig and analytic camera arc.');
+ expect(h.prompt).toContain('choreography for s-still');
+ expect(h.prompt).toContain('"sceneId":"s-still"');
+ for (const sceneId of ['s-intro', 's-clip']) {
+ expect(h.prompt).not.toContain(`choreography for ${sceneId}`);
+ expect(h.prompt).not.toContain(`"sceneId":"${sceneId}"`);
+ }
expect(after.sections.map((s) => s.source)).toEqual([before.sections[0].source, source('#00ff00'), before.sections[2].source]);
await expect(regenerateMixedMediaSection(id, 'still', { expectedDraft: first.directory })).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });
await projects.mutateProjectRecord(id, (current) => ({ project: {