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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(cos): respect Codex CLI model defaults
Adam Eivyfd9412b891d0
diff --git a/data.sample/providers.json b/data.sample/providers.jsonindex 3651b03dd8..6b330c585f 100644--- a/data.sample/providers.json+++ b/data.sample/providers.json@@ -40,11 +40,11 @@"type": "cli","command": "codex","args": [],- "models": ["gpt-5", "gpt-5-codex", "gpt-5.2"],- "defaultModel": "gpt-5.2",- "lightModel": "gpt-5",- "mediumModel": "gpt-5-codex",- "heavyModel": "gpt-5.2",+ "models": [],+ "defaultModel": null,+ "lightModel": null,+ "mediumModel": null,+ "heavyModel": null,"timeout": 300000,"enabled": true,"envVars": {}diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 7f06fd8040..e842a21bf3 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -16,6 +16,7 @@ import { existsSync } from 'fs';import http from 'http';import { Server as SocketServer } from 'socket.io';import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';const ROOT_DIR = PATHS.root;const STATE_FILE = join(PATHS.cos, 'runner-state.json');@@ -471,6 +472,8 @@ app.post('/spawn', async (req, res) => {// Detect if stream-json format is active (Claude CLI with streaming)const isStreamJson = spawnArgs.includes('stream-json');const streamParser = isStreamJson ? createStreamJsonParser() : null;+ const isCodexCli = basename(command).replace(/\.exe$/i, '') === 'codex';+ const codexStderrFormatter = isCodexCli ? createCodexStderrFormatter() : null;// Store in memoryactiveAgents.set(agentId, {@@ -481,6 +484,7 @@ app.post('/spawn', async (req, res) => {outputBuffer: '',rawStreamBuffer: '',streamParser,+ codexStderrFormatter,workspacePath: cwd});@@ -515,11 +519,18 @@ app.post('/spawn', async (req, res) => {// Handle stderrclaudeProcess.stderr.on('data', (data) => {- const text = `[stderr] ${data.toString()}`;const agent = activeAgents.get(agentId);- if (agent) {- agent.outputBuffer += text;+ if (agent?.codexStderrFormatter) {+ const lines = agent.codexStderrFormatter.processChunk(data.toString());+ for (const line of lines) {+ agent.outputBuffer += line + '\n';+ emitToServer('agent:output', { agentId, text: line + '\n' });+ }+ return;}++ const text = `[stderr] ${data.toString()}`;+ if (agent) agent.outputBuffer += text;emitToServer('agent:output', { agentId, text });});@@ -548,6 +559,13 @@ app.post('/spawn', async (req, res) => {agent.outputBuffer = finalResult;}}+ if (agent?.codexStderrFormatter) {+ const remaining = agent.codexStderrFormatter.flush();+ for (const line of remaining) {+ agent.outputBuffer += line + '\n';+ emitToServer('agent:output', { agentId, text: line + '\n' });+ }+ }const output = agent?.outputBuffer || '';diff --git a/server/lib/codexCliOutput.js b/server/lib/codexCliOutput.jsnew file mode 100644index 0000000000..19c566b1da--- /dev/null+++ b/server/lib/codexCliOutput.js@@ -0,0 +1,69 @@+const STARTUP_FIELD_RE = /^(workdir|model|provider|approval|sandbox|reasoning effort|reasoning summaries|session id):/i;+const RUNTIME_SIGNAL_RE = /^(ERROR:|exec\s+)/i;+const ERROR_SIGNAL_RE = /\b(invalid_request_error|not logged in|api key|unauthorized|forbidden|rate.?limit|quota exceeded|model .*not supported|billing|subscription)\b/i;++function shouldDropCodexLine(trimmed) {+ if (!trimmed) return true;+ if (trimmed === 'user') return true;+ if (/^-{4,}$/.test(trimmed)) return true;+ if (trimmed.startsWith('Reading prompt from stdin')) return true;+ if (trimmed.startsWith('OpenAI Codex v')) return true;+ if (STARTUP_FIELD_RE.test(trimmed)) return true;+ if (/WARN codex_analytics::client:/.test(trimmed)) return true;+ if (/WARN codex_core_plugins::manifest:/.test(trimmed)) return true;+ if (/WARN codex_core_skills::loader:/.test(trimmed)) return true;+ if (trimmed.startsWith('<') || trimmed.startsWith('{cFPWv:') || trimmed.includes('Cloudflare')) return true;+ return false;+}++function formatCodexRuntimeLine(trimmed) {+ if (trimmed.startsWith('exec ')) {+ const match = trimmed.match(/^exec\s+\S+\s+-lc\s+(['"])(.*?)\1/);+ const cmd = match ? match[2] : trimmed.split(' in /')[0];+ return `🔧 ${cmd}`;+ }+ if (trimmed.length > 300) return null;+ return trimmed;+}++export function createCodexStderrFormatter() {+ let lineBuffer = '';+ let sawRuntimeOutput = false;+ let suppressCommandOutput = false;++ const processLine = (line) => {+ const trimmed = line.trim();+ if (shouldDropCodexLine(trimmed)) return null;++ const isRuntimeSignal = RUNTIME_SIGNAL_RE.test(trimmed) || ERROR_SIGNAL_RE.test(trimmed);+ if (suppressCommandOutput && !isRuntimeSignal) return null;+ if (!sawRuntimeOutput && !isRuntimeSignal) return null;+ if (isRuntimeSignal) sawRuntimeOutput = true;+ if (trimmed.startsWith('exec ')) suppressCommandOutput = true;++ return formatCodexRuntimeLine(trimmed);+ };++ const processChunk = (rawData) => {+ const lines = [];+ lineBuffer += rawData;+ const parts = lineBuffer.split('\n');+ lineBuffer = parts.pop() || '';++ for (const part of parts) {+ const formatted = processLine(part);+ if (formatted) lines.push(formatted);+ }++ return lines;+ };++ const flush = () => {+ if (!lineBuffer) return [];+ const formatted = processLine(lineBuffer);+ lineBuffer = '';+ return formatted ? [formatted] : [];+ };++ return { processChunk, flush };+}diff --git a/server/lib/codexCliOutput.test.js b/server/lib/codexCliOutput.test.jsnew file mode 100644index 0000000000..799100a17b--- /dev/null+++ b/server/lib/codexCliOutput.test.js@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { createCodexStderrFormatter } from './codexCliOutput.js';++describe('createCodexStderrFormatter', () => {+ it('drops Codex startup prompt echo and keeps the real runtime error', () => {+ const formatter = createCodexStderrFormatter();++ const lines = formatter.processChunk(`Reading prompt from stdin...+OpenAI Codex v0.125.0 (research preview)+--------+workdir: /repo+model: gpt-5+provider: openai+approval: never+sandbox: workspace-write+reasoning effort: high+session id: abc+--------+user+PortOS intentionally omits authentication in this deployment.+Begin working now.+ERROR: {"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The 'gpt-5' model is not supported when using Codex with a ChatGPT account."}}+`);++ expect(lines).toEqual([+ 'ERROR: {"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The \'gpt-5\' model is not supported when using Codex with a ChatGPT account."}}'+ ]);+ });++ it('summarizes Codex exec lines without retaining command output', () => {+ const formatter = createCodexStderrFormatter();++ const lines = formatter.processChunk("exec bash -lc 'npm test' in /repo succeeded in 2s:\nlong command output\n");++ expect(lines).toEqual(['🔧 npm test']);+ });+});diff --git a/server/routes/scaffoldPortOS.js b/server/routes/scaffoldPortOS.jsindex ec226f9e29..d2c258a363 100644--- a/server/routes/scaffoldPortOS.js+++ b/server/routes/scaffoldPortOS.js@@ -362,11 +362,11 @@ export default defineConfig({type: 'cli',command: 'codex',args: [],- models: ['gpt-5', 'gpt-5-codex'],- defaultModel: 'gpt-5-codex',- lightModel: 'gpt-5',- mediumModel: 'gpt-5-codex',- heavyModel: 'gpt-5-codex',+ models: [],+ defaultModel: null,+ lightModel: null,+ mediumModel: null,+ heavyModel: null,timeout: 300000,enabled: true,envVars: {}diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex cd7be8f766..3cc6247704 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -23,6 +23,7 @@ import { processAgentCompletion } from './agentCompletion.js';import { persistSimplifySummaries } from './agentLifecycle.js';import { activeAgents, userTerminatedAgents } from './agentState.js';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';+import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';const AGENTS_DIR = PATHS.cosAgents;@@ -371,6 +372,7 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,const outputFile = join(agentDir, 'output.txt');const isStreamJson = cliConfig.streamFormat === 'stream-json';const streamParser = isStreamJson ? createStreamJsonParser() : null;+ const codexStderrFormatter = provider.id === 'codex' ? createCodexStderrFormatter() : null;// If no output after 3 seconds, transition from initializing to working to show progressconst initializationTimeout = setTimeout(async () => {@@ -413,26 +415,10 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,claudeProcess.stderr.on('data', async (data) => {const text = data.toString();// Codex stderr: show thinking + tool names, skip config dump and command output- if (provider.id === 'codex') {- for (const line of text.split('\n')) {- const trimmed = line.trim();- if (!trimmed) continue;- if (trimmed.startsWith('Reading prompt from stdin')) continue;- if (trimmed.startsWith('OpenAI Codex v')) continue;- if (trimmed.startsWith('succeeded in')) continue;- // Tool calls: show just the command, strip output after "succeeded"- if (trimmed.startsWith('exec ')) {- const match = trimmed.match(/^exec\s+\S+\s+-lc\s+(['"])(.*?)\1/);- const cmd = match ? match[2] : trimmed.split(' in /')[0];- const display = `🔧 ${cmd}`;- outputBuffer += display + '\n';- await appendAgentOutput(agentId, display);- continue;- }- // Skip long lines (command output like file contents, directory listings)- if (trimmed.length > 300) continue;- outputBuffer += trimmed + '\n';- await appendAgentOutput(agentId, trimmed);+ if (codexStderrFormatter) {+ for (const line of codexStderrFormatter.processChunk(text)) {+ outputBuffer += line + '\n';+ await appendAgentOutput(agentId, line);}await writeFile(outputFile, outputBuffer).catch(() => {});return;@@ -496,6 +482,12 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,outputBuffer = finalResult;}}+ if (codexStderrFormatter) {+ for (const line of codexStderrFormatter.flush()) {+ outputBuffer += line + '\n';+ await appendAgentOutput(agentId, line);+ }+ }// Release execution laneif (agentData?.laneName) {diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 25dadb7641..cc68efdbb5 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -31,6 +31,17 @@ export const ERROR_PATTERNS = [configuredModel: model})},+ {+ pattern: /(?:model:\s*)?["']?([A-Za-z0-9._:-]+)["']?\s+model is not supported|model\s+["']?([A-Za-z0-9._:-]+)["']?.*not supported/i,+ category: 'model-not-supported',+ actionable: true,+ extract: (match, output, task, model) => ({+ message: `Model "${match[1] || match[2] || model || 'configured model'}" is not supported`,+ suggestedFix: 'Update the provider model configuration or leave the model blank so the CLI can use its own configured default.',+ affectedModel: match[1] || match[2] || model,+ configuredModel: model+ })+ },{pattern: /API Error: 401|authentication|unauthorized/i,category: 'auth-error',@@ -392,6 +403,14 @@ export const ERROR_PATTERNS = [}];+function getFailureAnalysisWindow(output) {+ return output+ .split('\n')+ .filter(l => l.trim())+ .slice(-200)+ .join('\n');+}+/*** Analyze agent failure output and categorize the error.*/@@ -406,10 +425,12 @@ export function analyzeAgentFailure(output, task, model) {};}+ const analysisOutput = getFailureAnalysisWindow(output);+for (const errorDef of ERROR_PATTERNS) {- const match = output.match(errorDef.pattern);+ const match = analysisOutput.match(errorDef.pattern);if (match) {- const extracted = errorDef.extract(match, output, task, model);+ const extracted = errorDef.extract(match, analysisOutput, task, model);return {category: errorDef.category,actionable: errorDef.actionable,diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsnew file mode 100644index 0000000000..b7bb3b2c66--- /dev/null+++ b/server/services/agentErrorAnalysis.test.js@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';+import { analyzeAgentFailure } from './agentErrorAnalysis.js';++describe('analyzeAgentFailure', () => {+ it('classifies unsupported Codex model errors instead of matching prompt text', () => {+ const output = [+ 'Global instructions:',+ 'PortOS intentionally omits authentication in this deployment.',+ ...Array.from({ length: 220 }, (_, i) => `prompt line ${i}`),+ 'ERROR: {"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The \'gpt-5\' model is not supported when using Codex with a ChatGPT account."}}'+ ].join('\n');++ const analysis = analyzeAgentFailure(output, { id: 'task-1' }, 'gpt-5');++ expect(analysis.category).toBe('model-not-supported');+ expect(analysis.message).toContain('gpt-5');+ expect(analysis.suggestedFix).toContain('provider model configuration');+ });+});