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
bench a provider when the provider is what failed a CoS agent run
[._.]/ Adam Eivyff3334df96c5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6273e3720d..a0be3b4d4d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,6 +26,8 @@- **Updated documentation index and feature references.** Added missing feature deep dive links for Quota-burn automation (`QUOTA-BURN.md`), Three.js procedural 3D models (`THREEJS_MODELS.md`), Stacker News stewardship (`stacker-news.md`), and the PortDeck native companion app API contract (`COMPANION_APP_API.md`) across `README.md` and `docs/README.md`. Improved inline JSDoc comments for client and server utility modules.## Fixed+- **A provider that goes down mid-queue no longer takes every waiting task with it.** When an agent run failed because the *provider* failed, PortOS sidelined that provider only if the failure was a usage or rate limit. Every other provider-side failure — an expired credential, a refused account, an Antigravity install still waiting on Google to verify eligibility — left it marked healthy, so the next task off the queue picked the same provider and died the same way, and the next, and the next. The most visible version: `agy` reporting "We're finishing verifying your account eligibility… please try again shortly" would burn down a whole queue of tasks in about a minute, each in three seconds, with nothing to show for it. A failure the run can attribute to the provider itself now sidelines it for a cooldown scaled to the cause (minutes for a transient block, longer for something needing a human), which is what makes the retries land on a fallback provider instead of repeating the failure; the sideline expires on its own, so the provider comes back without anyone visiting settings. Failures that describe the *request* rather than the provider — a bad model id, a content refusal, an off-shape response — still never sideline anything, since the provider's other models are fine. And a failure diagnosed only by keyword-matching the agent's own transcript can't sideline a provider either; that takes a structured signal from the provider itself. One shared cooldown policy now answers this for both agent runs and one-shot prompts, which previously disagreed about how long the same failure was worth.+- **The Antigravity account-verification banner no longer blocks the task it interrupts.** PortOS recognized the banner and failed the run promptly rather than waiting out the idle reaper, but filed it as something a human had to fix — which blocked the task outright, over a condition whose own error message says it clears itself. It now takes the ordinary retry path, which (with the provider sidelined per the entry above) lands on a fallback rather than re-reading the same banner three seconds later.- **A `--model` you baked into a TUI provider's own arguments is now honored instead of silently overridden.** The CoS-agent TUI spawn path respected a hand-pinned `--model` for OpenCode providers only; for every other TUI it appended the UI's model choice as a *second* `--model` flag, and last-flag-wins meant your pin was quietly discarded (or the CLI rejected the duplicate outright). It now honors the pin for every provider, matching what the one-shot TUI path and the CLI path already did, and what the rest of the app documents. This only affects providers whose saved arguments hand-pin a model — no shipped provider does.- **The AI Providers page no longer offers "Refresh Models" on providers the server can't refresh.** The button's visibility was decided by a deny-list of command names that had drifted from the server's actual dispatch, so Codex and Kimi Code — both shipped providers — showed the button and produced an error toast on every click. It is now an allowlist mirroring that dispatch's real shape: routed on provider type first, then the same per-vendor tests the server applies — including that its TUI path, unlike its CLI path, never consults the provider name. A test walks every shipped provider against a transcription of the server dispatch, so the next provider added without a matching client branch fails there rather than in the UI. (One deliberate non-change: the server matches `claude`/`gemini` on the *exact* command string, so a renamed provider pointed at an absolute binary path still shows no button — widening both sides is tracked separately in #3616 rather than making the client optimistically disagree.)- **On a Bedrock box, a TUI provider that isn't Claude Code no longer has its model id rewritten.** Claude Code on AWS Bedrock needs region-prefixed model ids (`global.anthropic.claude-opus-5`), so PortOS rewrites bare Claude ids just-in-time when `CLAUDE_CODE_USE_BEDROCK` is set. That rewrite keyed only on the *model id* containing "claude" and was applied by default to every TUI provider — so any vendor that labels Anthropic models under its own ids got captured by it. Cursor is exactly that case: `claude-opus-5-thinking-high` would have been sent to Cursor's router as `global.anthropic.claude-opus-5-thinking-high`, an id it has never heard of. The rewrite now keys on the launch command actually being Claude Code, which is what it always meant. Two independent copies of that model-injection step (the one-shot TUI prompt path and the CoS-agent TUI spawn path) had already drifted apart on this; both now share one implementation, so the next provider can't be fixed in one and missed in the other. No shipped provider's behavior changes; a *custom* TUI provider running a non-`claude` binary against a claude-ish model id will stop being rewritten, which is the correct result for a non-Claude-Code binary.diff --git a/server/lib/README.md b/server/lib/README.mdindex da3278e125..8009dca324 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -99,6 +99,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `antigravity.js` | Antigravity (`agy`) CLI provider helpers — id/sentinel constants (`ANTIGRAVITY_CLI_ID`, `ANTIGRAVITY_CONFIGURED_DEFAULT`, `LEGACY_GEMINI_*`), `isAntigravityCommand`/`isAntigravityCliProvider` predicates, and `ensureAntigravityPrintArgs(args, {model, effort})`/`ensureAntigravityTuiArgs(args, {model, effort})`/`stripAntigravityUnsupportedArgs` argv normalizers. The strip drops legacy Gemini `--yolo`/`-m`/`--output-format` but PRESERVES the long `--model` (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject `--model`/`--effort` from the per-run overrides, always ahead of the trailing `--print` marker whose value is the prompt. || `aiProvider.js` | Shared AI provider utilities for LLM calls. || `promptRunner.js` | Shared LLM runner wrapper. |+| `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. || `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). || `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. || `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). |diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex d162628290..894c7c7b39 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -110,10 +110,20 @@ const IMMEDIATE_FALLBACK_SIGNALS = [// do no work until the idle reaper eventually kills it. This exact two-line// banner is provider chrome (not a generic auth word an agent may print),// making it safe to fail immediately and let the task select a fallback.+ //+ // NOT actionable: the account is fine and nothing in PortOS config is wrong+ // — Google is mid-verification and says so ("try again shortly"). Marking it+ // actionable would BLOCK the task outright (see+ // agentErrorAnalysis#resolveFailedTaskDecision) over a condition that clears+ // itself, so it takes the ordinary retry path instead. The host still+ // sidelines the provider for the auth-error cooldown (providerCooldown.js)+ // so that retry resolves onto a fallback rather than re-dying on the same+ // banner three seconds later.pattern: /We're finishing verifying your account eligibility\.\s*This usually takes a moment\. Please try again shortly\./i,category: ERROR_CATEGORIES.AUTH_ERROR,message: 'Antigravity account eligibility is still being verified',- suggestedFix: 'Wait for the Antigravity account verification to complete, or select another provider and retry.'+ suggestedFix: 'Antigravity account verification is still in progress — sidelining the provider briefly and retrying on a fallback.',+ actionable: false},{pattern: /^\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$)/im,@@ -265,8 +275,14 @@ export function detectImmediateFallbackSignal(text) {message: line || signal.message,waitTime: extractWaitTime(value),requiresFallback: true,- actionable: true,- suggestedFix: signal.suggestedFix+ // Signals are actionable-by-default (a human has to do something); a+ // signal opts out when the provider says the condition clears on its own.+ actionable: signal.actionable !== false,+ suggestedFix: signal.suggestedFix,+ // These banners are provider CHROME, not text an agent could have printed+ // — the host benches the provider on a provider-origin failure, so saying+ // so here is what routes the retry to a fallback (agentFinalization.js).+ origin: 'provider'};}diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex f4ebd174e5..f7650e1d8e 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -138,7 +138,25 @@ describe('Error Detection', () => {hasError: true,category: ERROR_CATEGORIES.AUTH_ERROR,requiresFallback: true,- suggestedFix: expect.stringContaining('verification')+ suggestedFix: expect.stringContaining('verification'),+ // The account is fine and no PortOS setting is wrong — Google is mid-+ // verification and says the condition clears itself. Actionable would+ // BLOCK the task (resolveFailedTaskDecision); provider origin is what+ // benches the provider so the retry resolves onto a fallback.+ actionable: false,+ origin: 'provider'+ });+ });++ // The banner is a repainted TUI screen, not a log: Antigravity emits the two+ // sentences on separate lines with a leading space from the erase-to-start+ // sequence. Fixture is the ANSI-STRIPPED shape observed in a real agy raw.txt+ // — the exact text the spawner's detector is fed.+ it('matches the banner as agy actually renders it (two lines, leading space)', () => {+ const rendered = " ⎿ We're finishing verifying your account eligibility.\n This usually takes a moment. Please try again shortly.\r\n";+ expect(detectImmediateFallbackSignal(rendered)).toMatchObject({+ category: ERROR_CATEGORIES.AUTH_ERROR,+ actionable: false});});@@ -158,6 +176,9 @@ describe('Error Detection', () => {category: ERROR_CATEGORIES.USAGE_LIMIT,requiresFallback: true});+ // Signals stay actionable-by-default; only a signal the provider says+ // clears itself opts out.+ expect(result.actionable).toBe(true);});it('does not match quoted prompt text in the middle of a line', () => {diff --git a/server/lib/index.js b/server/lib/index.jsindex baf2d1aea2..97672086f0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -113,6 +113,7 @@ export * from './promptPartials.js';export * from './promptRunner.js';export * from './promptSystemStages.js';export * from './promptTemplate.js';+export * from './providerCooldown.js';export * from './providerModels.js';// Namespaced: providerVendors.js re-exports `inferTuiCommand` /// `applyCommandDefaults` (from tuiHandshake.js) and `prepareCliPrompt` (fromdiff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex 771eb0e739..65f4631eee 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -32,6 +32,7 @@ import { executeTuiRun } from './tuiPromptRunner.js';import { ServerError } from './errorHandler.js';import { PROVIDER_TYPES } from './aiToolkit/constants.js';import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';+import { isSchemaTypeCategory, resolveProviderBench } from './providerCooldown.js';import { isGenerationModel } from './localModelHeuristics.js';import { getAIToolkitInstance } from './aiToolkitState.js';import { createSingleFlight } from './singleFlight.js';@@ -110,29 +111,6 @@ export async function withLocalConcurrencyGate(provider, fn) {}}-// Cooldown per error category — how long the failed provider is marked-// unavailable so subsequent calls skip it and proactively use the fallback.-// USAGE_LIMIT is absent because `markUsageLimit` parses the wait time-// from the error body (e.g. "resets 5pm"). Values target the timescale-// the user can plausibly recover the underlying cause:-// RATE_LIMIT — 5m: provider-side counter typically clears in minutes-// AUTH_ERROR — 15m: usually a config issue that needs human action-// MODEL_NOT_FOUND — 30m: also config; longer because retry is unlikely-// QUOTA_EXCEEDED — 60m: billing/credits; retry sooner is futile-// NETWORK_ERROR — 2m: usually a transient hiccup-// TIMEOUT/UNKNOWN — 1m: short enough to retry, long enough to skip-// while the immediate workload retries via fallback-const COOLDOWN_MS_BY_CATEGORY = {- [ERROR_CATEGORIES.RATE_LIMIT]: 5 * 60 * 1000,- [ERROR_CATEGORIES.AUTH_ERROR]: 15 * 60 * 1000,- [ERROR_CATEGORIES.MODEL_NOT_FOUND]: 30 * 60 * 1000,- [ERROR_CATEGORIES.QUOTA_EXCEEDED]: 60 * 60 * 1000,- [ERROR_CATEGORIES.NETWORK_ERROR]: 2 * 60 * 1000,- [ERROR_CATEGORIES.TIMEOUT]: 60 * 1000,- [ERROR_CATEGORIES.UNKNOWN]: 60 * 1000,-};-const DEFAULT_COOLDOWN_MS = 60 * 1000;-/*** Returns true when the runner+provider pair will actually honor a* per-call `model` override. For API providers the model is a@@ -243,15 +221,10 @@ export function pickConfigCorrectedModel(provider, failedModel) {// provider with a schema-strengthened prompt before the cascade escalates to a// Tier-3 fallback / Tier-4 investigation task.-// Categories the tiered cascade classifies as schema/type (mirrors-// autoFixer.CATEGORY_TO_TIER's SCHEMA_TYPE entries; kept LOCAL so promptRunner-// stays decoupled from the lazily-imported CoS stack — see loadAutoFixer). The-// synthetic response-schema failure below is tagged 'parse-error' so it lands-// in this tier when it re-enters the cascade.-const SCHEMA_TYPE_CATEGORIES = new Set([- 'parse-error', 'bad-request', 'context-length', 'output-length', 'build-error', 'lint-error',-]);-export const isSchemaTypeCategory = (category) => SCHEMA_TYPE_CATEGORIES.has(category);+// Re-exported from providerCooldown.js, which owns it alongside the cooldown+// table that consults it (the tier classification and the "don't bench a healthy+// provider over one off-shape response" rule are the same judgement).+export { isSchemaTypeCategory };// Deterministic instruction appended to the prompt on a schema/type re-request// when the caller declared a schema but supplied no custom `repair`. Names the@@ -1066,45 +1039,25 @@ async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalconst analysis = runnerAnalysis && typeof runnerAnalysis === 'object'? runnerAnalysis: analyzeError(errorMessage || '');- const category = analysis?.category || ERROR_CATEGORIES.UNKNOWN;- // A content/safety refusal is prompt-specific, not a provider outage — the- // provider is healthy and other prompts still work. Don't bench it (which- // would route every subsequent task to the fallback for a full cooldown);- // this single call still falls back via the caller's retry path.- //- // A model-not-found is REQUEST-specific the same way: the request named a- // model id the (reachable) endpoint doesn't have — a bad caller/config model,- // not the provider being down. Benching the whole provider would take its- // OTHER valid models offline for the full cooldown (e.g. one bad- // `codex-configured-default` vision call benching Ollama so a correct- // `qwen2.5vl` call then proactively swaps to a non-vision fallback). The- // single failing call still falls back via the retry path; the provider stays- // available for its working models. A genuine endpoint outage surfaces as- // NETWORK_ERROR, not MODEL_NOT_FOUND, so it is still benched.- //- // A schema/type failure (issue #2350) is likewise RESPONSE-specific, not a- // provider outage — the provider returned HTTP 200 with content that just- // didn't match this caller's declared schema. Benching it would take a healthy- // provider offline for every other caller over one off-shape response; the- // single failing call still fails over via Tier 3.- if (category === ERROR_CATEGORIES.CONTENT_REFUSAL- || category === ERROR_CATEGORIES.MODEL_NOT_FOUND- || isSchemaTypeCategory(category)) return;-- if (category === ERROR_CATEGORIES.USAGE_LIMIT) {+ // Request/response-specific categories (a content refusal, a bad model id, an+ // off-shape response) resolve to null — the provider is healthy and the single+ // failing call still falls back via the caller's retry path.+ const bench = resolveProviderBench(analysis);+ if (!bench) return;++ if (bench.marker === 'usage-limit') {await providerStatus.markUsageLimit(failed.id, {- message: analysis.message || errorMessage,- waitTime: analysis.waitTime,+ message: bench.message || errorMessage,+ waitTime: bench.waitTime,});return;}- const waitTimeMs = COOLDOWN_MS_BY_CATEGORY[category] ?? DEFAULT_COOLDOWN_MS;await providerStatus.markUnavailable(failed.id, {- reason: category,- message: analysis?.message || errorMessage || `Provider ${failed.name || failed.id} failed`,- waitTimeMs,+ reason: bench.category,+ message: bench.message || errorMessage || `Provider ${failed.name || failed.id} failed`,+ waitTimeMs: bench.waitTimeMs,});}diff --git a/server/lib/providerCooldown.js b/server/lib/providerCooldown.jsnew file mode 100644index 0000000000..2b1be61ad1--- /dev/null+++ b/server/lib/providerCooldown.js@@ -0,0 +1,100 @@+/**+ * Provider cooldown policy — "this run failed; should the provider be benched,+ * and for how long?"+ *+ * One answer, shared by both paths that can observe a provider failing:+ * - `promptRunner.js` (a one-shot prompt cascade), and+ * - `agentFinalization.js` (a finished CoS agent run).+ *+ * They used to disagree: the prompt path had this table, and the agent path+ * benched only usage/rate limits — so an `agy` TUI agent blocked on account+ * verification left the provider marked healthy and the next dequeued task+ * picked it again and died the same way. Keeping the policy here means a+ * category benches for the same duration no matter which path noticed.+ *+ * Pure — no I/O, no provider-status handle. Callers own the actual marking.+ */++import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';++// Cooldown per error category — how long the failed provider is marked+// unavailable so subsequent calls skip it and proactively use the fallback.+// USAGE_LIMIT is absent because `markUsageLimit` parses the wait time+// from the error body (e.g. "resets 5pm"). Values target the timescale+// the user can plausibly recover the underlying cause:+// RATE_LIMIT — 5m: provider-side counter typically clears in minutes+// AUTH_ERROR — 15m: usually a config issue that needs human action+// MODEL_NOT_FOUND — 30m: also config; longer because retry is unlikely+// QUOTA_EXCEEDED — 60m: billing/credits; retry sooner is futile+// NETWORK_ERROR — 2m: usually a transient hiccup+// TIMEOUT/UNKNOWN — 1m: short enough to retry, long enough to skip+// while the immediate workload retries via fallback+export const COOLDOWN_MS_BY_CATEGORY = {+ [ERROR_CATEGORIES.RATE_LIMIT]: 5 * 60 * 1000,+ [ERROR_CATEGORIES.AUTH_ERROR]: 15 * 60 * 1000,+ [ERROR_CATEGORIES.MODEL_NOT_FOUND]: 30 * 60 * 1000,+ [ERROR_CATEGORIES.QUOTA_EXCEEDED]: 60 * 60 * 1000,+ [ERROR_CATEGORIES.NETWORK_ERROR]: 2 * 60 * 1000,+ [ERROR_CATEGORIES.TIMEOUT]: 60 * 1000,+ [ERROR_CATEGORIES.UNKNOWN]: 60 * 1000,+};+export const DEFAULT_COOLDOWN_MS = 60 * 1000;++// Categories the tiered cascade classifies as schema/type (mirrors+// autoFixer.CATEGORY_TO_TIER's SCHEMA_TYPE entries; kept out of the CoS stack so+// promptRunner stays decoupled from it — see loadAutoFixer). promptRunner tags+// its synthetic response-schema failure 'parse-error' so it lands in this tier+// when it re-enters the cascade.+const SCHEMA_TYPE_CATEGORIES = new Set([+ 'parse-error', 'bad-request', 'context-length', 'output-length', 'build-error', 'lint-error',+]);+export const isSchemaTypeCategory = (category) => SCHEMA_TYPE_CATEGORIES.has(category);++/**+ * True when a failure is specific to the REQUEST or RESPONSE rather than the+ * provider, so benching the provider would take a healthy service offline for+ * every other caller.+ *+ * A content/safety refusal is prompt-specific — the provider is healthy and+ * other prompts still work. A model-not-found is likewise request-specific: the+ * request named a model id the (reachable) endpoint doesn't have, so benching+ * would take its OTHER valid models offline for the full cooldown (e.g. one bad+ * `codex-configured-default` vision call benching Ollama so a correct+ * `qwen2.5vl` call then proactively swaps to a non-vision fallback). A genuine+ * endpoint outage surfaces as NETWORK_ERROR, not MODEL_NOT_FOUND, so it is still+ * benched. A schema/type failure (#2350) is response-specific: the provider+ * returned HTTP 200 with content that just didn't match this caller's declared+ * schema. In every case the single failing call still falls back via its+ * caller's retry path.+ */+export function isRequestSpecificCategory(category) {+ return category === ERROR_CATEGORIES.CONTENT_REFUSAL+ || category === ERROR_CATEGORIES.MODEL_NOT_FOUND+ || isSchemaTypeCategory(category);+}++/**+ * Decide how a failed provider should be benched.+ *+ * @param {object|null} analysis — an errorDetection / agentErrorAnalysis payload+ * @returns {null+ * | { marker: 'usage-limit', category: string, message: string|null, waitTime: string|null }+ * | { marker: 'unavailable', category: string, message: string|null, waitTimeMs: number }}+ * `null` means "don't bench". The `usage-limit` marker is distinct because+ * `markUsageLimit` parses its own wait window out of the provider's message.+ */+export function resolveProviderBench(analysis) {+ const category = analysis?.category || ERROR_CATEGORIES.UNKNOWN;+ if (isRequestSpecificCategory(category)) return null;++ const message = analysis?.message || null;+ if (category === ERROR_CATEGORIES.USAGE_LIMIT) {+ return { marker: 'usage-limit', category, message, waitTime: analysis?.waitTime ?? null };+ }+ return {+ marker: 'unavailable',+ category,+ message,+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY[category] ?? DEFAULT_COOLDOWN_MS,+ };+}diff --git a/server/lib/providerCooldown.test.js b/server/lib/providerCooldown.test.jsnew file mode 100644index 0000000000..ba01ebc9fd--- /dev/null+++ b/server/lib/providerCooldown.test.js@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest';++import {+ COOLDOWN_MS_BY_CATEGORY,+ DEFAULT_COOLDOWN_MS,+ isRequestSpecificCategory,+ isSchemaTypeCategory,+ resolveProviderBench,+} from './providerCooldown.js';++describe('isSchemaTypeCategory', () => {+ it('covers the tiered cascade\'s schema/type categories', () => {+ for (const c of ['parse-error', 'bad-request', 'context-length', 'output-length', 'build-error', 'lint-error']) {+ expect(isSchemaTypeCategory(c)).toBe(true);+ }+ expect(isSchemaTypeCategory('auth-error')).toBe(false);+ expect(isSchemaTypeCategory(undefined)).toBe(false);+ });+});++describe('isRequestSpecificCategory', () => {+ // These describe THIS request, not the provider — benching would take a+ // healthy service offline for every other caller.+ it('is true for refusals, bad model ids, and schema/type failures', () => {+ expect(isRequestSpecificCategory('content-refusal')).toBe(true);+ expect(isRequestSpecificCategory('model-not-found')).toBe(true);+ expect(isRequestSpecificCategory('parse-error')).toBe(true);+ });++ it('is false for the categories that mean the provider itself is down', () => {+ expect(isRequestSpecificCategory('auth-error')).toBe(false);+ expect(isRequestSpecificCategory('rate-limit')).toBe(false);+ expect(isRequestSpecificCategory('network-error')).toBe(false);+ });+});++describe('resolveProviderBench', () => {+ it('declines to bench a request-specific failure', () => {+ expect(resolveProviderBench({ category: 'content-refusal' })).toBeNull();+ expect(resolveProviderBench({ category: 'model-not-found' })).toBeNull();+ expect(resolveProviderBench({ category: 'output-length' })).toBeNull();+ });++ // markUsageLimit parses its own window out of the provider's message+ // ("resets 5pm"), so it gets a distinct marker rather than a flat cooldown.+ it('routes a usage limit to its own marker, carrying the parsed wait', () => {+ expect(resolveProviderBench({ category: 'usage-limit', message: 'hit your limit', waitTime: 'resets 5pm' })).toEqual({+ marker: 'usage-limit',+ category: 'usage-limit',+ message: 'hit your limit',+ waitTime: 'resets 5pm',+ });+ });++ it('resolves the per-category cooldown for a provider outage', () => {+ expect(resolveProviderBench({ category: 'auth-error', message: 'nope' })).toEqual({+ marker: 'unavailable',+ category: 'auth-error',+ message: 'nope',+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY['auth-error'],+ });+ });++ // Categories outside the table (agentErrorAnalysis carries its own, richer+ // set — 'forbidden', 'claude-error') still bench, just briefly.+ it('falls back to the default cooldown for an untabled category', () => {+ expect(resolveProviderBench({ category: 'forbidden' })).toMatchObject({+ marker: 'unavailable',+ waitTimeMs: DEFAULT_COOLDOWN_MS,+ });+ });++ it('treats a missing category as unknown rather than skipping the bench', () => {+ expect(resolveProviderBench(null)).toMatchObject({+ marker: 'unavailable',+ category: 'unknown',+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY.unknown,+ });+ });+});diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex d9e10900cb..a2e62107b6 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -23,6 +23,7 @@ import {INVESTIGATION_CIRCUIT_MAX_CREATIONS,__resetInvestigationCircuit} from './agentErrorAnalysis.js';+import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';import { API_ACCESS_ERROR_CATEGORIES } from './agentErrorAnalysis.js';import { ENVIRONMENTAL_ERROR_CATEGORIES } from './taskLearning/metrics.js';import { addTask, updateTask, getAllTasks } from './cos.js';@@ -263,6 +264,7 @@ describe('resolveFailedTaskDecision', () => {const decision = resolveFailedTaskDecision(task({ failureCount: 0 }), { actionable: true, category: 'bad-request', message: 'bad' });expect(decision.status).toBe('blocked');});+});describe('non-actionable errors with retry tracking', () => {@@ -278,6 +280,21 @@ describe('resolveFailedTaskDecision', () => {expect(decision.investigationAnalysis).toBeNull();});+ // The agy "we're still verifying your account eligibility" banner is an+ // auth-error, but a self-clearing one — blocking the task strands work that+ // would have succeeded minutes later on a fallback provider. The signal is+ // emitted non-actionable precisely so it lands here; this pins the two files+ // together (the analysis comes from the real detector).+ it('retries — does not block — the self-clearing Antigravity eligibility block', () => {+ const analysis = detectImmediateFallbackSignal(+ "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly."+ );+ expect(analysis.category).toBe('auth-error');+ const decision = resolveFailedTaskDecision(task(), analysis, { agentId: 'agent-y', now: HOLD_NOW });+ expect(decision.status).toBe('in_progress');+ expect(decision.investigationAnalysis).toBeNull();+ });+it('blocks once failureCount reaches MAX_TASK_RETRIES', () => {const decision = resolveFailedTaskDecision(task({ failureCount: MAX_TASK_RETRIES - 1 }), { actionable: false, category: 'network-error', message: 'Network failed' });expect(decision.status).toBe('blocked');diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 29cf13b0e5..c1a803b08a 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -27,7 +27,8 @@ import { emitLog } from './cosEvents.js';import { getAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';import { updateTask } from './cos.js';import { getActiveProvider } from './providers.js';-import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';+import { markProviderUsageLimit, markProviderUnavailable } from './providerStatus.js';+import { resolveProviderBench } from '../lib/providerCooldown.js';import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';@@ -617,20 +618,36 @@ export async function finalizeAgent({}if (!success && !terminatedByUser && errorAnalysis) {- // Lazy provider lookup — only resolve the active provider when a marker- // fires AND the caller didn't already know the id. This keeps the- // successful-completion hot path free of a settings-file read.- const markerProviderId = errorAnalysis.category === 'usage-limit' || errorAnalysis.category === 'rate-limit'- ? providerId || (await getActiveProvider())?.id- : null;- if (markerProviderId && errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {- await markProviderUsageLimit(markerProviderId, errorAnalysis).catch(err => {- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId: markerProviderId });- });- }- if (markerProviderId && errorAnalysis.category === 'rate-limit') {- await markProviderRateLimited(markerProviderId).catch(err => {- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId: markerProviderId });+ // Bench the provider when the PROVIDER is what failed — not the agent's+ // work. `origin: 'provider'` is agentErrorAnalysis's provenance flag (#2642),+ // set only for structured provider chrome, never for a loose keyword sweep of+ // a transcript the agent itself wrote. Without a bench the provider stays+ // "available", so the very next dequeue picks it again and dies identically:+ // that is how one `agy` account-verification block could take down a whole+ // queue of tasks in under a minute. `resolveProviderBench` (shared with+ // promptRunner) picks the window and declines to bench request-specific+ // failures; the cooldown then routes the retry to a fallback+ // (agentProviderResolution.js) and auto-expires without anyone intervening.+ const isProviderFault = errorAnalysis.origin === 'provider'+ || errorAnalysis.category === 'usage-limit'+ || errorAnalysis.category === 'rate-limit';+ const bench = isProviderFault ? resolveProviderBench(errorAnalysis) : null;+ // Lazy provider lookup — resolve the active provider only when a marker+ // fires AND the caller didn't already know the id, keeping the ordinary+ // failure path free of a settings-file read.+ const markerProviderId = bench ? providerId || (await getActiveProvider())?.id : null;+ if (markerProviderId) {+ // `markUsageLimit` parses its own window out of the provider's message+ // ("resets 5pm"), so a usage limit keeps its dedicated marker.+ const mark = bench.marker === 'usage-limit'+ ? markProviderUsageLimit(markerProviderId, errorAnalysis)+ : markProviderUnavailable(markerProviderId, {+ reason: bench.category,+ message: bench.message || 'Provider unavailable',+ waitTimeMs: bench.waitTimeMs+ });+ await mark.catch(err => {+ emitLog('warn', `Failed to sideline provider: ${err.message}`, { providerId: markerProviderId, category: bench.category });});}}diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 6e9f46367e..9fe245f2f6 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -47,6 +47,7 @@ vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => null) })vi.mock('./providerStatus.js', () => ({markProviderUsageLimit: vi.fn(async () => null),markProviderRateLimited: vi.fn(async () => null),+ markProviderUnavailable: vi.fn(async () => null),}));vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsnew file mode 100644index 0000000000..88d630e4e7--- /dev/null+++ b/server/services/agentFinalization.providerBench.test.js@@ -0,0 +1,171 @@+/**+ * Tests for the provider-sidelining finalizeAgent does on a failed run.+ *+ * The bug this covers: an `agy` (Antigravity) TUI agent that hits the+ * "We're finishing verifying your account eligibility" banner fails in ~3s —+ * correctly — but nothing marked the provider unavailable, so the very next+ * dequeued task resolved onto the same provider and died on the same banner.+ * A run of queued tasks would all fail in sequence. The eligibility signal now+ * carries `benchMs`, and finalizeAgent honors it via the generic+ * `markProviderUnavailable` marker so `resolveAgentProviderAndModel` routes the+ * retry to a fallback until the deadline auto-recovers the provider.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/execGit.js', () => ({+ execGit: vi.fn(async () => ({ stdout: 'main\n', stderr: '', exitCode: 0 })),+}));+vi.mock('./github.js', () => ({+ findPullRequestForBranch: vi.fn(async () => ({ status: 'found', number: 1, url: 'u' })),+ ensureForgeReachable: vi.fn(async () => ({ ok: true, status: 'ok' })),+}));+vi.mock('./gitlab.js', () => ({ findMergeRequestForBranch: vi.fn() }));+vi.mock('./git.js', () => ({ resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh' })) }));+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));+vi.mock('./cosAgentLifecycle.js', () => ({+ getAgent: vi.fn(async () => null),+ updateAgent: vi.fn(async () => null),+ completeAgent: vi.fn(async () => null),+}));+vi.mock('./cos.js', () => ({ updateTask: vi.fn(async () => ({})) }));++const getActiveProviderMock = vi.fn(async () => null);+vi.mock('./providers.js', () => ({ getActiveProvider: (...a) => getActiveProviderMock(...a) }));++const markProviderUnavailableMock = vi.fn(async () => null);+const markProviderUsageLimitMock = vi.fn(async () => null);+vi.mock('./providerStatus.js', () => ({+ markProviderUsageLimit: (...a) => markProviderUsageLimitMock(...a),+ markProviderRateLimited: vi.fn(async () => null),+ markProviderUnavailable: (...a) => markProviderUnavailableMock(...a),+}));++vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));+vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));+vi.mock('./agentErrorAnalysis.js', () => ({+ resolveFailedTaskUpdate: vi.fn(async () => ({ status: 'pending', metadata: {} })),+ resolveTypeFailureSignal: vi.fn(() => ({ record: 'skip' })),+}));+vi.mock('./agentRunTracking.js', () => ({+ checkForTaskCommit: vi.fn(async () => false),+ createAgentRun: vi.fn(),+ completeAgentRun: vi.fn(async () => null),+}));+vi.mock('./taskTypeHooks.js', () => ({+ canRunTaskOutputHookWithoutPayload: vi.fn(() => false),+ isProgrammaticIoTaskType: vi.fn(() => false),+ resolveTaskHookType: vi.fn(() => null),+ declaresNoCommitCriterion: vi.fn(() => false),+ getTaskOutputHook: vi.fn(async () => null),+}));+vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));+vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));++import { finalizeAgent } from './agentFinalization.js';+// The real detector and the real cooldown table supply the analysis shape and+// the window, so the assertions below can't drift from what actually ships.+import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';+import { COOLDOWN_MS_BY_CATEGORY } from '../lib/providerCooldown.js';++const failedRun = (errorAnalysis, providerId = 'antigravity-tui') => finalizeAgent({+ agentId: 'agent-1',+ task: { id: 'task-1', taskType: 'internal', description: 'do a thing', metadata: {} },+ runId: 'run-1',+ providerId,+ success: false,+ exitCode: 1,+ duration: 3000,+ outputBuffer: '',+ errorAnalysis,+ terminatedByUser: false,+ isTruthyMetaFn: () => false,+ error: errorAnalysis?.message,+ completionReason: 'fallback-signal',+ workspacePath: '/w',+ prExpected: false,+});++beforeEach(() => vi.clearAllMocks());++describe('finalizeAgent provider sidelining', () => {+ it('benches the provider on the agy eligibility signal', async () => {+ const analysis = detectImmediateFallbackSignal(+ "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly."+ );+ await failedRun(analysis);++ expect(markProviderUnavailableMock).toHaveBeenCalledWith('antigravity-tui', {+ reason: 'auth-error',+ message: analysis.message,+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY['auth-error'],+ });+ // Before this fix only usage-limit/rate-limit benched, so an auth-error left+ // the provider healthy and the next dequeued task died on the same banner.+ expect(markProviderUsageLimitMock).not.toHaveBeenCalled();+ });++ it('leaves the usage-limit marker owning its own cooldown', async () => {+ await failedRun({+ hasError: true,+ category: 'usage-limit',+ origin: 'provider',+ message: 'hit your usage limit',+ requiresFallback: true,+ }, 'claude-code-tui');++ // markUsageLimit parses its own window out of the provider's message, so it+ // keeps the dedicated marker rather than the flat per-category cooldown.+ expect(markProviderUsageLimitMock).toHaveBeenCalledWith('claude-code-tui', expect.objectContaining({+ category: 'usage-limit',+ }));+ expect(markProviderUnavailableMock).not.toHaveBeenCalled();+ });++ // The provenance gate (#2642): a repainted TUI transcript is a whole session+ // of text the agent itself wrote, so a loose keyword match must never bench a+ // healthy provider — only structured provider chrome does.+ it('does not bench an output-scan failure that merely looks provider-ish', async () => {+ await failedRun({ hasError: true, category: 'auth-error', origin: 'output-scan', message: 'unauthorized' });+ expect(markProviderUnavailableMock).not.toHaveBeenCalled();+ expect(markProviderUsageLimitMock).not.toHaveBeenCalled();+ // No marker fired, so the lazy active-provider lookup must stay unread.+ expect(getActiveProviderMock).not.toHaveBeenCalled();+ });++ it('does not bench an ordinary agent-work failure', async () => {+ await failedRun({ hasError: true, category: 'test-failure', origin: 'output-scan', message: 'suite failed' });+ expect(markProviderUnavailableMock).not.toHaveBeenCalled();+ expect(markProviderUsageLimitMock).not.toHaveBeenCalled();+ });++ // A bad model id is REQUEST-specific: benching would take the provider's other+ // working models offline over one wrong id.+ it('does not bench a provider-origin model-not-found', async () => {+ await failedRun({ hasError: true, category: 'model-not-found', origin: 'provider', message: 'no such model' });+ expect(markProviderUnavailableMock).not.toHaveBeenCalled();+ });++ it('does not bench when the user terminated the run', async () => {+ const analysis = detectImmediateFallbackSignal(+ "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly."+ );+ await finalizeAgent({+ agentId: 'agent-2',+ task: { id: 'task-2', taskType: 'internal', description: 'x', metadata: {} },+ runId: 'run-2',+ providerId: 'antigravity-tui',+ success: false,+ exitCode: 130,+ duration: 10,+ outputBuffer: '',+ errorAnalysis: analysis,+ terminatedByUser: true,+ isTruthyMetaFn: () => false,+ completionReason: 'terminated',+ workspacePath: '/w',+ prExpected: false,+ });+ expect(markProviderUnavailableMock).not.toHaveBeenCalled();+ });+});diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.jsindex 2ac97df903..369e1e74d7 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.js@@ -90,7 +90,9 @@ export async function captureWorktreeDiff(workspacePath, agentDir) {*/export async function resolveErrorAnalysis({ finalSuccess, rawFile, fallbackText, task, model, immediateFallbackAnalysis, completionReason, completionError }) {if (finalSuccess) return null;+ // Short-circuit BEFORE the tail read: a mid-stream fallback signal already is+ // the verdict, so reading ~16KB of spool only to discard it is pure waste.+ if (immediateFallbackAnalysis) return immediateFallbackAnalysis;const rawAnalysisText = await readFileTail(rawFile, RAW_TAIL_ANALYSIS_BYTES);- return immediateFallbackAnalysis- || analyzeAgentFailure(rawAnalysisText ?? fallbackText, task, model, { completionReason, completionError });+ return analyzeAgentFailure(rawAnalysisText ?? fallbackText, task, model, { completionReason, completionError });}diff --git a/server/services/providerStatus.js b/server/services/providerStatus.jsindex 34240a63f7..3f5b487c01 100644--- a/server/services/providerStatus.js+++ b/server/services/providerStatus.js@@ -51,6 +51,20 @@ export function isProviderAvailable(providerId) {return providerStatusService.isAvailable(providerId);}+/**+ * Mark a provider unavailable for an arbitrary reason + cooldown — the generic+ * marker the category-specific ones below are wrappers over. Callers resolve+ * `options` via `lib/providerCooldown.js#resolveProviderBench`.+ *+ * @param {string} providerId+ * @param {{ reason?: string, message?: string, waitTimeMs?: number, extras?: object }} options+ */+export async function markProviderUnavailable(providerId, options = {}) {+ const status = await providerStatusService.markUnavailable(providerId, options);+ console.log(`⚠️ Provider ${providerId} sidelined: ${options.reason || 'unknown'} (retry in ${Math.round((options.waitTimeMs || 0) / 60000)}m)`);+ return status;+}+/*** Mark a provider as unavailable due to usage limit*/