Skip to content

Commit 196d811

Browse files
MertBasar0Ceviz Agentclaude
authored
fix(auth): cooldown inline api key billing failures (#88709)
* fix(auth): cooldown inline api key billing failures * fix: mark inline api key prompt failures * fix(auth): propagate inline api key cooldown to provider visibility * fix(types): fix test type errors in agents and ui * fix(auth): correct null check for cooldown gate and fix test case * fix(ui): remove unrelated test drift and fix expired toast expectation * fix(auth): preserve inline cooldown usageStats in warm worker snapshots * test(auth): update warm snapshot expectation with usageStats * test(auth): format inline cooldown worker proof * fix(auth): narrow inline cooldown classifier * fix(auth): mark managed file/exec SecretRef inline keys on auth/billing failure The inline-api-key cooldown marker only fired for literal, env-marker, and env SecretRef sources, while the resolution gate already covered managed file/exec SecretRef provider keys via coerceSecretRef. As a result a file/exec SecretRef models.providers.<id>.apiKey could never record a 402 billing cooldown, so the gate that would honor it never triggered. Align the runner failure-marker trigger with the gate predicate (isConfigBackedInlineProviderApiKey) so managed non-env SecretRef inline keys are marked on auth/billing failure. Adds focused regression coverage. Co-Authored-By: Claude Opus 4.8 <[email protected]> * refactor(auth): drop now-unused isInlineProviderApiKeyAuth export The runner failure-marker now gates on isConfigBackedInlineProviderApiKey, so isInlineProviderApiKeyAuth has no remaining callers. Removing the dead export also trims one public callable export back under the plugin-SDK surface budget. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(auth): enforce inline cooldown for managed file/exec SecretRef keys The inline-api-key cooldown was recorded for managed (file/exec) SecretRef provider keys but never enforced: these keys resolve through the synthetic runtime path (resolveSyntheticLocalProviderAuth) and the explicit api-key override path, neither of which consulted the inline-key cooldown gate. So an exhausted file/exec SecretRef provider kept resolving and reporting available during an active inline-api-key:<provider> cooldown. Gate both resolution exits (and the provider-availability check) on isConfigBackedInlineProviderApiKey + assertInlineProviderApiKeyUsable, matching the literal/env paths. Local no-auth markers are not config-backed inline keys, so they stay untouched. Adds regression coverage for both resolution paths. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(auth): gate runtime SecretRef cooldown checks * fix(auth): honor inline key cooldowns in model-list and tool auth checks Direct hasRuntimeAvailableProviderAuth callers omitted the auth store, so inline provider keys in billing cooldown were still advertised as available in model browsing (models.list) and model-backed tool auth checks. Pass the scoped auth store at each call site and cover the cooled-key paths with regression tests, including profile fallback and cooldown expiry. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(auth): resolve merge CI failures (format + browse cooldown mock independence) - failover-retry-controller.ts: apply oxfmt formatting missed after the port. - model-auth-availability.ts: the browse-side inline cooldown check imported resolveInlineProviderApiKeyUnusableUntil from the auth-profiles usage module, which several command/directive tests partially mock — the new export was absent from those mocks, so every mocking test threw at the browse path. Read the inline cooldown via usage-state primitives (resolveProfileUnusableUntil + isAuthCooldownBypassedForProvider) and build the usage id with the same normalizeProviderId the write side uses, so the hot browse path no longer depends on the mocked usage module while keeping key resolution identical. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(auth): make model-auth inline cooldown reads mock-independent resolveApiKeyForProvider/assertInlineProviderApiKeyUsable read the inline provider API-key cooldown, which this PR routes through the auth-profiles usage module. Many existing suites partially mock that barrel (e.g. run.overflow-compaction.test.ts) without the new export, so those tests threw once merged code reached the inline path. Read the cooldown via usage-state primitives (resolveProfileUnusableUntil + isAuthCooldownBypassedForProvider) and build the `inline-api-key:<provider>` usage id with the same normalizeProviderId the write side uses, so model-auth no longer depends on the mocked usage module while key resolution stays identical. Verified across all 30 suites that mock the auth-profiles module. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(test): use main's terminal failure shape for the inline-key billing case Main reworked EmbeddedRunAttemptResult so attempt failures are reported via `terminal: { kind: "failed", source, error }` instead of the old `promptError`/`promptErrorSource` fields. The inline-key billing regression test still used the removed fields, which merged cleanly but broke check-test-types. Switch it to the same shape the sibling helper in this file already uses. Verified with `pnpm check:test-types` (exit 0). Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Mert Basar <[email protected]> Co-authored-by: Ceviz Agent <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
1 parent b4faa5a commit 196d811

25 files changed

Lines changed: 1106 additions & 40 deletions

‎src/agents/auth-profiles.markauthprofilefailure.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import {
2727
import {
2828
calculateAuthProfileCooldownMs,
2929
markAuthProfileFailure,
30+
markInlineProviderApiKeyFailure,
31+
resolveInlineProviderApiKeyUsageId,
3032
setAuthProfileFailureHook,
3133
} from "./auth-profiles/usage.js";
3234

@@ -168,6 +170,26 @@ describe("markAuthProfileFailure", () => {
168170
expectCooldownInRange(remainingMs, 4.5 * 60 * 60 * 1000, 5.5 * 60 * 60 * 1000);
169171
});
170172
});
173+
it("records billing backoff for inline provider api keys without creating an auth profile", async () => {
174+
await withAuthProfileStore(async ({ agentDir, store }) => {
175+
const startedAt = Date.now();
176+
await markInlineProviderApiKeyFailure({
177+
store,
178+
provider: "anthropic",
179+
reason: "billing",
180+
agentDir,
181+
});
182+
183+
const usageId = resolveInlineProviderApiKeyUsageId("anthropic");
184+
const stats = store.usageStats?.[usageId];
185+
expect(store.profiles[usageId]).toBeUndefined();
186+
expect(stats?.disabledReason).toBe("billing");
187+
expect(typeof stats?.disabledUntil).toBe("number");
188+
const remainingMs = (stats?.disabledUntil as number) - startedAt;
189+
expectCooldownInRange(remainingMs, 4.5 * 60 * 60 * 1000, 5.5 * 60 * 60 * 1000);
190+
});
191+
});
192+
171193
it("keeps persisted cooldownUntil unchanged across mid-window retries", async () => {
172194
await withAuthProfileStore(async ({ agentDir, store }) => {
173195
await markAuthProfileFailure({
@@ -376,6 +398,24 @@ describe("markAuthProfileFailure", () => {
376398
});
377399
});
378400

401+
it("fires the auth profile failure hook for inline provider api key failures", async () => {
402+
await withAuthProfileStore(async ({ agentDir, store }) => {
403+
const hook = vi.fn();
404+
setAuthProfileFailureHook(hook);
405+
try {
406+
await markInlineProviderApiKeyFailure({
407+
store,
408+
provider: "anthropic",
409+
reason: "billing",
410+
agentDir,
411+
});
412+
expect(hook).toHaveBeenCalledTimes(1);
413+
} finally {
414+
setAuthProfileFailureHook(undefined);
415+
}
416+
});
417+
});
418+
379419
it("does not break failure recording when the hook throws", async () => {
380420
await withAuthProfileStore(async ({ agentDir, store }) => {
381421
const throwingHook = vi.fn(() => {

‎src/agents/auth-profiles.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,9 @@ export {
9797
markAuthProfileCooldown,
9898
markAuthProfileBlockedUntil,
9999
markAuthProfileFailure,
100+
markInlineProviderApiKeyFailure,
101+
resolveInlineProviderApiKeyUnusableUntil,
102+
resolveInlineProviderApiKeyUsageId,
100103
resolveProfilesUnavailableReason,
101104
resolveProfileUnusableUntilForDisplay,
102105
setAuthProfileFailureHook,

‎src/agents/auth-profiles/persisted.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ type CredentialRejectReason = "non_object" | "invalid_type" | "missing_provider"
4444
type RejectedCredentialEntry = { key: string; reason: CredentialRejectReason };
4545

4646
const AUTH_PROFILE_TYPES = new Set<AuthProfileCredential["type"]>(["api_key", "oauth", "token"]);
47+
const INLINE_API_KEY_USAGE_ID_PREFIX = "inline-api-key:";
48+
49+
function isRetainedUsageStatsId(
50+
profileId: string,
51+
profiles: AuthProfileStore["profiles"],
52+
): boolean {
53+
return Boolean(profiles[profileId]) || profileId.startsWith(INLINE_API_KEY_USAGE_ID_PREFIX);
54+
}
4755

4856
// Persisted credential normalization accepts old field names and SecretRef-ish
4957
// values, then emits the current credential discriminated union.
@@ -652,7 +660,9 @@ export function mergeAuthProfileStores(
652660
const mergedUsageStats = mergeRecord(base.usageStats, override.usageStats);
653661
const usageStats = mergedUsageStats
654662
? Object.fromEntries(
655-
Object.entries(mergedUsageStats).filter(([profileId]) => profiles[profileId]),
663+
Object.entries(mergedUsageStats).filter(([profileId]) =>
664+
isRetainedUsageStatsId(profileId, profiles),
665+
),
656666
)
657667
: undefined;
658668
const merged = {

‎src/agents/auth-profiles/store.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,9 @@ function pruneAuthProfileStoreReferences(
539539
: undefined;
540540
store.usageStats = store.usageStats
541541
? Object.fromEntries(
542-
Object.entries(store.usageStats).filter(([profileId]) => keptProfileIds.has(profileId)),
542+
Object.entries(store.usageStats).filter(
543+
([profileId]) => keptProfileIds.has(profileId) || profileId.startsWith("inline-api-key:"),
544+
),
543545
)
544546
: undefined;
545547
store.runtimePersistedProfileIds = store.runtimePersistedProfileIds

‎src/agents/auth-profiles/usage.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,12 @@ function logDroppedAuthProfileBookkeeping(kind: string, profileId: string): void
7373
});
7474
}
7575

76+
const INLINE_API_KEY_USAGE_ID_PREFIX = "inline-api-key:";
77+
78+
export function resolveInlineProviderApiKeyUsageId(provider: string): string {
79+
return `${INLINE_API_KEY_USAGE_ID_PREFIX}${normalizeProviderId(provider)}`;
80+
}
81+
7682
const FAILURE_REASON_PRIORITY: AuthProfileFailureReason[] = [
7783
"auth_permanent",
7884
"auth",
@@ -761,6 +767,20 @@ export function resolveProfileUnusableUntilForDisplay(
761767
return resolveProfileUnusableUntil(stats);
762768
}
763769

770+
export function resolveInlineProviderApiKeyUnusableUntil(
771+
store: AuthProfileStore,
772+
provider: string,
773+
): number | null {
774+
if (isAuthCooldownBypassedForProvider(provider)) {
775+
return null;
776+
}
777+
const stats = store.usageStats?.[resolveInlineProviderApiKeyUsageId(provider)];
778+
if (!stats) {
779+
return null;
780+
}
781+
return resolveProfileUnusableUntil(stats);
782+
}
783+
764784
function resetUsageStats(
765785
existing: ProfileUsageStats | undefined,
766786
overrides?: Partial<ProfileUsageStats>,
@@ -1120,6 +1140,64 @@ export async function markAuthProfileBlockedUntil(params: {
11201140
}
11211141
}
11221142

1143+
export async function markInlineProviderApiKeyFailure(params: {
1144+
store: AuthProfileStore;
1145+
provider: string;
1146+
reason: AuthProfileFailureReason;
1147+
cfg?: OpenClawConfig;
1148+
agentDir?: string;
1149+
runId?: string;
1150+
modelId?: string;
1151+
}): Promise<void> {
1152+
const { store, provider, reason, agentDir, runId, modelId } = params;
1153+
if (isAuthCooldownBypassedForProvider(provider)) {
1154+
return;
1155+
}
1156+
1157+
const usageId = resolveInlineProviderApiKeyUsageId(provider);
1158+
const cfgResolved = resolveAuthCooldownConfig();
1159+
1160+
let nextStats: ProfileUsageStats | undefined;
1161+
let previousStats: ProfileUsageStats | undefined;
1162+
let updateTime = 0;
1163+
const updated = await authProfileUsageDeps.updateAuthProfileStoreWithLock({
1164+
agentDir,
1165+
updater: (freshStore) => {
1166+
const now = Date.now();
1167+
previousStats = freshStore.usageStats?.[usageId];
1168+
updateTime = now;
1169+
nextStats = computeNextProfileUsageStats({
1170+
existing: previousStats ?? {},
1171+
now,
1172+
reason,
1173+
cfgResolved,
1174+
modelId,
1175+
});
1176+
updateUsageStatsEntry(freshStore, usageId, () => nextStats as ProfileUsageStats);
1177+
return true;
1178+
},
1179+
});
1180+
if (updated) {
1181+
store.usageStats = updated.usageStats;
1182+
if (nextStats) {
1183+
logAuthProfileFailureStateChange({
1184+
runId,
1185+
profileId: usageId,
1186+
provider,
1187+
reason,
1188+
previous: previousStats,
1189+
next: nextStats,
1190+
now: updateTime,
1191+
});
1192+
}
1193+
notifyAuthProfileFailureHook();
1194+
return;
1195+
}
1196+
if (updated === null) {
1197+
logDroppedAuthProfileBookkeeping("inline_api_key_failure", usageId);
1198+
}
1199+
}
1200+
11231201
/**
11241202
* Mark a profile as transiently failed. Applies stepped backoff cooldown.
11251203
* Cooldown times: 30s, 1min, 5min (capped).

‎src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import type { AssistantMessage } from "openclaw/plugin-sdk/llm";
66
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
77
import type { OpenClawConfig } from "../config/config.js";
88
import { redactIdentifier } from "../logging/redact-identifier.js";
9-
import type { AuthProfileFailureReason } from "./auth-profiles.js";
9+
import {
10+
resolveInlineProviderApiKeyUsageId,
11+
type AuthProfileFailureReason,
12+
} from "./auth-profiles.js";
1013
import { ensureAuthProfileStore, saveAuthProfileStore } from "./auth-profiles/store.js";
1114
import type { EmbeddedRunAttemptResult } from "./embedded-agent-runner/run/types.js";
1215
import {
@@ -934,6 +937,48 @@ describe("runEmbeddedAgent auth profile rotation", () => {
934937
expect(sleepWithAbortMock).not.toHaveBeenCalled();
935938
});
936939

940+
it("marks inline provider api key billing prompt failures without an auth profile", async () => {
941+
await withAgentWorkspace(async ({ agentDir, workspaceDir }) => {
942+
await fs.writeFile(
943+
path.join(agentDir, "auth-profiles.json"),
944+
JSON.stringify({ version: 1, profiles: {} }),
945+
);
946+
await fs.writeFile(
947+
path.join(agentDir, "auth-state.json"),
948+
JSON.stringify({ version: 1, usageStats: {} }),
949+
);
950+
runEmbeddedAttemptMock.mockResolvedValueOnce(
951+
makeAttempt({
952+
terminal: { kind: "failed", source: "prompt", error: new Error("insufficient credits") },
953+
}),
954+
);
955+
956+
await expect(
957+
runEmbeddedAgentInline({
958+
sessionId: "session:test",
959+
sessionKey: "agent:test:inline-api-key-prompt-billing",
960+
sessionFile: path.join(workspaceDir, "session.jsonl"),
961+
workspaceDir,
962+
agentDir,
963+
config: makeConfig(),
964+
prompt: "hello",
965+
provider: "openai",
966+
model: "mock-1",
967+
authProfileIdSource: "auto",
968+
timeoutMs: 5_000,
969+
runId: "run:inline-api-key-prompt-billing",
970+
}),
971+
).rejects.toThrow(/insufficient credits/);
972+
973+
expect(runEmbeddedAttemptMock).toHaveBeenCalledTimes(1);
974+
const usageStats = await readUsageStats(agentDir);
975+
const usageId = resolveInlineProviderApiKeyUsageId("openai");
976+
expect(usageStats[usageId]?.disabledReason).toBe("billing");
977+
expect(typeof usageStats[usageId]?.disabledUntil).toBe("number");
978+
expect(usageStats["openai:p1"]).toBeUndefined();
979+
});
980+
});
981+
937982
it("rotates on timeout without cooling down the timed-out profile", async () => {
938983
const { usageStats } = await runAutoPinnedRotationCase({
939984
errorMessage: "request ended without sending any chunks",

‎src/agents/embedded-agent-runner/run-loop.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ export async function runPreparedEmbeddedLoop(
262262
getLastProfileId: () => preparedRuntime.snapshot().lastProfileId,
263263
getSessionId: () => sessionPromptState.sessionId,
264264
harnessOwnsTransport: () => preparedRuntime.snapshot().pluginHarnessOwnsTransport,
265+
getApiKeyInfo,
265266
});
266267
// Resolve the context engine once and reuse across retries to avoid
267268
// repeated initialization/connection overhead per attempt.

‎src/agents/embedded-agent-runner/run/assistant-failover.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,28 @@ describe("handleAssistantFailover", () => {
497497
expect(warn).not.toHaveBeenCalled();
498498
});
499499

500+
it("marks inline auth failures even when no profile id is active", async () => {
501+
const maybeMarkAuthProfileFailure = vi.fn(async () => {});
502+
503+
const outcome = await handleAssistantFailover(
504+
makeParams({
505+
initialDecision: { action: "rotate_profile", reason: "billing" },
506+
failoverReason: "billing",
507+
assistantProfileFailureReason: "billing",
508+
lastProfileId: undefined,
509+
advanceAuthProfile: vi.fn(async () => false),
510+
maybeMarkAuthProfileFailure,
511+
}),
512+
);
513+
514+
expect(outcome.action).toBe("throw");
515+
expect(maybeMarkAuthProfileFailure).toHaveBeenCalledWith({
516+
profileId: undefined,
517+
reason: "billing",
518+
modelId: "claude-haiku-4-5-20251001",
519+
});
520+
});
521+
500522
it("marks provider-started timeout rotations against the failed profile", async () => {
501523
const maybeMarkAuthProfileFailure = vi.fn(async () => {});
502524

‎src/agents/embedded-agent-runner/run/assistant-failover.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ export async function handleAssistantFailover(params: {
146146
const timeoutFailure = terminal.timedOut;
147147
const failureReason = params.assistantProfileFailureReason;
148148
const markFailedProfile = async () => {
149-
if (!failedProfileId || !failureReason) {
149+
if (!failureReason) {
150150
return;
151151
}
152152
try {

‎src/agents/embedded-agent-runner/run/failover-retry-controller.ts‎

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
import { sanitizeForLog } from "../../../../packages/terminal-core/src/ansi.js";
22
import { sleepWithAbort } from "../../../infra/backoff.js";
3-
import { type AuthProfileFailureReason, markAuthProfileFailure } from "../../auth-profiles.js";
3+
import {
4+
type AuthProfileFailureReason,
5+
markAuthProfileFailure,
6+
markInlineProviderApiKeyFailure,
7+
} from "../../auth-profiles.js";
48
import type { FailoverReason } from "../../embedded-agent-helpers.js";
59
import { FailoverError, resolveFailoverStatus } from "../../failover-error.js";
10+
import { isConfigBackedInlineProviderApiKey, type ResolvedProviderAuth } from "../../model-auth.js";
611
import { log } from "../logger.js";
712
import { resolveAuthProfileFailureReason } from "./auth-profile-failure-policy.js";
813
import type { PreparedEmbeddedRunInput } from "./execution-context.js";
@@ -29,6 +34,7 @@ export function createEmbeddedRunFailoverRetryController(input: {
2934
getLastProfileId: () => string | undefined;
3035
getSessionId: () => string;
3136
harnessOwnsTransport: () => boolean;
37+
getApiKeyInfo: () => ResolvedProviderAuth | null;
3238
}) {
3339
const {
3440
runParams: params,
@@ -109,15 +115,42 @@ export function createEmbeddedRunFailoverRetryController(input: {
109115
return;
110116
}
111117
const { profileId, reason } = failure;
112-
if (!profileId || !reason) {
118+
if (!reason) {
113119
return;
114120
}
115121
if (input.harnessOwnsTransport() && reason === "timeout") {
116122
return;
117123
}
118-
await markAuthProfileFailure({
124+
if (profileId) {
125+
await markAuthProfileFailure({
126+
store: profileFailureStore,
127+
profileId,
128+
reason,
129+
cfg: params.config,
130+
agentDir,
131+
runId: params.runId,
132+
modelId: failure.modelId,
133+
});
134+
return;
135+
}
136+
// Inline provider API keys have no auth profile, so record their
137+
// billing/auth failures under the provider-scoped inline cooldown so the
138+
// resolver stops handing back the exhausted key on the next turn.
139+
const apiKeyInfo = input.getApiKeyInfo();
140+
if (
141+
apiKeyInfo?.mode !== "api-key" ||
142+
!isConfigBackedInlineProviderApiKey({
143+
cfg: params.config,
144+
provider,
145+
source: apiKeyInfo.source,
146+
store: profileFailureStore,
147+
})
148+
) {
149+
return;
150+
}
151+
await markInlineProviderApiKeyFailure({
119152
store: profileFailureStore,
120-
profileId,
153+
provider,
121154
reason,
122155
cfg: params.config,
123156
agentDir,

0 commit comments

Comments
 (0)