Skip to content

Commit db31c6f

Browse files
committed
fix(agents): centralize terminal retry policy
1 parent 7403ee6 commit db31c6f

11 files changed

Lines changed: 225 additions & 205 deletions

‎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-runner/run.empty-error-retry.test-support.ts‎

Lines changed: 31 additions & 162 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
// Full-entry coverage for retrying empty errored assistant turns.
2-
import http from "node:http";
3-
import type { AddressInfo } from "node:net";
42
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
5-
import type { Context, Model } from "../../../packages/ai/src/types.js";
63
import type { OpenClawTestState } from "../../test-utils/openclaw-test-state.js";
74
import { makeAssistantMessageFixture } from "../test-helpers/assistant-message-fixtures.js";
85
import { makeAttemptResult } from "./run.overflow-compaction.fixture.js";
@@ -113,129 +110,6 @@ describe("runEmbeddedAgent silent-error retry", () => {
113110
expect(result.payloads).toBeUndefined();
114111
});
115112

116-
it.each(["This request is not allowed.", "This request is refused; prompt is too long."])(
117-
"surfaces a loopback Anthropic transport refusal without retrying: %s",
118-
async (explanation) => {
119-
let providerRequests = 0;
120-
const server = http.createServer((request, response) => {
121-
providerRequests += 1;
122-
request.resume();
123-
response.writeHead(200, { "content-type": "text/event-stream" });
124-
response.end(
125-
[
126-
{ type: "message_start", message: { id: "msg_refusal", usage: {} } },
127-
{
128-
type: "message_delta",
129-
delta: {
130-
stop_reason: "refusal",
131-
stop_details: {
132-
type: "refusal",
133-
category: "reasoning_extraction",
134-
explanation,
135-
},
136-
},
137-
usage: { input_tokens: 3, output_tokens: 0 },
138-
},
139-
{ type: "message_stop" },
140-
]
141-
.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
142-
.join(""),
143-
);
144-
});
145-
await new Promise<void>((resolve, reject) => {
146-
server.once("error", reject);
147-
server.listen(0, "127.0.0.1", resolve);
148-
});
149-
const { port } = server.address() as AddressInfo;
150-
const model = {
151-
id: "claude-opus-5",
152-
name: "Claude Opus 5 refusal proof",
153-
api: "anthropic-messages",
154-
provider: "anthropic",
155-
baseUrl: `http://127.0.0.1:${port}`,
156-
reasoning: true,
157-
input: ["text"],
158-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
159-
contextWindow: 200_000,
160-
maxTokens: 4_096,
161-
} satisfies Model<"anthropic-messages">;
162-
const context = {
163-
messages: [{ role: "user", content: "hello", timestamp: 1 }],
164-
} satisfies Context;
165-
166-
try {
167-
mockedRunEmbeddedAttempt.mockImplementation(async () => {
168-
const { streamAnthropic } =
169-
await import("../../../packages/ai/src/providers/anthropic.js");
170-
const stream = streamAnthropic(model, context, { apiKey: "redacted-fixture-token" });
171-
for await (const event of stream) {
172-
void event;
173-
}
174-
const assistant = await stream.result();
175-
return makeAttemptResult({
176-
assistantTexts: [],
177-
lastAssistant: assistant,
178-
currentAttemptAssistant: assistant,
179-
});
180-
});
181-
182-
const result = await runEmbeddedAgent({
183-
...createOverflowRunParams(state),
184-
provider: "anthropic",
185-
model: "claude-opus-5",
186-
runId: "run-anthropic-refusal",
187-
});
188-
189-
expect(providerRequests).toBe(1);
190-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
191-
expect(result.payloads?.[0]).toMatchObject({
192-
isError: true,
193-
text: "The provider refused this request (category: reasoning_extraction).",
194-
});
195-
expect(result.meta.error).toMatchObject({
196-
message: "The provider refused this request (category: reasoning_extraction).",
197-
});
198-
} finally {
199-
await new Promise<void>((resolve, reject) => {
200-
server.close((error) => (error ? reject(error) : resolve()));
201-
});
202-
}
203-
},
204-
);
205-
206-
it("also treats Bedrock Anthropic refusal diagnostics as terminal", async () => {
207-
const refusal = emptyErrorAttempt("amazon-bedrock", "claude-opus-5");
208-
const diagnostics = [
209-
{
210-
type: "provider_refusal",
211-
timestamp: 0,
212-
details: { provider: "amazon-bedrock", category: "cyber" },
213-
},
214-
];
215-
refusal.lastAssistant!.diagnostics = diagnostics;
216-
refusal.currentAttemptAssistant!.diagnostics = diagnostics;
217-
mockedRunEmbeddedAttempt.mockResolvedValueOnce(refusal);
218-
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
219-
successAttempt("amazon-bedrock", "claude-opus-5"),
220-
);
221-
222-
const result = await runEmbeddedAgent({
223-
...createOverflowRunParams(state),
224-
provider: "amazon-bedrock",
225-
model: "claude-opus-5",
226-
runId: "run-bedrock-refusal",
227-
});
228-
229-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
230-
expect(result.payloads?.[0]).toMatchObject({
231-
isError: true,
232-
text: "The provider refused this request (category: cyber).",
233-
});
234-
expect(result.meta.error).toMatchObject({
235-
message: "The provider refused this request (category: cyber).",
236-
});
237-
});
238-
239113
it("does not intercept concrete non-transient failover errors", async () => {
240114
mockedClassifyFailoverReason.mockReturnValue("model_not_found");
241115
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
@@ -313,44 +187,39 @@ describe("runEmbeddedAgent silent-error retry", () => {
313187
});
314188
});
315189
describe("current-assistant provenance", () => {
316-
it.each([0, 1])(
317-
"ignores a historical refusal when a later empty attempt reports %s compactions",
318-
async (compactionCount) => {
319-
const refusal = makeAssistantMessageFixture({
320-
api: "anthropic-messages",
321-
provider: "anthropic",
322-
model: "claude-opus-5",
323-
stopReason: "error",
324-
content: [],
325-
errorMessage: "historical refusal",
326-
diagnostics: [{ type: "provider_refusal", timestamp: 1, details: { category: "cyber" } }],
327-
});
328-
mockedRunEmbeddedAttempt
329-
.mockResolvedValueOnce(
330-
makeAttemptResult({
331-
assistantTexts: [],
332-
lastAssistant: refusal,
333-
currentAttemptAssistant: undefined,
334-
currentAttemptCompletedAssistant: undefined,
335-
compactionCount,
336-
}),
337-
)
338-
.mockResolvedValueOnce(successAttempt("anthropic", "claude-opus-5"));
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"));
339211

340-
const result = await runEmbeddedAgent({
341-
...createOverflowRunParams(state),
342-
provider: "anthropic",
343-
model: "claude-opus-5",
344-
runId: `run-historical-refusal-empty-${compactionCount}`,
345-
});
212+
const result = await runEmbeddedAgent({
213+
...createOverflowRunParams(state),
214+
provider: "anthropic",
215+
model: "claude-opus-5",
216+
runId: "run-historical-refusal-after-compaction",
217+
});
346218

347-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
348-
expect(result.meta.error).toBeUndefined();
349-
expect(result.payloads?.some((payload) => payload.text?.includes("refused"))).not.toBe(
350-
true,
351-
);
352-
},
353-
);
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+
});
354223

