diff --git a/src/agent/loop.ts b/src/agent/loop.ts index aad14278a..dd62de4cd 100644 --- a/src/agent/loop.ts +++ b/src/agent/loop.ts @@ -35,7 +35,7 @@ import { executeTool, } from "./tools.js"; import { sanitizeInput } from "./injection-defense.js"; -import { getSurvivalTier } from "../conway/credits.js"; +import { getSurvivalTier, resolveSurvivalTier, BALANCE_UNKNOWN } from "../conway/credits.js"; import { getUsdcBalance } from "../conway/x402.js"; import { claimInboxMessages, @@ -431,7 +431,7 @@ export async function runAgentLoop( // Check survival tier // api_unreachable: creditsCents === -1 means API failed with no cache. // Do NOT kill the agent; continue in low-compute mode and retry next tick. - if (financial.creditsCents === -1) { + if (financial.creditsCents === BALANCE_UNKNOWN) { log(config, "[API_UNREACHABLE] Balance API unreachable, continuing in low-compute mode."); inference.setLowComputeMode(true); } else { @@ -596,7 +596,7 @@ export async function runAgentLoop( pendingInput = undefined; // ── Inference Call (via router when available) ── - const survivalTier = getSurvivalTier(financial.creditsCents); + const survivalTier = resolveSurvivalTier(financial.creditsCents); log(config, `[THINK] Routing inference (tier: ${survivalTier}, model: ${inference.getDefaultModel()})...`); const inferenceTools = toolsToInferenceFormat(tools); @@ -977,7 +977,7 @@ async function getFinancialState( // No cache available -- return conservative non-zero sentinel logger.error("Balance API failed, no cache available"); return { - creditsCents: -1, + creditsCents: BALANCE_UNKNOWN, usdcBalance: -1, lastChecked: new Date().toISOString(), }; diff --git a/src/conway/credits.ts b/src/conway/credits.ts index ba9f63e1e..e1f8b77b1 100644 --- a/src/conway/credits.ts +++ b/src/conway/credits.ts @@ -43,6 +43,25 @@ export function getSurvivalTier(creditsCents: number): SurvivalTier { return "dead"; } +/** + * Sentinel used when the balance API is unreachable and no cached balance + * exists. It is deliberately NOT a real balance: "unknown" must never be + * read as the API-confirmed debt that getSurvivalTier() treats as "dead". + */ +export const BALANCE_UNKNOWN = -1; + +/** + * Map a possibly-unknown balance to a survival tier. + * + * When the balance is unknown the automaton degrades to "low_compute" + * instead of dying: an unreachable billing API is an infrastructure + * failure, not evidence that the agent is out of money. Retried next tick. + */ +export function resolveSurvivalTier(creditsCents: number): SurvivalTier { + if (creditsCents === BALANCE_UNKNOWN) return "low_compute"; + return getSurvivalTier(creditsCents); +} + /** * Format a credit amount for display. */