Skip to content

Commit 2d286e8

Browse files
fix(agents): avoid API key billing copy for OAuth
1 parent 1e7d5d6 commit 2d286e8

10 files changed

Lines changed: 106 additions & 3 deletions

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,19 @@ describe("formatAssistantErrorText", () => {
124124
expect(result).toContain("Anthropic");
125125
expect(result).not.toContain("API provider");
126126
});
127+
it("uses neutral recovery copy for Anthropic OAuth billing-shaped errors", () => {
128+
const msg = makeAssistantError("out of extra usage; try again later");
129+
msg.model = "claude-sonnet-4-6";
130+
const result = formatAssistantErrorText(msg, {
131+
provider: "Anthropic",
132+
authProfileMode: "oauth",
133+
});
134+
expect(result).toBe(formatBillingErrorMessage("Anthropic", "claude-sonnet-4-6", "oauth"));
135+
expect(result).toContain("OAuth credentials");
136+
expect(result).toContain("try again in a minute");
137+
expect(result).not.toContain("API key");
138+
expect(result).not.toContain("top up");
139+
});
127140
it("uses the active assistant model for billing message context", () => {
128141
const msg = makeAssistantError("insufficient credits");
129142
msg.model = "claude-3-5-sonnet";

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -986,7 +986,13 @@ export function classifyProviderRuntimeFailureKind(
986986

987987
export function formatAssistantErrorText(
988988
msg: AssistantMessage,
989-
opts?: { cfg?: OpenClawConfig; sessionKey?: string; provider?: string; model?: string },
989+
opts?: {
990+
cfg?: OpenClawConfig;
991+
sessionKey?: string;
992+
provider?: string;
993+
model?: string;
994+
authProfileMode?: string;
995+
},
990996
): string | undefined {
991997
// Also format errors if errorMessage is present, even if stopReason isn't "error"
992998
const raw = (msg.errorMessage ?? "").trim();
@@ -1138,7 +1144,11 @@ export function formatAssistantErrorText(
11381144
}
11391145

11401146
if (isBillingErrorMessage(raw)) {
1141-
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model);
1147+
return formatBillingErrorMessage(
1148+
opts?.provider,
1149+
opts?.model ?? msg.model,
1150+
opts?.authProfileMode,
1151+
);
11421152
}
11431153

11441154
if (providerRuntimeFailureKind === "schema") {

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

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,53 @@ import {
2727
isTimeoutErrorMessage,
2828
} from "./failover-matches.js";
2929

30-
export function formatBillingErrorMessage(provider?: string, model?: string): string {
30+
function isApiKeyBillingAuthMode(authProfileMode?: string): boolean {
31+
const normalized = authProfileMode?.trim().toLowerCase().replace(/-/g, "_");
32+
return !normalized || normalized === "api_key";
33+
}
34+
35+
function formatProviderLabel(
36+
provider?: string,
37+
model?: string,
38+
): {
39+
providerName?: string;
40+
providerLabel?: string;
41+
} {
3142
const providerName = provider?.trim();
3243
const modelName = model?.trim();
3344
const providerLabel =
3445
providerName && modelName ? `${providerName} (${modelName})` : providerName || undefined;
46+
return { providerName, providerLabel };
47+
}
48+
49+
function formatNonApiKeyBillingErrorMessage(
50+
provider?: string,
51+
model?: string,
52+
authProfileMode?: string,
53+
): string {
54+
const { providerLabel } = formatProviderLabel(provider, model);
55+
const credentialLabel =
56+
authProfileMode?.trim().toLowerCase() === "oauth"
57+
? "OAuth"
58+
: authProfileMode?.trim().toLowerCase() === "token"
59+
? "token"
60+
: "non-API-key";
61+
if (providerLabel) {
62+
return `⚠️ ${providerLabel} returned a temporary account or usage-limit error while using ${credentialLabel} credentials. OpenClaw will retry when the provider recovers; please try again in a minute.`;
63+
}
64+
return `⚠️ API provider returned a temporary account or usage-limit error while using ${credentialLabel} credentials. OpenClaw will retry when the provider recovers; please try again in a minute.`;
65+
}
66+
67+
export function formatBillingErrorMessage(
68+
provider?: string,
69+
model?: string,
70+
authProfileMode?: string,
71+
): string {
72+
if (!isApiKeyBillingAuthMode(authProfileMode)) {
73+
return formatNonApiKeyBillingErrorMessage(provider, model, authProfileMode);
74+
}
75+
76+
const { providerName, providerLabel } = formatProviderLabel(provider, model);
3577
if (providerLabel) {
3678
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.`;
3779
}

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,6 +1489,9 @@ export async function runEmbeddedPiAgent(
14891489
model: modelId,
14901490
assistant: currentAttemptAssistant ?? sessionLastAssistant,
14911491
});
1492+
const activeAuthProfileMode = lastProfileId
1493+
? attemptAuthProfileStore.profiles?.[lastProfileId]?.type
1494+
: undefined;
14921495
const resolveReplayInvalidForAttempt = (incompleteTurnText?: string | null) =>
14931496
accumulatedReplayState.replayInvalid ||
14941497
resolveReplayInvalidFlag({
@@ -1508,6 +1511,7 @@ export async function runEmbeddedPiAgent(
15081511
sessionKey: resolvedSessionKey ?? params.sessionId,
15091512
provider: activeErrorContext.provider,
15101513
model: activeErrorContext.model,
1514+
authProfileMode: activeAuthProfileMode,
15111515
})
15121516
: undefined;
15131517
const assistantErrorText =
@@ -2378,6 +2382,7 @@ export async function runEmbeddedPiAgent(
23782382
modelId,
23792383
provider,
23802384
activeErrorContext,
2385+
authProfileMode: activeAuthProfileMode,
23812386
lastAssistant: assistantForFailover,
23822387
config: params.config,
23832388
sessionKey: params.sessionKey ?? params.sessionId,
@@ -2483,6 +2488,7 @@ export async function runEmbeddedPiAgent(
24832488
sessionKey: params.sessionKey ?? params.sessionId,
24842489
provider: activeErrorContext.provider,
24852490
model: activeErrorContext.model,
2491+
authProfileMode: activeAuthProfileMode,
24862492
verboseLevel: params.verboseLevel,
24872493
reasoningLevel: params.reasoningLevel,
24882494
thinkingLevel: params.thinkLevel,

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,26 @@ describe("handleAssistantFailover", () => {
141141
expect(logDecision).toHaveBeenCalledWith("surface_error");
142142
});
143143

144+
it("uses neutral billing copy for OAuth-backed Anthropic profiles", async () => {
145+
const outcome = await handleAssistantFailover(
146+
makeParams({
147+
initialDecision: { action: "surface_error", reason: "billing" },
148+
failoverReason: "billing",
149+
billingFailure: true,
150+
authProfileMode: "oauth",
151+
}),
152+
);
153+
154+
const err = expectThrownFailoverError(outcome);
155+
expect(err.reason).toBe("billing");
156+
expect(err.message).toBe(
157+
formatBillingErrorMessage("Anthropic", "claude-haiku-4-5-20251001", "oauth"),
158+
);
159+
expect(err.message).toContain("OAuth credentials");
160+
expect(err.message).not.toContain("API key");
161+
expect(err.message).not.toContain("top up");
162+
});
163+
144164
it("throws an auth FailoverError for auth-classified surface errors", async () => {
145165
const outcome = await handleAssistantFailover(
146166
makeParams({

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export async function handleAssistantFailover(params: {
4949
modelId: string;
5050
provider: string;
5151
activeErrorContext: { provider: string; model: string };
52+
authProfileMode?: string;
5253
lastAssistant: AssistantMessage | undefined;
5354
config: OpenClawConfig | undefined;
5455
sessionKey?: string;
@@ -278,6 +279,7 @@ function resolveAssistantFailoverErrorMessage(params: {
278279
config: OpenClawConfig | undefined;
279280
sessionKey?: string;
280281
activeErrorContext: { provider: string; model: string };
282+
authProfileMode?: string;
281283
timedOut: boolean;
282284
rateLimitFailure: boolean;
283285
billingFailure: boolean;
@@ -290,6 +292,7 @@ function resolveAssistantFailoverErrorMessage(params: {
290292
sessionKey: params.sessionKey,
291293
provider: params.activeErrorContext.provider,
292294
model: params.activeErrorContext.model,
295+
authProfileMode: params.authProfileMode,
293296
})
294297
: undefined) ||
295298
params.lastAssistant?.errorMessage?.trim() ||
@@ -301,6 +304,7 @@ function resolveAssistantFailoverErrorMessage(params: {
301304
? formatBillingErrorMessage(
302305
params.activeErrorContext.provider,
303306
params.activeErrorContext.model,
307+
params.authProfileMode,
304308
)
305309
: params.authFailure
306310
? "LLM request unauthorized."

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2669,6 +2669,9 @@ export async function runEmbeddedAttempt(
26692669
silentExpected: params.silentExpected,
26702670
config: params.config,
26712671
sessionKey: sandboxSessionKey,
2672+
authProfileMode: params.authProfileId
2673+
? params.authProfileStore.profiles?.[params.authProfileId]?.type
2674+
: undefined,
26722675
sessionId: params.sessionId,
26732676
agentId: sessionAgentId,
26742677
builtinToolNames,

‎src/agents/pi-embedded-runner/run/payloads.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ export function buildEmbeddedRunPayloads(params: {
180180
sessionKey: string;
181181
provider?: string;
182182
model?: string;
183+
authProfileMode?: string;
183184
verboseLevel?: VerboseLevel;
184185
reasoningLevel?: ReasoningLevel;
185186
thinkingLevel?: ThinkLevel;
@@ -228,6 +229,7 @@ export function buildEmbeddedRunPayloads(params: {
228229
sessionKey: params.sessionKey,
229230
provider: params.provider,
230231
model: params.model,
232+
authProfileMode: params.authProfileMode,
231233
})
232234
: undefined;
233235
const rawErrorMessage = lastAssistantErrored

‎src/agents/pi-embedded-subscribe.handlers.lifecycle.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ export function handleAgentEnd(ctx: EmbeddedPiSubscribeContext): void | Promise<
7474
sessionKey: ctx.params.sessionKey,
7575
provider: lastAssistant.provider,
7676
model: lastAssistant.model,
77+
authProfileMode: ctx.params.authProfileMode,
7778
});
7879
const rawError = lastAssistant.errorMessage?.trim();
7980
const failoverReason = classifyFailoverReason(rawError ?? "", {

‎src/agents/pi-embedded-subscribe.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ export type SubscribeEmbeddedPiSessionParams = {
5858
silentExpected?: boolean;
5959
config?: OpenClawConfig;
6060
sessionKey?: string;
61+
/** Credential type for the active auth profile, used only for user-facing error copy. */
62+
authProfileMode?: string;
6163
/** Ephemeral session UUID — regenerated on /new and /reset. */
6264
sessionId?: string;
6365
/** Agent identity for hook context — resolved from session config in attempt.ts. */

0 commit comments

Comments
 (0)