355224
it("preserves a completed current refusal after transcript projection removes its slice", async () => {
356225
const refusal = makeAssistantMessageFixture({

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

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import { isProviderRefusalAssistantError } from "@openclaw/llm-core/diagnostics";
21
import type { ThinkLevel } from "../../../auto-reply/thinking.js";
32
import type { AssistantMessage } from "../../../llm/types.js";
4-
import { isReplayUnsafeAssistantError } from "../../../llm/utils/retry.js";
3+
import { isTerminalAssistantError } from "../../../llm/utils/retry.js";
54
import { projectAgentRunAttemptTerminal } from "../../agent-run-terminal-outcome.js";
65
import type { AuthProfileFailureReason, AuthProfileStore } from "../../auth-profiles.js";
76
import {
@@ -123,13 +122,11 @@ export async function handleEmbeddedAssistantFailure(input: {
123122
isShortWindowRateLimitMessage(input.attemptAssistant?.errorMessage),
124123
},
125124
);
126-
const replayUnsafeAssistantError = isReplayUnsafeAssistantError(input.attemptAssistant);
127-
const providerRefusal = isProviderRefusalAssistantError(input.attemptAssistant);
128-
if (replayUnsafeAssistantError || providerRefusal || !isCurrentAttemptReplaySafe(input.attempt)) {
125+
const terminalAssistantError = isTerminalAssistantError(input.attemptAssistant);
126+
if (terminalAssistantError || !isCurrentAttemptReplaySafe(input.attempt)) {
129127
return buildOutcome(input, {
130128
action: "proceed",
131-
assistantProfileFailureReason:
132-
replayUnsafeAssistantError || providerRefusal ? null : assistantProfileFailureReason,
129+
assistantProfileFailureReason: terminalAssistantError ? null : assistantProfileFailureReason,
133130
});
134131
}
135132
if (fallbackThinking && !terminalInterrupted) {

‎src/agents/embedded-agent-runner/run/attempt-result.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ describe("attempt result projection", () => {
155155
});
156156

157157
expect(result.currentAttemptAssistant).toBeUndefined();
158-
expect(result.currentAttemptCompletedAssistant).toBe(assistant);
158+
expect(result.currentAttemptCompletedAssistant).toEqual(assistant);
159159
expect(recordEvent).toHaveBeenCalledWith(
160160
"session.ended",
161161
expect.objectContaining({ status: expectedStatus, terminalError }),

‎src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/** Owns side-effect-sensitive retry and silent-reply recovery policy. */
2-
import { isReplayUnsafeAssistantError } from "../../../llm/utils/retry.js";
2+
import { isTerminalAssistantError } from "../../../llm/utils/retry.js";
33
import { hasAcceptedSessionSpawn } from "../../accepted-session-spawn.js";
44
import { hasOnlyAssistantReasoningContent } from "../../replay-turn-classification.js";
55
import { TOOL_FAILURE_INSTRUCTION } from "../../tool-outcome-instructions.js";
@@ -71,7 +71,7 @@ export function shouldRetrySilentErrorAssistantTurn(params: {
7171
}
7272

7373
const assistant = params.assistant;
74-
if (!assistant || assistant.stopReason !== "error" || isReplayUnsafeAssistantError(assistant)) {
74+
if (!assistant || assistant.stopReason !== "error" || isTerminalAssistantError(assistant)) {
7575
return false;
7676
}
7777

‎src/agents/embedded-agent-runner/run/terminal-resolution.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
22
import { SILENT_REPLY_TOKEN } from "../../../auto-reply/tokens.js";
33
import { classifyAgentExecResult } from "../../../commands/agent-exec-result.js";
4+
import {
5+
PROVIDER_FAILURE_WITH_OUTPUT_ERROR_CODE,
6+
PROVIDER_POST_DISPATCH_AMBIGUITY_ERROR_CODE,
7+
} from "../../../llm/types.js";
48
import {
59
buildEmbeddedRunnerAssistant,
610
makeEmbeddedRunnerAttempt,
@@ -349,6 +353,43 @@ describe("terminal resolution", () => {
349353
},
350354
);
351355

356+
it.each([PROVIDER_FAILURE_WITH_OUTPUT_ERROR_CODE, PROVIDER_POST_DISPATCH_AMBIGUITY_ERROR_CODE])(
357+
"does not retry terminal provider outcome %s after compaction",
358+
async (errorCode) => {
359+
const assistant = emptyAssistant({
360+
stopReason: "error",
361+
errorCode,
362+
providerReplay: {
363+
v: 1,
364+
type: "anthropic-compaction",
365+
data: "summary",
366+
provider: "anthropic",
367+
api: "anthropic-messages",
368+
model: "claude-sonnet-4-6",
369+
baseUrlHash: "route-a",
370+
},
371+
});
372+
const attempt = makeEmbeddedRunnerAttempt({
373+
assistantTexts: [],
374+
currentAttemptAssistant: assistant,
375+
currentAttemptReplayMetadata: { hadPotentialSideEffects: false, replaySafe: true },
376+
});
377+
const input = makeTerminalInput({
378+
attempt,
379+
attemptAssistant: assistant,
380+
maxEmptyResponseRetryAttempts: 0,
381+
});
382+
383+
const resolved = await resolveEmbeddedRunTerminal(input);
384+
385+
expect(resolved).toMatchObject({
386+
action: "complete",
387+
result: { meta: { error: { kind: "incomplete_turn", fallbackSafe: false } } },
388+
});
389+
expect(input.armPostCompactionGuard).not.toHaveBeenCalled();
390+
},
391+
);
392+
352393
it("keeps the current incomplete turn fallback-safe after a prior-turn refusal", async () => {
353394
const assistant = emptyAssistant({ stopReason: "length" });
354395
const priorRefusal = emptyAssistant({

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { randomBytes } from "node:crypto";
22
import { isCompactionReplayCheckpoint } from "@openclaw/ai/transports";
3-
import { isProviderRefusalAssistantError } from "@openclaw/llm-core/diagnostics";
43
import { SILENT_REPLY_TOKEN } from "../../../auto-reply/tokens.js";
54
import { freezeDiagnosticTraceContext } from "../../../infra/diagnostic-trace-context.js";
65
import { formatErrorMessage } from "../../../infra/errors.js";
76
import type { AssistantMessage } from "../../../llm/types.js";
7+
import { isTerminalAssistantError } from "../../../llm/utils/retry.js";
88
import type { ProviderRouteOverridePresence } from "../../../plugin-sdk/provider-model-types.js";
99
import {
1010
classifyAgentRunTerminalOutcome,
@@ -351,7 +351,7 @@ export async function resolveEmbeddedRunTerminal(input: {
351351
return { action: "retry" };
352352
}
353353
const completedEmptyFinalization = input.settledTurnFinalizationOutcome === "completed-empty";
354-
const providerRefusal = isProviderRefusalAssistantError(input.attemptAssistant);
354+
const terminalAssistantError = isTerminalAssistantError(input.attemptAssistant);
355355
const incompleteTurnText =
356356
emptyAssistantReplyIsSilent ||
357357
(completedEmptyFinalization && !requiresVisibleTerminalReply(runParams))
@@ -372,7 +372,7 @@ export async function resolveEmbeddedRunTerminal(input: {
372372
!promptError &&
373373
!attempt.lastToolError &&
374374
!hasAttemptTerminalState(attempt) &&
375-
!providerRefusal &&
375+
!terminalAssistantError &&
376376
!input.replayState.hadPotentialSideEffects,
377377
);
378378
const terminalToolPresentation = incompleteTurnFallbackSafe
@@ -390,7 +390,7 @@ export async function resolveEmbeddedRunTerminal(input: {
390390
!attempt.yieldDetected &&
391391
!attempt.didSendDeterministicApprovalPrompt &&
392392
!attempt.lastToolError &&
393-
!providerRefusal &&
393+
!terminalAssistantError &&
394394
!input.replayState.hadPotentialSideEffects &&
395395
retryState.compactionContinuationAttempts < 1
396396
) {

0 commit comments

Comments
 (0)