Skip to content

Commit ead8ce0

Browse files
Marvintheboredsteipeteobviyus
authored
fix: keep provider refusals terminal
Treat structured provider refusals as terminal before retry, compaction, credential rotation, or model fallback. Preserve exact current-attempt ownership so historical refusal diagnostics cannot control later turns. Keep bounded refusal guidance intact after Gateway history reload. Closes #134968 Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent da91373 commit ead8ce0

35 files changed

Lines changed: 1031 additions & 168 deletions

‎docs/concepts/model-failover.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ OpenClaw builds the candidate list from the currently requested `provider/model`
309309
- context overflow errors that should stay inside compaction/retry logic (for example `request_too_large`, `input token count exceeds the maximum number of input tokens`, `input exceeds the maximum number of tokens`, `input too long for the model`, or `ollama error: context length exceeded`)
310310
- context overflow inside an embedded run that has already been declared terminal, including a provider request-size ceiling (for example Groq's `413 ... on tokens per minute (TPM): Limit 8000, Requested 8098`), which the runner stops on rather than compacting
311311
- a final unknown error when there are no candidates left
312-
- Claude Fable 5 safety refusals; direct API-key requests handle those at the provider level via Anthropic's server-side fallback to `claude-opus-4-8` instead (see [Anthropic](/providers/anthropic#safety-refusal-fallback-claude-opus-5-and-fable-5))
312+
- final provider refusals; eligible Anthropic direct API-key requests handle refusal fallback within the provider request instead (see [Anthropic](/providers/anthropic#safety-refusal-fallback-claude-opus-5-and-fable-5))
313313

314314
</Tab>
315315
</Tabs>

‎docs/providers/anthropic.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,8 @@ Anthropic has a recommended model for that refusal category.
421421
are discarded per Anthropic's replay rules (they must not be echoed back or
422422
executed).
423423
4. If the recommended model declines as well, the turn surfaces the refusal
424-
as an error.
424+
as an error. OpenClaw does not retry a final refusal or advance to another
425+
configured model.
425426

426427
The fallback happens at the Anthropic API level, so the serving model does not
427428
need to be in your configured OpenClaw fallback chain.

‎packages/ai/src/utils/overflow.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ describe("configured context size overflow", () => {
5757
});
5858

5959
describe("provider overflow messages", () => {
60+
it.each([
61+
{ type: "provider_refusal", overflow: false },
62+
{ type: "provider_fallback", overflow: true },
63+
])("preserves $type when the error text mentions overflow", ({ type, overflow }) => {
64+
const message = errorMessage("prompt is too long: 1200 tokens > 1000 maximum");
65+
message.diagnostics = [{ type, timestamp: 1 }];
66+
expect(isContextOverflow(message, 1000)).toBe(overflow);
67+
});
68+
6069
it.each([
6170
"Error: 400 Input length (265330) exceeds model's maximum context length (262144).",
6271
"Provider returned error: Input length 131393 exceeds the maximum allowed input length of 131,040 tokens.",

‎packages/ai/src/utils/overflow.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Overflow helpers classify provider overflow errors and retryable responses.
2+
import { isProviderRefusalAssistantError } from "@openclaw/llm-core/diagnostics";
23
import type { AssistantMessage } from "../types.js";
34

45
const CONFIGURED_CONTEXT_SIZE_OVERFLOW_RE =
@@ -214,6 +215,10 @@ function resolveContextInputTokens(message: AssistantMessage): number | undefine
214215
* @returns true if the message indicates a context overflow
215216
*/
216217
export function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {
218+
// A refusal explanation can mention overflow without authorizing compact-and-retry.
219+
if (isProviderRefusalAssistantError(message)) {
220+
return false;
221+
}
217222
// Case 1: Check error message patterns
218223
if (message.stopReason === "error" && message.errorMessage) {
219224
// Hoist so the regex closures keep the narrowing without assertions.

‎packages/llm-core/src/utils/diagnostics.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@ export interface AssistantMessageDiagnostic {
1313
details?: Record<string, unknown>;
1414
}
1515

16+
/** True when the provider explicitly refused the request payload. */
17+
export function isProviderRefusalAssistantError(
18+
message: { diagnostics?: AssistantMessageDiagnostic[] } | null | undefined,
19+
): boolean {
20+
return Boolean(
21+
message?.diagnostics?.some((diagnostic) => diagnostic.type === "provider_refusal"),
22+
);
23+
}
24+
1625
/** Formats arbitrary thrown values into diagnostic-safe text. */
1726
export function formatThrownValue(value: unknown): string {
1827
if (value instanceof Error) {

‎src/agents/embedded-agent-helpers/assistant-message-failures.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { AssistantMessage } from "../../llm/types.js";
2-
import { isReplayUnsafeAssistantError } from "../../llm/utils/retry.js";
2+
import { isTerminalAssistantError } from "../../llm/utils/retry.js";
33
import { extractErrorHttpStatus } from "../../shared/assistant-error-format.js";
44
import {
55
classifyFailoverSignal,
@@ -30,7 +30,7 @@ export function classifyAssistantFailoverReason(
3030
msg: AssistantMessage | undefined,
3131
opts?: { provider?: string; providerOwner?: PreparedProviderFailoverOwner | null },
3232
): FailoverReason | null {
33-
if (!msg || msg.stopReason !== "error" || isReplayUnsafeAssistantError(msg)) {
33+
if (!msg || msg.stopReason !== "error" || isTerminalAssistantError(msg)) {
3434
return null;
3535
}
3636
// Runtime preparation carries the resolved owner here so packaged runs do

‎src/agents/embedded-agent-helpers/error-text.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
12
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
23
import type { OpenClawConfig } from "../../config/types.openclaw.js";
34
import type { AssistantMessage } from "../../llm/types.js";
@@ -61,6 +62,20 @@ type ClassifiedAssistantErrorFacts = {
6162
reason: FailoverReason | null;
6263
status?: number;
6364
};
65+
export function formatProviderRefusalText(message: { diagnostics?: unknown }): string | undefined {
66+
const refusal = Array.isArray(message.diagnostics)
67+
? message.diagnostics.find(
68+
(diagnostic) => asOptionalRecord(diagnostic)?.type === "provider_refusal",
69+
)
70+
: undefined;
71+
if (!refusal) {
72+
return undefined;
73+
}
74+
const category = asOptionalRecord(asOptionalRecord(refusal)?.details)?.category;
75+
const safeCategory =
76+
typeof category === "string" && /^[a-z0-9_-]{1,64}$/i.test(category) ? category : undefined;
77+
return `The provider refused this request${safeCategory ? ` (category: ${safeCategory})` : ""}. Revise the request and try again.`;
78+
}
6479
function classifyAssistantErrorFacts(
6580
msg: AssistantMessage,
6681
opts?: AssistantErrorTextOptions,
@@ -100,6 +115,10 @@ export function formatAssistantErrorText(
100115
if (msg.stopReason !== "error" && !raw) {
101116
return undefined;
102117
}
118+
const providerRefusalText = formatProviderRefusalText(msg);
119+
if (providerRefusalText) {
120+
return providerRefusalText;
121+
}
103122
const formatCopy = renderFormatErrorCopy(raw);
104123
const classifiedFacts = facts ?? classifyAssistantErrorFacts(msg, opts);
105124
const {

‎src/agents/embedded-agent-runner/run.cross-provider-fallback-error-context.test-support.ts‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -121,19 +121,21 @@ function setupCompactionRemovedFallbackAttempt() {
121121
return isCurrentAttemptAssistant(assistant) && assistant.provider === "anthropic";
122122
});
123123
mockedClassifyFailoverReason.mockReturnValue("model_not_found");
124+
const assistant = makeAssistantMessageFixture({
125+
stopReason: "error",
126+
errorMessage: COMPACTION_REMOVED_ERROR_MESSAGE,
127+
provider: "anthropic",
128+
model: "test-model",
129+
content: [],
130+
});
124131
// The pinned profile may rotate to another same-provider credential before
125132
// the outer model fallback runs, so every credential attempt must fail alike.
126133
mockedRunEmbeddedAttempt.mockResolvedValue(
127134
makeAttemptResult({
128135
assistantTexts: [],
129-
lastAssistant: makeAssistantMessageFixture({
130-
stopReason: "error",
131-
errorMessage: COMPACTION_REMOVED_ERROR_MESSAGE,
132-
provider: "anthropic",
133-
model: "test-model",
134-
content: [],
135-
}),
136+
lastAssistant: assistant,
136137
currentAttemptAssistant: undefined,
138+
currentAttemptCompletedAssistant: assistant,
137139
}),
138140
);
139141
}
@@ -227,7 +229,7 @@ describe("runEmbeddedAgent cross-provider fallback error handling", () => {
227229
await expectDeepseekFallbackError(promise);
228230
});
229231

230-
it("falls back to the session assistant when compaction removes the current attempt slice", async () => {
232+
it("uses the completed assistant when compaction removes the current attempt slice", async () => {
231233
const getLastFormattedAssistant = captureFormattedAssistant();
232234
setupCompactionRemovedFallbackAttempt();
233235
const promise = runCompactionRemovedFallbackAttempt(state);

‎src/agents/embedded-agent-runner/run.empty-error-retry.test-support.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Full-entry coverage for retrying empty errored assistant turns.
22
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
33
import type { OpenClawTestState } from "../../test-utils/openclaw-test-state.js";
4+
import { makeAssistantMessageFixture } from "../test-helpers/assistant-message-fixtures.js";
45
import { makeAttemptResult } from "./run.overflow-compaction.fixture.js";
56
import {
67
mockedClassifyAssistantFailoverReason,
@@ -185,4 +186,75 @@ describe("runEmbeddedAgent silent-error retry", () => {
185186
fallbackSafe: false,
186187
});
187188
});
189+
describe("current-assistant provenance", () => {
190+
it("ignores a historical refusal after compaction", async () => {
191+
const refusal = makeAssistantMessageFixture({
192+
api: "anthropic-messages",
193+
provider: "anthropic",
194+
model: "claude-opus-5",
195+
stopReason: "error",
196+
content: [],
197+
errorMessage: "historical refusal",
198+
diagnostics: [{ type: "provider_refusal", timestamp: 1, details: { category: "cyber" } }],
199+
});
200+
mockedRunEmbeddedAttempt
201+
.mockResolvedValueOnce(
202+
makeAttemptResult({
203+
assistantTexts: [],
204+
lastAssistant: refusal,
205+
currentAttemptAssistant: undefined,
206+
currentAttemptCompletedAssistant: undefined,
207+
compactionCount: 1,
208+
}),
209+
)
210+
.mockResolvedValueOnce(successAttempt("anthropic", "claude-opus-5"));
211+
212+
const result = await runEmbeddedAgent({
213+
...createOverflowRunParams(state),
214+
provider: "anthropic",
215+
model: "claude-opus-5",
216+
runId: "run-historical-refusal-after-compaction",
217+
});
218+
219+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
220+
expect(result.meta.error).toBeUndefined();
221+
expect(result.payloads?.some((payload) => payload.text?.includes("refused"))).not.toBe(true);
222+
});
223+
224+
it("preserves a completed current refusal after transcript projection removes its slice", async () => {
225+
const refusal = makeAssistantMessageFixture({
226+
api: "anthropic-messages",
227+
provider: "anthropic",
228+
model: "claude-opus-5",
229+
stopReason: "error",
230+
content: [],
231+
errorMessage: "current refusal",
232+
diagnostics: [{ type: "provider_refusal", timestamp: 2, details: { category: "cyber" } }],
233+
});
234+
mockedRunEmbeddedAttempt
235+
.mockResolvedValueOnce(
236+
makeAttemptResult({
237+
assistantTexts: [],
238+
lastAssistant: undefined,
239+
currentAttemptAssistant: undefined,
240+
currentAttemptCompletedAssistant: refusal,
241+
compactionCount: 1,
242+
}),
243+
)
244+
.mockResolvedValueOnce(successAttempt("anthropic", "claude-opus-5"));
245+
246+
const result = await runEmbeddedAgent({
247+
...createOverflowRunParams(state),
248+
provider: "anthropic",
249+
model: "claude-opus-5",
250+
runId: "run-completed-refusal-without-transcript-slice",
251+
});
252+
253+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
254+
expect(result.payloads?.[0]).toMatchObject({
255+
isError: true,
256+
text: "The provider refused this request (category: cyber). Revise the request and try again.",
257+
});
258+
});
259+
});
188260
});

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,31 @@ describe("recoverEmbeddedRunOverflow", () => {
270270
expect(mocks.compact).not.toHaveBeenCalled();
271271
});
272272

273+
it.each([
274+
{ name: "refusal alone", promptError: null, action: "none" },
275+
{ name: "independent prompt overflow", promptError: overflowError(), action: "retry" },
276+
{
277+
name: "non-overflow prompt failure",
278+
promptError: new Error("transport disconnected"),
279+
action: "none",
280+
},
281+
])("preserves a structured refusal alongside $name", async ({ promptError, action }) => {
282+
const assistant = makeAssistantMessage({
283+
stopReason: "error",
284+
errorMessage: "Anthropic refusal: prompt is too long.",
285+
});
286+
assistant.diagnostics = [{ type: "provider_refusal", timestamp: 1 }];
287+
const input = makeInput({
288+
promptError,
289+
assistantOverflowCandidate: assistant,
290+
assistantErrorText: assistant.errorMessage,
291+
});
292+
293+
expect(await recoverEmbeddedRunOverflow(input)).toEqual({ action });
294+
expect(mocks.compact).toHaveBeenCalledTimes(action === "retry" ? 1 : 0);
295+
expect(mocks.truncateOversizedToolResults).not.toHaveBeenCalled();
296+
});
297+
273298
it("preserves compaction recovery after a bodyless 413", async () => {
274299
const assistantOverflowCandidate = makeAssistantMessage({
275300
stopReason: "error",

0 commit comments

Comments
 (0)