Skip to content

Commit 7c97c6d

Browse files
eldar702vincentkoc
andauthored
fix(agents): use neutral billing copy for subscription auth (#93763)
* fix(agents): neutral billing-error copy for OAuth/subscription auth Fixes #80877 AI-assisted (Claude Code). * fix(agents): preserve subscription billing guidance * test(agents): use active auth store in prompt failover --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent f7d96c9 commit 7c97c6d

19 files changed

Lines changed: 373 additions & 22 deletions

‎src/agents/auth-profiles.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export {
3939
listProfilesForProvider,
4040
markAuthProfileSuccess,
4141
removeProviderAuthProfilesWithLock,
42+
resolveSubscriptionAuthModeForProfiles,
4243
setAuthProfileOrder,
4344
upsertAuthProfile,
4445
upsertAuthProfileWithLock,

‎src/agents/auth-profiles/profile-list.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,16 @@ export function listProfilesForProvider(store: AuthProfileStore, provider: strin
1919
.filter(([, cred]) => resolveProviderIdForAuth(cred.provider) === providerKey)
2020
.map(([id]) => id);
2121
}
22+
23+
export function resolveSubscriptionAuthModeForProfiles(params: {
24+
store: AuthProfileStore;
25+
profileIds: ReadonlyArray<string | undefined>;
26+
}): "oauth" | "token" | undefined {
27+
for (const profileId of params.profileIds) {
28+
const type = profileId ? params.store.profiles[profileId]?.type : undefined;
29+
if (type === "oauth" || type === "token") {
30+
return type;
31+
}
32+
}
33+
return undefined;
34+
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ import {
1717
updateAuthProfileStoreWithLock,
1818
} from "./store.js";
1919
import type { AuthProfileCredential, AuthProfileStore, ProfileUsageStats } from "./types.js";
20-
export { dedupeProfileIds, listProfilesForProvider } from "./profile-list.js";
20+
export {
21+
dedupeProfileIds,
22+
listProfilesForProvider,
23+
resolveSubscriptionAuthModeForProfiles,
24+
} from "./profile-list.js";
2125

2226
// Auth profile order/lastGood keys may be stored as aliases. Resolve through
2327
// auth provider normalization before updating per-provider state.

‎src/agents/embedded-agent-helpers.formatassistanterrortext.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,38 @@ describe("raw API error payload helpers", () => {
673673
});
674674
});
675675

676+
describe("formatBillingErrorMessage — authMode neutral copy (#80877)", () => {
677+
// OAuth/Max users should NOT see "API key" or "top up" language.
678+
it("returns neutral copy for oauth authMode — no 'API key' text", () => {
679+
const result = formatBillingErrorMessage("Anthropic", "claude-sonnet-4-5", "oauth");
680+
expect(result).not.toMatch(/api key/i);
681+
expect(result).not.toMatch(/top up/i);
682+
expect(result).toContain("check your account");
683+
});
684+
685+
it("returns neutral copy for token authMode — no 'API key' text", () => {
686+
const result = formatBillingErrorMessage("Anthropic", "claude-sonnet-4-5", "token");
687+
expect(result).not.toMatch(/api key/i);
688+
expect(result).not.toMatch(/top up/i);
689+
});
690+
691+
it("REGRESSION: api_key authMode still returns 'API key' copy", () => {
692+
const result = formatBillingErrorMessage("Anthropic", "claude-sonnet-4-5", "api_key");
693+
expect(result).toMatch(/api key/i);
694+
expect(result).toMatch(/top up/i);
695+
});
696+
697+
it("REGRESSION: undefined authMode (legacy call-sites) still returns 'API key' copy", () => {
698+
const result = formatBillingErrorMessage("Anthropic", "claude-sonnet-4-5");
699+
expect(result).toMatch(/api key/i);
700+
});
701+
702+
it("REGRESSION: no-provider call still returns generic 'API key' copy", () => {
703+
const result = formatBillingErrorMessage();
704+
expect(result).toMatch(/api key/i);
705+
});
706+
});
707+
676708
describe("sanitizeUserFacingText — streaming JSON parse error (#59076)", () => {
677709
it("rewrites transport-classified malformed streaming fragments in error context", () => {
678710
const result = sanitizeUserFacingText(MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE, {

‎src/agents/embedded-agent-helpers/errors.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,7 +1324,15 @@ export function classifyAssistantFailoverReason(
13241324

13251325
export function formatAssistantErrorText(
13261326
msg: AssistantMessage,
1327-
opts?: { cfg?: OpenClawConfig; sessionKey?: string; provider?: string; model?: string },
1327+
opts?: {
1328+
cfg?: OpenClawConfig;
1329+
sessionKey?: string;
1330+
provider?: string;
1331+
model?: string;
1332+
/** Credential auth mode (e.g. "oauth", "token", "api_key", "aws-sdk").
1333+
* When "oauth" or "token", billing copy omits API-key language (#80877). */
1334+
authMode?: string;
1335+
},
13281336
): string | undefined {
13291337
// Also format errors if errorMessage is present, even if stopReason isn't "error"
13301338
const raw = (msg.errorMessage ?? "").trim();
@@ -1481,10 +1489,10 @@ export function formatAssistantErrorText(
14811489
isOpenRouterKeyLimitExceededError(raw, opts?.provider) ||
14821490
isOpenRouterKeyBudgetLimitExceededError(raw, opts?.provider)
14831491
) {
1484-
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model);
1492+
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model, opts?.authMode);
14851493
}
14861494
if (isBilling429MessageForProvider(raw, opts?.provider)) {
1487-
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model);
1495+
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model, opts?.authMode);
14881496
}
14891497

14901498
const transientCopy = formatRateLimitOrOverloadedErrorCopy(raw);
@@ -1506,7 +1514,7 @@ export function formatAssistantErrorText(
15061514
}
15071515

15081516
if (isBillingErrorMessage(raw)) {
1509-
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model);
1517+
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model, opts?.authMode);
15101518
}
15111519

15121520
if (providerRuntimeFailureKind === "schema") {
@@ -1560,7 +1568,14 @@ export function isRawAssistantErrorPassthrough(params: {
15601568

15611569
export function formatUserFacingAssistantErrorText(
15621570
msg: AssistantMessage,
1563-
opts?: { cfg?: OpenClawConfig; sessionKey?: string; provider?: string; model?: string },
1571+
opts?: {
1572+
cfg?: OpenClawConfig;
1573+
sessionKey?: string;
1574+
provider?: string;
1575+
model?: string;
1576+
/** Credential auth mode for billing copy (#80877). */
1577+
authMode?: string;
1578+
},
15641579
): string {
15651580
const friendlyError = formatAssistantErrorText(msg, opts);
15661581
const rawError = msg.errorMessage?.trim();

‎src/agents/embedded-agent-helpers/sanitize-user-facing-text.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,31 @@ import {
3434
isTimeoutErrorMessage,
3535
} from "./failover-matches.js";
3636

37-
/** Format the billing failure copy with optional provider/model context. */
38-
export function formatBillingErrorMessage(provider?: string, model?: string): string {
37+
/** Format the billing failure copy with optional provider/model context.
38+
*
39+
* When `authMode` is `"oauth"` or `"token"` (i.e. Anthropic Max or a static
40+
* bearer-token subscription) the user has no API key to top up, so we emit
41+
* neutral copy that directs them to check their account instead (#80877).
42+
*/
43+
export function formatBillingErrorMessage(
44+
provider?: string,
45+
model?: string,
46+
authMode?: string,
47+
): string {
3948
const providerName = provider?.trim();
4049
const modelName = model?.trim();
4150
const providerLabel =
4251
providerName && modelName ? `${providerName} (${modelName})` : providerName || undefined;
52+
53+
// OAuth and static-token credentials do not have an API key to top up.
54+
const isSubscriptionAuth = authMode === "oauth" || authMode === "token";
55+
if (isSubscriptionAuth) {
56+
if (providerLabel) {
57+
return `⚠️ ${providerLabel} returned a billing error — check your account for subscription or usage limits, then try again.`;
58+
}
59+
return "⚠️ API provider returned a billing error — check your account for subscription or usage limits, then try again.";
60+
}
61+
4362
if (providerLabel) {
4463
return `⚠️ ${providerLabel} returned a billing error — your API key has run out of credits or has an insufficient balance. Check your ${providerName} billing dashboard and top up or switch to a different API key.`;
4564
}

‎src/agents/embedded-agent-runner/run.overflow-compaction.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2660,6 +2660,14 @@ describe("runEmbeddedAgent overflow compaction trigger routing", () => {
26602660
});
26612661

26622662
mockedRunEmbeddedAttempt.mockResolvedValue(makeAttemptResult({ promptError }));
2663+
mockedEnsureAuthProfileStoreWithoutExternalProfiles.mockReturnValue({
2664+
profiles: {
2665+
"test-profile": {
2666+
provider: "anthropic",
2667+
type: "oauth",
2668+
},
2669+
},
2670+
});
26632671
mockedCoerceToFailoverError.mockReturnValue(normalized);
26642672
mockedDescribeFailoverError.mockImplementation((err: unknown) => ({
26652673
message: err instanceof Error ? err.message : String(err),
@@ -2689,6 +2697,7 @@ describe("runEmbeddedAgent overflow compaction trigger routing", () => {
26892697
provider: "anthropic",
26902698
model: "test-model",
26912699
profileId: "test-profile",
2700+
authMode: "oauth",
26922701
});
26932702
expect(mockedResolveFailoverStatus).toHaveBeenCalledWith("rate_limit");
26942703
});

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2142,6 +2142,9 @@ async function runEmbeddedAgentInternal(
21422142
sessionKey: resolvedSessionKey ?? params.sessionId,
21432143
provider: activeErrorContext.provider,
21442144
model: activeErrorContext.model,
2145+
authMode: lastProfileId
2146+
? attemptAuthProfileStore.profiles?.[lastProfileId]?.type
2147+
: undefined,
21452148
})
21462149
: undefined;
21472150
const assistantErrorText =
@@ -2766,10 +2769,14 @@ async function runEmbeddedAgentInternal(
27662769
// promptErrorSource === "compaction" means the model call already completed and the
27672770
// abort happened only while waiting for compaction/retry cleanup. Retrying from here
27682771
// would replay that completed tool turn as a fresh prompt attempt.
2772+
const promptAuthMode = lastProfileId
2773+
? attemptAuthProfileStore.profiles?.[lastProfileId]?.type
2774+
: undefined;
27692775
const normalizedPromptFailover = coerceToFailoverError(promptError, {
27702776
provider: activeErrorContext.provider,
27712777
model: activeErrorContext.model,
27722778
profileId: lastProfileId,
2779+
authMode: promptAuthMode,
27732780
sessionId: sessionIdUsed,
27742781
lane: globalLane,
27752782
});
@@ -2999,6 +3006,7 @@ async function runEmbeddedAgentInternal(
29993006
provider,
30003007
model: modelId,
30013008
profileId: lastProfileId,
3009+
authMode: promptAuthMode,
30023010
sessionId: sessionIdUsed,
30033011
lane: globalLane,
30043012
status,
@@ -3185,6 +3193,9 @@ async function runEmbeddedAgentInternal(
31853193
authFailure,
31863194
rateLimitFailure,
31873195
billingFailure,
3196+
authMode: lastProfileId
3197+
? attemptAuthProfileStore.profiles?.[lastProfileId]?.type
3198+
: undefined,
31883199
cloudCodeAssistFormatError,
31893200
isProbeSession,
31903201
overloadProfileRotations,
@@ -3300,6 +3311,9 @@ async function runEmbeddedAgentInternal(
33003311
sessionKey: params.sessionKey ?? params.sessionId,
33013312
provider: activeErrorContext.provider,
33023313
model: activeErrorContext.model,
3314+
authMode: lastProfileId
3315+
? attemptAuthProfileStore.profiles?.[lastProfileId]?.type
3316+
: undefined,
33033317
verboseLevel: params.verboseLevel,
33043318
reasoningLevel: params.reasoningLevel,
33053319
thinkingLevel: params.thinkLevel,

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ export async function handleAssistantFailover(params: {
143143
authFailure: boolean;
144144
rateLimitFailure: boolean;
145145
billingFailure: boolean;
146+
/** Credential auth mode (e.g. "oauth", "token", "api_key") for billing copy (#80877). */
147+
authMode?: string;
146148
cloudCodeAssistFormatError: boolean;
147149
isProbeSession: boolean;
148150
overloadProfileRotations: number;
@@ -331,6 +333,7 @@ export async function handleAssistantFailover(params: {
331333
provider: params.activeErrorContext.provider,
332334
model: params.activeErrorContext.model,
333335
profileId: params.lastProfileId,
336+
authMode: params.authMode,
334337
status,
335338
rawError: params.lastAssistant?.errorMessage?.trim(),
336339
suspend: shouldSuspend,
@@ -362,6 +365,7 @@ export async function handleAssistantFailover(params: {
362365
provider: params.activeErrorContext.provider,
363366
model: params.activeErrorContext.model,
364367
profileId: params.lastProfileId,
368+
authMode: params.authMode,
365369
status,
366370
rawError: params.lastAssistant?.errorMessage?.trim(),
367371
suspend: shouldSuspend,
@@ -386,6 +390,8 @@ function resolveAssistantFailoverErrorMessage(params: {
386390
rateLimitFailure: boolean;
387391
billingFailure: boolean;
388392
authFailure: boolean;
393+
/** Credential auth mode passed through to billing copy formatter (#80877). */
394+
authMode?: string;
389395
}): string {
390396
const timeoutFailure = params.timedOut || params.idleTimedOut;
391397
return (
@@ -395,6 +401,7 @@ function resolveAssistantFailoverErrorMessage(params: {
395401
sessionKey: params.sessionKey,
396402
provider: params.activeErrorContext.provider,
397403
model: params.activeErrorContext.model,
404+
authMode: params.authMode,
398405
})
399406
: undefined) ||
400407
params.lastAssistant?.errorMessage?.trim() ||
@@ -406,6 +413,7 @@ function resolveAssistantFailoverErrorMessage(params: {
406413
? formatBillingErrorMessage(
407414
params.activeErrorContext.provider,
408415
params.activeErrorContext.model,
416+
params.authMode,
409417
)
410418
: params.authFailure
411419
? "LLM request unauthorized."

‎src/agents/embedded-agent-runner/run/auth-controller.test.ts‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { Model } from "openclaw/plugin-sdk/llm";
33
import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
44
import type { AuthProfileStore } from "../../auth-profiles.js";
5+
import { FailoverError } from "../../failover-error.js";
56
import type { RuntimeAuthState } from "./helpers.js";
67

78
const mocks = vi.hoisted(() => ({
@@ -95,21 +96,25 @@ function createMutableEmbeddedRunAuthController(params: {
9596
harness: MutableAuthControllerHarness;
9697
setRuntimeApiKey: RuntimeApiKeySetter;
9798
profileCandidates?: string[];
99+
authStore?: AuthProfileStore;
100+
fallbackConfigured?: boolean;
98101
warn?: (message: string) => void;
99102
}) {
100103
return createEmbeddedRunAuthController({
101104
config: undefined,
102105
agentDir: "/tmp/agent",
103106
workspaceDir: "/tmp/workspace",
104-
authStore: {
105-
version: 1,
106-
profiles: {},
107-
} as AuthProfileStore,
107+
authStore:
108+
params.authStore ??
109+
({
110+
version: 1,
111+
profiles: {},
112+
} as AuthProfileStore),
108113
authStorage: { setRuntimeApiKey: params.setRuntimeApiKey },
109114
profileCandidates: params.profileCandidates ?? ["default"],
110115
initialThinkLevel: "medium",
111116
attemptedThinking: new Set(),
112-
fallbackConfigured: false,
117+
fallbackConfigured: params.fallbackConfigured ?? false,
113118
allowTransientCooldownProbe: false,
114119
getProvider: () => "custom-openai",
115120
getModelId: () => "test-model",
@@ -228,6 +233,43 @@ describe("createEmbeddedRunAuthController", () => {
228233
});
229234
});
230235

236+
it("preserves OAuth mode when billing-disabled profiles are all unavailable", async () => {
237+
const harness = createMutableAuthControllerHarness();
238+
const profileId = "custom-openai:oauth";
239+
const controller = createMutableEmbeddedRunAuthController({
240+
harness,
241+
setRuntimeApiKey: vi.fn(),
242+
profileCandidates: [profileId],
243+
fallbackConfigured: true,
244+
authStore: {
245+
version: 1,
246+
profiles: {
247+
[profileId]: {
248+
type: "oauth",
249+
provider: "custom-openai",
250+
access: "access-token",
251+
refresh: "refresh-token",
252+
expires: Date.now() + 60_000,
253+
},
254+
},
255+
usageStats: {
256+
[profileId]: {
257+
disabledUntil: Date.now() + 60_000,
258+
disabledReason: "billing",
259+
},
260+
},
261+
},
262+
});
263+
264+
const error = await controller.initializeAuthProfile().catch((err: unknown) => err);
265+
266+
expect(error).toBeInstanceOf(FailoverError);
267+
expect(error).toMatchObject({
268+
reason: "billing",
269+
authMode: "oauth",
270+
});
271+
});
272+
231273
it("rejects privileged runtime transport overrides on the first auth exchange", async () => {
232274
let runtimeModel = createTestModel();
233275

0 commit comments

Comments
 (0)