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

address review (codex): scope the terminal model-id signal to the one-shot TUI runner

[._.]/ Adam Eivy6fb5a5c994b1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 43be7cca52..c42654de99 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,6 @@
## Fixed
-- **A TUI run whose model id is rejected by the backend now fails (and falls back) instead of returning a screen-scrape of the error.** When a Claude Code TUI run hit a non-recoverable model-id rejection — e.g. a bare Anthropic id like `claude-opus-4-8` passed to a Bedrock-backed Claude Code, which answers `API Error (…): 400 The provided model identifier is invalid` and suggests `global.anthropic.…` — the TUI just sat at an unanswered prompt. The one-shot runner saw output go idle, marked the run `success`, and (no `tui-response.txt` having been written) scraped the error *screen* and returned it as the model's "response." Downstream that surfaced as a baffling failure: AI manuscript Reformat reported `AI reformat changed the wording` (its integrity guard correctly rejecting the screen garbage), while other TUI-backed stages silently consumed the noise. The runner's immediate-fallback detector now recognizes Claude Code's terminal model-id rejection (Bedrock 400 "model identifier is invalid" and Anthropic 404 `not_found_error`) and fails the run as `MODEL_NOT_FOUND`, so `runPromptThroughProvider` benches the provider and retries its configured fallback (e.g. `claude-code-tui` → `claude-code-bedrock`, whose Bedrock ids are valid) — turning a silent corruption into a transparent recovery, or, with no fallback, an actionable error. The signal is anchored on the literal `API Error` + a 400/404 status so an agent merely *printing* the phrase in its own output can't trip it, and only this terminal class fires (a retryable 429/500 Claude Code auto-retries is left alone). (`server/lib/aiToolkit/errorDetection.js`, `server/lib/tuiPromptRunner.js`)
+- **A TUI run whose model id is rejected by the backend now fails (and falls back) instead of returning a screen-scrape of the error.** When a Claude Code TUI run hit a non-recoverable model-id rejection — e.g. a bare Anthropic id like `claude-opus-4-8` passed to a Bedrock-backed Claude Code, which answers `API Error (…): 400 The provided model identifier is invalid` and suggests `global.anthropic.…` — the TUI just sat at an unanswered prompt. The one-shot runner saw output go idle, marked the run `success`, and (no `tui-response.txt` having been written) scraped the error *screen* and returned it as the model's "response." Downstream that surfaced as a baffling failure: AI manuscript Reformat reported `AI reformat changed the wording` (its integrity guard correctly rejecting the screen garbage), while other TUI-backed stages silently consumed the noise. The one-shot TUI runner now recognizes Claude Code's terminal model-id rejection (Bedrock 400 "model identifier is invalid" and Anthropic 404 `not_found_error`) and fails the run as `MODEL_NOT_FOUND`, so `runPromptThroughProvider` benches the provider and retries its configured fallback (e.g. `claude-code-tui` → `claude-code-bedrock`, whose Bedrock ids are valid) — turning a silent corruption into a transparent recovery, or, with no fallback, an actionable error. The check is line-anchored, requires the 400/404 to immediately follow the `API Error` prefix (so a retryable 429/500 Claude Code auto-retries is left alone), and is deliberately scoped to the one-shot runner — *not* the shared fallback detector the long-running agent spawn paths use, so an agent that merely echoes the error line in its own output (cat-ing a log, running the tests, investigating this very failure) can't have its run killed and misclassified. (`server/lib/aiToolkit/errorDetection.js`, `server/lib/tuiPromptRunner.js`)
- **The "Verify arc" hover tooltip on the series arc page no longer renders behind the nav.** The `VerifyScopeTooltip` panel in `ArcCanvas.jsx` was at `z-30`, which loses to the sidebar nav (`z-50`), so the tooltip's overflow was clipped under the nav. Bumped to `z-[60]` — the layer the app's other floating dropdowns use. (`client/src/components/pipeline/ArcCanvas.jsx`)
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index 7cce2e949e..bcdc41f125 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -109,37 +109,63 @@ const IMMEDIATE_FALLBACK_SIGNALS = [
category: ERROR_CATEGORIES.USAGE_LIMIT,
message: 'Provider switched to extra usage',
suggestedFix: 'Provider usage limit reached. Using fallback provider or wait for limit reset.'
- },
- {
- // Claude Code renders a non-recoverable *model id* rejection inline as
- // `⏺ API Error (<model>): 400 The provided model identifier is invalid…`
- // (Bedrock) or `API Error: 404 … not_found_error` (Anthropic) and then sits
- // at an unanswered prompt — it does NOT auto-retry the way it does a 429/500.
- // Without an early-fail signal the one-shot TUI runner idles out, reports
- // success, and scrapes the error screen as a bogus "response" (which then
- // trips downstream guards like the manuscript-reformat integrity check).
- //
- // Two precision constraints keep this from killing a long-running CoS agent
- // (the agent spawn paths also stop the run on this signal) that merely echoes
- // such a line in its OWN work output:
- // 1. Line-anchored (`^…/m`, like the `Now using extra usage` signal above)
- // — Claude Code prints the error on its own line, so the real signal is
- // at a line start (or the 512-char buffer's slice boundary, which `^`
- // also matches); a full error line quoted mid-sentence in agent prose
- // is not.
- // 2. The 400/404 status must immediately follow the `API Error[(model)]:`
- // prefix — so a retryable line like `API Error: 429 … 404 not found`
- // (whose 404 is incidental) does not match and a run Claude Code would
- // auto-retry isn't aborted.
- // Terminal + model-specific, so failing the run immediately (to fall back /
- // surface an actionable error) never aborts a run that would have recovered.
- pattern: /^\s*(?:⏺\s*)?API Error(?:\s*\([^)]*\))?:\s*(?:400|404)\b[^\n]{0,160}(?:model identifier is invalid|not[_\s]?found)/im,
- category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
- message: 'Provider rejected the configured model id',
- suggestedFix: 'The provider does not recognize this model id — check the model name/availability for this provider; retrying with a fallback model.'
}
];
+// Claude Code renders a non-recoverable *model id* rejection inline as
+// `⏺ API Error (<model>): 400 The provided model identifier is invalid…`
+// (Bedrock) or `API Error: 404 … not_found_error` (Anthropic) and then sits at an
+// unanswered prompt — it does NOT auto-retry the way it does a 429/500. Without an
+// early-fail signal the one-shot TUI runner idles out, reports success, and scrapes
+// the error screen as a bogus "response" (which then trips downstream guards like
+// the manuscript-reformat integrity check).
+//
+// This is DELIBERATELY NOT in IMMEDIATE_FALLBACK_SIGNALS: that detector is shared
+// by the long-running agent spawn paths (agentTuiSpawning / agentCliSpawning) and
+// the CLI runner, which stream arbitrary agent output through it. An agent that
+// legitimately prints this error line — `cat`-ing a prior run's output.txt, running
+// the error-detection tests, or investigating this very failure — commonly puts the
+// raw error at a LINE START, where line-anchoring alone wouldn't save it, and a
+// healthy run would be killed and misclassified MODEL_NOT_FOUND. So only the one-shot
+// TUI runner (tuiPromptRunner) consults this, via `createTerminalModelErrorDetector`:
+// it runs a single prompt whose only `API Error` rendering is Claude Code's own, so
+// the false-positive surface is negligible. CLI runs detect the same failure via the
+// process's non-zero exit code; they don't need an in-stream signal.
+//
+// Two precision constraints (belt-and-suspenders for the one-shot path):
+// 1. Line-anchored (`^…/m`) — the real signal is at a line start (or the
+// 512-char buffer's slice boundary, which `^` also matches).
+// 2. The 400/404 status must immediately follow the `API Error[(model)]:` prefix
+// — so a retryable `API Error: 429 … 404 not found` (incidental 404) is left
+// alone for Claude Code to auto-retry.
+const TERMINAL_MODEL_ERROR_PATTERN = /^\s*(?:⏺\s*)?API Error(?:\s*\([^)]*\))?:\s*(?:400|404)\b[^\n]{0,160}(?:model identifier is invalid|not[_\s]?found)/im;
+
+export function detectTerminalModelError(text) {
+ if (!text) return null;
+ const match = String(text).match(TERMINAL_MODEL_ERROR_PATTERN);
+ if (!match) return null;
+ return {
+ hasError: true,
+ category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
+ message: match[0].trim() || 'Provider rejected the configured model id',
+ waitTime: null,
+ requiresFallback: true,
+ actionable: true,
+ suggestedFix: 'The provider does not recognize this model id — check the model name/availability for this provider; retrying with a fallback model.'
+ };
+}
+
+export function createTerminalModelErrorDetector({ 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 detectTerminalModelError(buffer);
+ };
+}
+
export function extractWaitTime(text) {
if (!text) return null;
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index f5526fc08b..5080e1c542 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -3,7 +3,9 @@ import {
analyzeError,
analyzeHttpError,
createImmediateFallbackSignalDetector,
+ createTerminalModelErrorDetector,
detectImmediateFallbackSignal,
+ detectTerminalModelError,
extractWaitTime,
ERROR_CATEGORIES
} from './errorDetection.js';
@@ -157,8 +159,17 @@ describe('Error Detection', () => {
});
});
+ it('does NOT catch a terminal model-id rejection — that is scoped to the one-shot TUI runner, not the shared detector the agent paths use', () => {
+ // The agent spawn paths route arbitrary agent output through this shared
+ // detector; a model-id rejection must NOT fire here (it lives in
+ // detectTerminalModelError, consulted only by tuiPromptRunner).
+ expect(detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 400 The provided model identifier is invalid.')).toBeNull();
+ });
+ });
+
+ describe('detectTerminalModelError', () => {
it('detects Claude Code\'s terminal "model identifier is invalid" (Bedrock 400) error line', () => {
- const result = detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 400 The provided model identifier is invalid.. Try /model to switch to us.anthropic.claude-opus-4-1-20250805-v1:0.');
+ const result = detectTerminalModelError('⏺ API Error (claude-opus-4-8): 400 The provided model identifier is invalid.. Try /model to switch to us.anthropic.claude-opus-4-1-20250805-v1:0.');
expect(result).toMatchObject({
hasError: true,
category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
@@ -167,7 +178,7 @@ describe('Error Detection', () => {
});
it('detects an Anthropic 404 not_found_error model rejection', () => {
- const result = detectImmediateFallbackSignal('API Error: 404 {"type":"error","error":{"type":"not_found_error","message":"model: claude-9"}}');
+ const result = detectTerminalModelError('API Error: 404 {"type":"error","error":{"type":"not_found_error","message":"model: claude-9"}}');
expect(result).toMatchObject({
hasError: true,
category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
@@ -175,28 +186,28 @@ describe('Error Detection', () => {
});
});
- it('does NOT early-fail a recoverable 429/500 (Claude Code auto-retries those)', () => {
- expect(detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 429 rate limited, retrying…')).toBeNull();
- expect(detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 500 internal server error, retrying…')).toBeNull();
+ it('does NOT fire on a recoverable 429/500 (Claude Code auto-retries those)', () => {
+ expect(detectTerminalModelError('⏺ API Error (claude-opus-4-8): 429 rate limited, retrying…')).toBeNull();
+ expect(detectTerminalModelError('⏺ API Error (claude-opus-4-8): 500 internal server error, retrying…')).toBeNull();
+ });
+
+ it('does NOT fire on an agent merely printing the phrase without the API Error prefix', () => {
+ expect(detectTerminalModelError('The Bedrock backend says the model identifier is invalid when you pass a bare id.')).toBeNull();
});
- it('does NOT trip on an agent merely printing the phrase without the API Error prefix', () => {
- // A CoS agent editing this very fix would print "model identifier is invalid"
- // in its own output — that must not kill its run.
- expect(detectImmediateFallbackSignal('The Bedrock backend says the model identifier is invalid when you pass a bare id.')).toBeNull();
+ it('does NOT fire on a full error line quoted mid-sentence in prose (line-anchored)', () => {
+ expect(detectTerminalModelError('I fixed the `API Error (claude-opus-4-8): 400 The provided model identifier is invalid` bug in the runner.')).toBeNull();
});
- it('does NOT trip on a full error line quoted mid-sentence in agent prose (line-anchored)', () => {
- // A CoS agent summarizing the bug echoes the complete error line inside a
- // sentence — the agent spawn paths stop the run on this signal, so a
- // mid-line echo must not match (only a real line-start error does).
- expect(detectImmediateFallbackSignal('I fixed the `API Error (claude-opus-4-8): 400 The provided model identifier is invalid` bug in the runner.')).toBeNull();
+ it('does NOT fire on a retryable 429 line that incidentally contains 404 (status anchored to the prefix)', () => {
+ expect(detectTerminalModelError('API Error: 429 too many requests for the 404 page not found endpoint')).toBeNull();
});
- it('does NOT trip on a retryable 429 line that incidentally contains 404 (status anchored to the prefix)', () => {
- // The 400/404 must immediately follow the `API Error[(model)]:` prefix, so a
- // 429 whose body merely mentions "404 ... not found" stays a retry, not a fail.
- expect(detectImmediateFallbackSignal('API Error: 429 too many requests for the 404 page not found endpoint')).toBeNull();
+ it('buffers the error line across stream chunks', () => {
+ const detect = createTerminalModelErrorDetector();
+ expect(detect('⏺ API Error (claude-opus-4-8): 400 The provided ')).toBeNull();
+ const result = detect('model identifier is invalid.\n');
+ expect(result).toMatchObject({ category: ERROR_CATEGORIES.MODEL_NOT_FOUND, requiresFallback: true });
});
});
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index e3c255033c..54b8405497 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -37,7 +37,7 @@ import { spawn as ptySpawn } from 'node-pty';
import { join, resolve } from 'path';
import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';
import { createStreamingAnsiStripper, stripAnsi } from './ansiStrip.js';
-import { createImmediateFallbackSignalDetector } from './aiToolkit/errorDetection.js';
+import { createImmediateFallbackSignalDetector, createTerminalModelErrorDetector } from './aiToolkit/errorDetection.js';
import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun } from '../services/runner.js';
import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached } from '../services/shell.js';
import {
@@ -221,6 +221,12 @@ ${prompt}`;
let firstResponseAt = null;
let finalized = false;
const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
+ // One-shot-only: a terminal model-id rejection (Bedrock 400 / Anthropic 404)
+ // leaves the TUI idle at an unanswered prompt, so without this the run idles to
+ // a false success and the error screen is scraped as the "response". Scoped here
+ // (not in the shared fallback detector) so it can't kill a long-running agent
+ // that merely echoes the error line — see errorDetection.js for the rationale.
+ const detectTerminalModelError = createTerminalModelErrorDetector();
// 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.
@@ -326,7 +332,7 @@ ${prompt}`;
}
onData?.(stripped);
- const fallbackSignal = detectImmediateFallbackSignal(stripped);
+ const fallbackSignal = detectImmediateFallbackSignal(stripped) || detectTerminalModelError(stripped);
if (fallbackSignal) {
finish({
success: false,