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

Handle AI provider fallback signals

Adam Eivy9356c5bb0125
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index f1b26e80d7..8155f12870 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -33,7 +33,7 @@ const ERROR_PATTERNS = [
suggestedFix: 'Wait and retry - temporary rate limiting'
},
{
- pattern: /(?:hit your usage limit|You've hit your limit|usage limit|Upgrade to Pro)/i,
+ pattern: /(?:hit your usage limit|You've hit your limit|usage limit|Upgrade to Pro|(?:^|\n)\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$))/i,
category: ERROR_CATEGORIES.USAGE_LIMIT,
requiresFallback: true,
actionable: true,
@@ -78,6 +78,15 @@ const WAIT_TIME_PATTERNS = [
/(\d+\s*day(?:s)?)?[,\s]*(\d+\s*hour(?:s)?)?[,\s]*(\d+\s*min(?:ute)?(?:s)?)?/i
];
+const IMMEDIATE_FALLBACK_SIGNALS = [
+ {
+ pattern: /^\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$)/im,
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ message: 'Provider switched to extra usage',
+ suggestedFix: 'Provider usage limit reached. Using fallback provider or wait for limit reset.'
+ }
+];
+
export function extractWaitTime(text) {
if (!text) return null;
@@ -151,6 +160,40 @@ export function analyzeError(errorText, exitCode = null) {
};
}
+export function detectImmediateFallbackSignal(text) {
+ if (!text) return null;
+ const value = String(text);
+
+ for (const signal of IMMEDIATE_FALLBACK_SIGNALS) {
+ const match = value.match(signal.pattern);
+ if (!match) continue;
+
+ const line = match[0].trim();
+ return {
+ hasError: true,
+ category: signal.category,
+ message: line || signal.message,
+ waitTime: extractWaitTime(value),
+ requiresFallback: true,
+ actionable: true,
+ suggestedFix: signal.suggestedFix
+ };
+ }
+
+ return null;
+}
+
+export function createImmediateFallbackSignalDetector({ maxBuffer = 512 } = {}) {
+ let buffer = '';
+ const cap = Number.isFinite(maxBuffer) && maxBuffer > 0 ? maxBuffer : 512;
+
+ return (chunk) => {
+ if (!chunk) return null;
+ buffer = `${buffer}${String(chunk)}`.slice(-cap);
+ return detectImmediateFallbackSignal(buffer);
+ };
+}
+
function extractErrorMessage(text) {
if (!text) return '';
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index e304d94fa2..71d4794c0f 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -2,6 +2,8 @@ import { describe, it, expect } from 'vitest';
import {
analyzeError,
analyzeHttpError,
+ createImmediateFallbackSignalDetector,
+ detectImmediateFallbackSignal,
extractWaitTime,
ERROR_CATEGORIES
} from './errorDetection.js';
@@ -28,6 +30,19 @@ describe('Error Detection', () => {
expect(result.requiresFallback).toBe(true);
});
+ it('should detect Claude extra-usage status as a usage limit', () => {
+ const result = analyzeError('Now using extra usage');
+ expect(result.hasError).toBe(true);
+ expect(result.category).toBe(ERROR_CATEGORIES.USAGE_LIMIT);
+ expect(result.requiresFallback).toBe(true);
+ });
+
+ it('should not detect ordinary prose about extra usage as a usage limit', () => {
+ const result = analyzeError('The report mentions extra usage in the appendix.', 1);
+ expect(result.hasError).toBe(true);
+ expect(result.category).toBe(ERROR_CATEGORIES.UNKNOWN);
+ });
+
it('should extract wait time from usage limit errors', () => {
const result = analyzeError("You've hit your usage limit. Upgrade to Pro or try again in 1 day 1 hour 33 minutes");
expect(result.waitTime).toBeTruthy();
@@ -85,6 +100,37 @@ describe('Error Detection', () => {
});
});
+ describe('detectImmediateFallbackSignal', () => {
+ it('detects the Claude extra-usage status line', () => {
+ const result = detectImmediateFallbackSignal('Now using extra usage');
+ expect(result).toMatchObject({
+ hasError: true,
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ requiresFallback: true
+ });
+ });
+
+ it('does not match quoted prompt text in the middle of a line', () => {
+ const result = detectImmediateFallbackSignal('The failure condition is "Now using extra usage".');
+ expect(result).toBeNull();
+ });
+
+ it('does not match a line that only starts with the status text', () => {
+ const result = detectImmediateFallbackSignal('Now using extra usage examples in docs\n');
+ expect(result).toBeNull();
+ });
+
+ it('buffers the status line across stream chunks', () => {
+ const detect = createImmediateFallbackSignalDetector();
+ expect(detect('Now using extra ')).toBeNull();
+ const result = detect('usage\n');
+ expect(result).toMatchObject({
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ requiresFallback: true
+ });
+ });
+ });
+
describe('extractWaitTime', () => {
it('should extract "X day X hour X minutes" format', () => {
const result = extractWaitTime('try again in 1 day 2 hours 30 minutes');
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index b897fb1c59..e45f458971 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -30,6 +30,7 @@ import { spawn as ptySpawn } from 'node-pty';
import { join, resolve } from 'path';
import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';
import { createStreamingAnsiStripper } from './ansiStrip.js';
+import { createImmediateFallbackSignalDetector } from './aiToolkit/errorDetection.js';
import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun } from '../services/runner.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
@@ -177,6 +178,7 @@ ${prompt}`;
let lastOutputAt = startTime;
let firstResponseAt = null;
let finalized = false;
+ const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
// True once outputBuffer overflowed OUTPUT_BUFFER_HEADROOM and the head was
// dropped. We warn once and surface it in the run record so /runs can flag
// responses where the fallback path may have lost the start.
@@ -249,6 +251,17 @@ ${prompt}`;
}
}
onData?.(stripped);
+
+ const fallbackSignal = detectImmediateFallbackSignal(stripped);
+ if (fallbackSignal) {
+ finish({
+ success: false,
+ exitCode: 1,
+ error: fallbackSignal.message || 'Provider requires fallback',
+ reason: 'fallback-signal'
+ });
+ return;
+ }
}
const now = Date.now();
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
index f75a2da736..09905c4d3f 100644
--- a/server/lib/tuiPromptRunner.test.js
+++ b/server/lib/tuiPromptRunner.test.js
@@ -433,6 +433,32 @@ describe('executeTuiRun', () => {
}));
});
+ it('early-fails with reason "fallback-signal" when Claude switches to extra usage', async () => {
+ const provider = { id: 'claude', type: 'tui', command: 'claude' };
+ const onComplete = vi.fn();
+ const promise = executeTuiRun('run-extra-usage', provider, 'a prompt long enough', '/cwd', undefined, onComplete, 60000);
+ await flushAsync();
+
+ ptyInstances[0].emitData('Now using extra ');
+ expect(ptyInstances[0].kill).not.toHaveBeenCalled();
+ ptyInstances[0].emitData('usage\n');
+
+ await promise;
+ expect(ptyInstances[0].kill).toHaveBeenCalled();
+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({
+ runId: 'run-extra-usage',
+ success: false,
+ exitCode: 1,
+ error: expect.stringContaining('Now using extra usage'),
+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),
+ }));
+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({
+ success: false,
+ error: expect.stringContaining('Now using extra usage'),
+ completionReason: 'fallback-signal',
+ }));
+ });
+
it('finishes with reason "exit" + exitCode 0 when the PTY closes cleanly', async () => {
const provider = { id: 'claude', type: 'tui', command: 'echo' };
const promise = executeTuiRun('run-exit', provider, 'a prompt long enough', '/cwd', undefined, undefined, 60000);
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 3ef5998fb6..cb021199d7 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -23,6 +23,7 @@ import { normalizeReviewers, DEFAULT_REVIEW_STOP_MODE } from '../lib/validation.
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
+import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
const AGENTS_DIR = PATHS.cosAgents;
@@ -411,6 +412,22 @@ export async function spawnDirectly({
const isStreamJson = cliConfig.streamFormat === 'stream-json';
const streamParser = isStreamJson ? createStreamJsonParser() : null;
const codexStderrFormatter = provider.id === 'codex' ? createCodexStderrFormatter(prompt) : null;
+ let immediateFallbackAnalysis = null;
+ const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
+
+ const stopForImmediateFallbackSignal = (text) => {
+ if (immediateFallbackAnalysis || claudeProcess.killed) return;
+ const analysis = detectImmediateFallbackSignal(text);
+ if (!analysis) return;
+ immediateFallbackAnalysis = analysis;
+ emitLog('warn', `Agent ${agentId} detected provider fallback signal (${analysis.category}); stopping ${provider.name || provider.id}`, {
+ agentId,
+ taskId: task.id,
+ providerId: provider.id,
+ category: analysis.category
+ });
+ claudeProcess.kill('SIGTERM');
+ };
// If no output after 3 seconds, transition from initializing to working to show progress
const initializationTimeout = setTimeout(async () => {
@@ -424,6 +441,7 @@ export async function spawnDirectly({
claudeProcess.stdout.on('data', async (data) => {
try {
const text = data.toString();
+ stopForImmediateFallbackSignal(text);
if (!hasStartedWorking) {
hasStartedWorking = true;
@@ -455,6 +473,7 @@ export async function spawnDirectly({
claudeProcess.stderr.on('data', async (data) => {
try {
const text = data.toString();
+ stopForImmediateFallbackSignal(`[stderr] ${text}`);
// Codex stderr: show thinking + tool names, skip config dump and command output
if (codexStderrFormatter) {
const lines = codexStderrFormatter.processChunk(text);
@@ -560,7 +579,7 @@ export async function spawnDirectly({
// Use raw stream buffer for error analysis (contains full JSON with error details)
const analysisBuffer = rawStreamBuffer || outputBuffer;
- const errorAnalysis = finalSuccess ? null : analyzeAgentFailure(analysisBuffer, task, model);
+ const errorAnalysis = finalSuccess ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));
// try/finally so a throw from finalizeAgent still runs the local
// cleanup (worktree, pid unregister, activeAgents delete). Mirrors the
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index cc68efdbb5..6bc8b660f0 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -62,7 +62,7 @@ export const ERROR_PATTERNS = [
},
{
// Catches both "hit your usage limit" and session limits like "hit your limit · resets 6am"
- pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit)/i,
+ pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit|(?:^|\n)\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$))/i,
category: 'usage-limit',
actionable: true, // Need to switch provider
extract: (match, output) => {
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index b7bb3b2c66..83d2f56f3f 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -16,4 +16,44 @@ describe('analyzeAgentFailure', () => {
expect(analysis.message).toContain('gpt-5');
expect(analysis.suggestedFix).toContain('provider model configuration');
});
+
+ it('classifies Claude extra-usage status as a usage-limit fallback condition', () => {
+ const output = [
+ 'Claude Code starting...',
+ ...Array.from({ length: 60 }, (_, i) => `setup line ${i}`),
+ 'Now using extra usage'
+ ].join('\n');
+
+ const analysis = analyzeAgentFailure(output, { id: 'task-2' }, 'claude-opus');
+
+ expect(analysis.category).toBe('usage-limit');
+ expect(analysis.requiresFallback).toBe(true);
+ expect(analysis.suggestedFix).toContain('fallback provider');
+ });
+
+ it('does not classify ordinary prose about extra usage as a usage-limit fallback condition', () => {
+ const output = [
+ 'The task failed while editing docs.',
+ 'The draft mentions extra usage examples in a billing section.',
+ 'Error: markdown validation failed'
+ ].join('\n');
+
+ const analysis = analyzeAgentFailure(output, { id: 'task-3' }, 'claude-opus');
+
+ expect(analysis.category).not.toBe('usage-limit');
+ expect(analysis.requiresFallback).toBeUndefined();
+ });
+
+ it('does not classify status-line prefixes as usage-limit fallback conditions', () => {
+ const output = [
+ 'The task failed while editing docs.',
+ 'Now using extra usage examples in release notes',
+ 'Error: markdown validation failed'
+ ].join('\n');
+
+ const analysis = analyzeAgentFailure(output, { id: 'task-4' }, 'claude-opus');
+
+ expect(analysis.category).not.toBe('usage-limit');
+ expect(analysis.requiresFallback).toBeUndefined();
+ });
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index b42366d0a5..4674ce84fa 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -19,6 +19,7 @@ import { activeAgents, userTerminatedAgents } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { resolveCliModel } from '../lib/providerModels.js';
import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';
+import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
DEFAULT_TUI_IDLE_TIMEOUT_MS,
@@ -194,6 +195,8 @@ export async function spawnTuiAgent({
let outputBuffer = '';
let finalized = false;
+ let immediateFallbackAnalysis = null;
+ const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
// Guards ingestDoneSentinel to a single read. finish() is its only caller and
// is itself guarded by `finalized`, so this is defensive — it pins the
// read-at-most-once invariant at the helper.
@@ -439,7 +442,7 @@ export async function spawnTuiAgent({
// fall back to outputBuffer (which has the spawn-startup notices).
const errorAnalysis = finalSuccess
? null
- : analyzeAgentFailure(rawAnalysisText ?? outputBuffer, task, model);
+ : (immediateFallbackAnalysis || analyzeAgentFailure(rawAnalysisText ?? outputBuffer, task, model));
// try/finally so a throw from finalizeAgent (e.g. processAgentCompletion
// hook crash) still runs the local cleanup — sentinel removal, worktree
@@ -503,6 +506,7 @@ export async function spawnTuiAgent({
// The String(...) coerces defensively in case a future caller wires
// a Buffer-emitting encoding.
const text = typeof data === 'string' ? data : String(data);
+ const stripped = streamingStrip(text);
pendingRawChunks.push(text);
scheduleRawFlush();
if (postPasteBuffer !== null) postPasteBuffer += text;
@@ -522,8 +526,21 @@ export async function spawnTuiAgent({
// path. We still spool the raw stream to raw.txt for error analysis
// on failure, and we detect early "command not found" so a missing
// binary fails fast instead of idling.
+ const fallbackSignal = detectImmediateFallbackSignal(stripped);
+ if (fallbackSignal) {
+ immediateFallbackAnalysis = fallbackSignal;
+ appendLine(`⚡ Provider fallback signal: ${fallbackSignal.message}`);
+ await finish({
+ success: false,
+ exitCode: 1,
+ error: fallbackSignal.message || 'Provider requires fallback',
+ reason: 'fallback-signal'
+ });
+ return;
+ }
+
if (!promptSentAt) {
- const lowerStripped = streamingStrip(text).toLowerCase();
+ const lowerStripped = stripped.toLowerCase();
if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {
// finish() uses try/finally internally: finalizeAgent errors re-throw after
// cleanup, so finish() can reject. The outer try/catch in handleData already
diff --git a/server/services/runner.js b/server/services/runner.js
index cb4d7e9181..7de64644d7 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -8,6 +8,7 @@ import { join } from 'path';
import { ensureDir, tryReadFile } from '../lib/fileUtils.js';
import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
import { buildCliArgs } from '../lib/cliProviderArgs.js';
+import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import {
setAIToolkitInstance,
getAIToolkitInstance,
@@ -153,12 +154,24 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDa
const startTime = Date.now();
let output = '';
+ let immediateFallbackAnalysis = null;
+ let childProcess = null;
+ const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
+
+ const abortForImmediateFallbackSignal = (text) => {
+ if (immediateFallbackAnalysis || childProcess.killed) return;
+ const analysis = detectImmediateFallbackSignal(text);
+ if (!analysis) return;
+ immediateFallbackAnalysis = analysis;
+ console.log(`⚡ Run ${runId} detected fallback signal (${analysis.category}); stopping ${provider.name || provider.id || provider.command}`);
+ childProcess.kill('SIGTERM');
+ };
// Build provider-specific args for stdin-based prompt delivery
const args = buildCliArgs(provider);
console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via stdin)`);
- const childProcess = spawn(provider.command, args, {
+ childProcess = spawn(provider.command, args, {
cwd: workspacePath,
env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
windowsHide: true
@@ -190,12 +203,14 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDa
const text = data.toString();
output += text;
onData?.(text);
+ abortForImmediateFallbackSignal(text);
});
childProcess.stderr?.on('data', (data) => {
const text = data.toString();
output += text;
onData?.(text);
+ abortForImmediateFallbackSignal(text);
});
childProcess.on('error', async (err) => {
@@ -236,7 +251,7 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDa
// Analyze errors if the run failed (delegate to toolkit's error detection)
if (!metadata.success && toolkit.services.errorDetection) {
- const errorAnalysis = toolkit.services.errorDetection.analyzeError(output, code);
+ const errorAnalysis = immediateFallbackAnalysis || toolkit.services.errorDetection.analyzeError(output, code);
metadata.error = errorAnalysis.message || `Process exited with code ${code}`;
metadata.errorCategory = errorAnalysis.category;
metadata.errorAnalysis = errorAnalysis;
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 640de3ceaf..49d57d4612 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -18,14 +18,15 @@ vi.mock('fs/promises', () => ({
const { spawn } = await import('child_process');
const runner = await import('./runner.js');
+const { analyzeError, ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');
const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedModel, emitRunStarted } = runner;
// Minimal toolkit stub that satisfies executeCliRun's expectations
-function fakeToolkit() {
+function fakeToolkit(errorDetection = null) {
return {
services: {
runner: { _portosActiveRuns: new Map() },
- errorDetection: null,
+ errorDetection,
},
};
}
@@ -97,6 +98,42 @@ describe('executeCliRun — Codex sentinel suppression', () => {
expect(modelIdx).toBeGreaterThanOrEqual(0);
expect(capturedArgs[modelIdx + 1]).toBe('o4-mini');
});
+
+ it('stops the CLI immediately when Claude switches to extra usage', async () => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+ setAIToolkit(fakeToolkit({ analyzeError }), { dataDir: '/tmp/test-runner' });
+
+ const provider = {
+ id: 'claude-code',
+ name: 'Claude Code',
+ command: 'claude',
+ args: [],
+ defaultModel: 'claude-opus-4-7',
+ timeout: 60000,
+ };
+
+ const completed = new Promise((resolve) => {
+ executeCliRun('run-extra-usage', provider, 'test prompt', '/workspace', undefined, resolve, 60000);
+ });
+
+ await Promise.resolve();
+ child.stderr.emit('data', Buffer.from('Now using extra '));
+ expect(child.kill).not.toHaveBeenCalled();
+ child.stderr.emit('data', Buffer.from('usage\n'));
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+
+ child.emit('close', null);
+ const metadata = await completed;
+ expect(metadata).toMatchObject({
+ success: false,
+ errorCategory: ERROR_CATEGORIES.USAGE_LIMIT,
+ errorAnalysis: expect.objectContaining({
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ requiresFallback: true,
+ }),
+ });
+ });
});
describe('buildCliArgs — claude-code defaultModel honoring', () => {