Skip to content

Commit e2deb87

Browse files
fix(agents): preserve valid CLI session bindings (#128732)
* fix(agents): preserve CLI session binding on format-class failover shouldClearFailedCliSessionBinding cleared the stored CLI session binding for every FailoverError, including format-class failures (output limit exceeded, parser error, unsupported image input). A format-class failover means the stream could not be read, not that the CLI session on disk is invalid — clearing the binding silently lost the conversation context on the next turn. Narrow the condition to only session-invalidating failover reasons (session_expired, auth, auth_permanent) using a whitelist so new reasons default to preserving the binding. Fixes #128698 * fix(agents): preserve valid CLI session bindings * fix(agents): retain CLI binding across format recovery * fix(agents): scope fresh CLI recovery by backend * docs(plugins): document CLI recovery policy --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent dca05ea commit e2deb87

10 files changed

Lines changed: 324 additions & 31 deletions

File tree

‎docs/plugins/cli-backend-plugins.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,23 @@ model-alias, session, image, and watchdog fields as the bundled
215215
| `imagePathScope` | Where staged image files live before handoff: `temp` or `workspace` |
216216
| `serialize` | Keep same-backend runs ordered |
217217
| `reseedFromRawTranscriptWhenUncompacted` | Opt in to bounded raw-transcript reseed before compaction for safe session resets |
218+
| `freshSessionRecovery` | Fresh recovery policy after a recoverable resumed-session failure |
218219
| `reliability.watchdog` | No-output timeout tuning, separate for fresh vs resumed runs |
219220

221+
`freshSessionRecovery` is a backend-owned compatibility contract:
222+
223+
- Leave it undefined or set it to `"replace-binding"` to preserve the legacy
224+
clear-and-reseed behavior. OpenClaw clears the persisted binding and retries
225+
with a fresh session when the failure is eligible for recovery.
226+
- Set it to `"invalidated-only"` to suppress fresh replacement unless the
227+
canonical invalidation predicate proves the old session is dead. Currently,
228+
only `session_expired` does so.
229+
230+
Choose the value from the CLI or SDK session contract, not from a provider id
231+
or broad error class. The bundled Anthropic backend uses `"invalidated-only"`;
232+
its Agent SDK contract does not treat non-expiration failures as proof that the
233+
conversation can no longer resume.
234+
220235
Prefer the smallest static config that matches the CLI. Add plugin callbacks
221236
only for behavior that really belongs to the backend.
222237

‎extensions/anthropic/cli-backend.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ export function buildAnthropicCliBackend(
218218
sessionArgs: ["--session-id", "{sessionId}"],
219219
sessionMode: "always",
220220
reseedFromRawTranscriptWhenUncompacted: true,
221+
freshSessionRecovery: "invalidated-only",
221222
sessionIdFields: [...CLAUDE_CLI_SESSION_ID_FIELDS],
222223
systemPromptFileArg: "--append-system-prompt-file",
223224
systemPromptMode: "append",

‎extensions/anthropic/index.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ describe("anthropic provider replay hooks", () => {
9797
expect(backend.bundleMcp).toBe(true);
9898
expectFields(backend.config, {
9999
command: "claude",
100+
freshSessionRecovery: "invalidated-only",
100101
modelArg: "--model",
101102
sessionArgs: ["--session-id", "{sessionId}"],
102103
});

‎src/agents/cli-runner.reliability.test.ts‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import {
5656
requestHeartbeatMock,
5757
supervisorSpawnMock,
5858
} from "./cli-runner.test-support.js";
59+
import { runCliRecovery } from "./cli-runner/cli-run-recovery.js";
5960
import { executePreparedCliRun } from "./cli-runner/execute.js";
6061
import {
6162
resolveCliNoOutputTimeoutMs,
@@ -65,6 +66,7 @@ import { prepareCliRunContext } from "./cli-runner/prepare.js";
6566
import { hashCliReseedPrompt } from "./cli-runner/reseed-envelope.js";
6667
import * as sessionHistoryModule from "./cli-runner/session-history.js";
6768
import type { PreparedCliRunContext } from "./cli-runner/types.js";
69+
import { FailoverError } from "./failover-error.js";
6870
import { runAgentHarnessBeforeMessageWriteHook } from "./harness/hook-helpers.js";
6971
import { MAX_AGENT_HOOK_HISTORY_MESSAGES } from "./harness/hook-history.js";
7072

@@ -2092,6 +2094,130 @@ describe("runCliAgent reliability", () => {
20922094
expect(clearBeforeRetry).not.toHaveBeenCalled();
20932095
});
20942096

2097+
it("does not start a fresh CLI attempt when format recovery retains the binding", async () => {
2098+
supervisorSpawnMock.mockClear();
2099+
supervisorSpawnMock.mockResolvedValueOnce(
2100+
makeManagedRun({
2101+
stdout: [
2102+
JSON.stringify({
2103+
type: "assistant",
2104+
message: {
2105+
model: "<synthetic>",
2106+
content: [{ type: "text", text: "No response requested." }],
2107+
},
2108+
}),
2109+
JSON.stringify({ type: "result", subtype: "success", result: "" }),
2110+
].join("\n"),
2111+
}),
2112+
);
2113+
const clearBeforeRetry = vi.fn(async () => false);
2114+
const { dir, sessionFile } = createSessionFile({
2115+
history: [{ role: "user", content: "earlier context" }],
2116+
});
2117+
2118+
try {
2119+
const context = makeClaudePreparedContext({
2120+
sessionKey: "agent:main:subagent:retained-format",
2121+
runId: "run-retained-format",
2122+
cliSessionId: "retained-cli-session",
2123+
openClawHistoryPrompt: CLI_RESEED_PROMPT,
2124+
});
2125+
context.preparedBackend.backend = {
2126+
...context.preparedBackend.backend,
2127+
freshSessionRecovery: "invalidated-only",
2128+
output: "jsonl",
2129+
input: "stdin",
2130+
jsonlDialect: "claude-stream-json",
2131+
};
2132+
context.backendResolved.config = context.preparedBackend.backend;
2133+
2134+
await expect(
2135+
runPreparedCliAgent({
2136+
...context,
2137+
params: {
2138+
...context.params,
2139+
agentId: "main",
2140+
sessionFile,
2141+
workspaceDir: dir,
2142+
onBeforeFreshCliSessionRetry: clearBeforeRetry,
2143+
},
2144+
}),
2145+
).rejects.toMatchObject({ reason: "format", code: "cli_synthetic_no_response" });
2146+
2147+
expect(supervisorSpawnMock).toHaveBeenCalledTimes(1);
2148+
expect(clearBeforeRetry).not.toHaveBeenCalled();
2149+
} finally {
2150+
fs.rmSync(dir, { recursive: true, force: true });
2151+
}
2152+
});
2153+
2154+
it.each([
2155+
["format", "cli_synthetic_no_response"],
2156+
["timeout", "cli_no_output_timeout"],
2157+
] as const)(
2158+
"keeps undefined Gemini recovery policy compatible after %s failover",
2159+
async (reason, code) => {
2160+
const context = buildPreparedContext({
2161+
provider: "google-gemini-cli",
2162+
sessionKey: `agent:main:gemini-${reason}`,
2163+
cliSessionId: "gemini-resumed-session",
2164+
openClawHistoryPrompt: CLI_RESEED_PROMPT,
2165+
});
2166+
context.preparedBackend.backend = {
2167+
command: "gemini",
2168+
args: ["--prompt", "{prompt}"],
2169+
resumeArgs: ["--resume", "{sessionId}", "--prompt", "{prompt}"],
2170+
output: "jsonl",
2171+
jsonlDialect: "gemini-stream-json",
2172+
input: "arg",
2173+
sessionMode: "existing",
2174+
};
2175+
context.backendResolved.config = context.preparedBackend.backend;
2176+
expect(context.preparedBackend.backend.freshSessionRecovery).toBeUndefined();
2177+
2178+
const executeAttempt = vi
2179+
.fn()
2180+
.mockRejectedValueOnce(
2181+
new FailoverError(`Gemini ${reason} failure`, {
2182+
reason,
2183+
code,
2184+
provider: "google-gemini-cli",
2185+
model: "gemini-3.1-pro-preview",
2186+
}),
2187+
)
2188+
.mockResolvedValueOnce({ sessionId: `gemini-fresh-${reason}` });
2189+
const clearBeforeRetry = vi.fn(async () => true);
2190+
2191+
const result = await runCliRecovery({
2192+
context: {
2193+
...context,
2194+
params: {
2195+
...context.params,
2196+
onBeforeFreshCliSessionRetry: clearBeforeRetry,
2197+
},
2198+
},
2199+
executeAttempt,
2200+
finishAttempt: async (attempt: { sessionId: string }) =>
2201+
({
2202+
payloads: [{ text: "Gemini recovered" }],
2203+
meta: { cliSessionId: attempt.sessionId },
2204+
}) as never,
2205+
finishDeliveredFailure: async () => undefined,
2206+
onTerminalFailure: async () => {},
2207+
});
2208+
2209+
expect(executeAttempt).toHaveBeenCalledTimes(2);
2210+
expect(executeAttempt.mock.calls[0]?.[0]).toBe("gemini-resumed-session");
2211+
expect(executeAttempt.mock.calls[1]?.[0]).toBeUndefined();
2212+
expect(clearBeforeRetry).toHaveBeenCalledWith({
2213+
provider: "google-gemini-cli",
2214+
reason,
2215+
sessionId: "gemini-resumed-session",
2216+
});
2217+
expect(requireRecord(result.meta, "result meta").cliSessionId).toBe(`gemini-fresh-${reason}`);
2218+
},
2219+
);
2220+
20952221
it.each(["timeout", "unknown", "context_overflow", "format"] as const)(
20962222
"retries a fresh CLI session after recoverable %s failover without a failed agent_end",
20972223
async (reason) => {
@@ -4050,6 +4176,7 @@ describe("runCliAgent reliability", () => {
40504176
openClawHistoryPrompt:
40514177
"Continue this conversation using the OpenClaw transcript below.\n\nUser: recovered history\n\n<next_user_message>\nhi\n</next_user_message>",
40524178
});
4179+
context.preparedBackend.backend.freshSessionRecovery = "invalidated-only";
40534180
const clearBeforeRetry = vi.fn(async () => true);
40544181

40554182
try {

‎src/agents/cli-runner/cli-run-recovery.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { formatErrorMessage } from "../../infra/errors.js";
2+
import { isCliSessionInvalidatingFailoverReason } from "../cli-session.js";
23
import type { EmbeddedAgentRunResult } from "../embedded-agent-runner.js";
34
import { type FailoverError, isFailoverError } from "../failover-error.js";
45
import { createCliFailoverError } from "./exit-error.js";
@@ -21,10 +22,19 @@ export function resolveCliSessionId(reusableCliSession: CliReusableSession): str
2122
function shouldRetryFreshCliSessionAfterFailover(params: {
2223
error: FailoverError;
2324
hasHistoryPrompt: boolean;
25+
recoveryPolicy?: "replace-binding" | "invalidated-only";
2426
}): boolean {
2527
if (!params.hasHistoryPrompt) {
2628
return false;
2729
}
30+
// Some CLIs can safely replace a resumable conversation after transport or
31+
// format failures. Backends that cannot must positively prove invalidation.
32+
if (
33+
params.recoveryPolicy === "invalidated-only" &&
34+
!isCliSessionInvalidatingFailoverReason(params.error.reason)
35+
) {
36+
return false;
37+
}
2838
switch (params.error.reason) {
2939
case "session_expired":
3040
return true;
@@ -163,6 +173,7 @@ export async function runCliRecovery<TAttempt>(params: {
163173
shouldRetryFreshCliSessionAfterFailover({
164174
error: recoveryError,
165175
hasHistoryPrompt: Boolean(context.openClawHistoryPrompt),
176+
recoveryPolicy: context.preparedBackend.backend.freshSessionRecovery,
166177
}) &&
167178
retryableSessionId &&
168179
runParams.sessionKey

‎src/agents/cli-session.test.ts‎

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ import {
1313
clearCliSession,
1414
getCliSessionBinding,
1515
hashCliSessionText,
16+
isCliSessionInvalidatingFailoverReason,
1617
resolveCliSessionClearReason,
1718
resolveCliSessionReuse,
1819
setCliSessionBinding,
1920
setCliSessionId,
2021
shouldClearFailedCliSessionBinding,
2122
} from "./cli-session.js";
2223
import { FailoverError } from "./failover-error.js";
24+
import { FAILOVER_REASONS } from "./failover/signal.js";
2325

2426
describe("cli-session helpers", () => {
2527
it("persists binding metadata alongside legacy session ids", () => {
@@ -628,26 +630,20 @@ describe("cli-session helpers", () => {
628630
});
629631

630632
it("shares failed reused-session cleanup policy across CLI entry points", () => {
631-
const failover = new FailoverError("session expired", {
632-
reason: "session_expired",
633-
provider: "claude-cli",
634-
model: "claude-opus-4-8",
635-
});
636633
const abort = Object.assign(new Error("aborted"), { name: "AbortError" });
637634

638635
const binding = { sessionId: "reused" };
639636
const forkBinding = { sessionId: "fork-source", forkNextResume: true as const };
640637

641-
expect(shouldClearFailedCliSessionBinding({ error: failover, binding })).toBe(true);
642-
expect(shouldClearFailedCliSessionBinding({ error: failover, binding: forkBinding })).toBe(
643-
true,
644-
);
645-
expect(resolveCliSessionClearReason(failover)).toBe("session_expired");
646638
expect(shouldClearFailedCliSessionBinding({ error: abort, binding })).toBe(true);
647639
expect(shouldClearFailedCliSessionBinding({ error: abort, binding: forkBinding })).toBe(false);
648640
expect(
649641
shouldClearFailedCliSessionBinding({
650-
error: failover,
642+
error: new FailoverError("session expired", {
643+
reason: "session_expired",
644+
provider: "claude-cli",
645+
model: "claude-opus-4-8",
646+
}),
651647
binding,
652648
hasNewGeneratedMediaTask: true,
653649
}),
@@ -656,6 +652,17 @@ describe("cli-session helpers", () => {
656652
expect(
657653
shouldClearFailedCliSessionBinding({ error: new Error("provider failed"), binding }),
658654
).toBe(false);
659-
expect(shouldClearFailedCliSessionBinding({ error: failover })).toBe(false);
655+
expect(shouldClearFailedCliSessionBinding({ error: abort })).toBe(false);
656+
});
657+
658+
it.each(FAILOVER_REASONS)("only clears binding for a provider-expired session: %s", (reason) => {
659+
const error = new FailoverError("failover", { reason, provider: "claude-cli" });
660+
const invalidatesSession = reason === "session_expired";
661+
662+
expect(FAILOVER_REASONS).toHaveLength(16);
663+
expect(isCliSessionInvalidatingFailoverReason(reason)).toBe(invalidatesSession);
664+
expect(shouldClearFailedCliSessionBinding({ error, binding: { sessionId: "reused" } })).toBe(
665+
invalidatesSession,
666+
);
660667
});
661668
});

‎src/agents/cli-session.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { CliSessionBinding, SessionEntry } from "../config/sessions.js";
1010
import { normalizeCliSessionReseedReceipt } from "../config/sessions/cli-session-binding.js";
1111
import { readErrorName } from "../infra/errors.js";
1212
import { isFailoverError } from "./failover-error.js";
13+
import type { FailoverReason } from "./failover/signal.js";
1314
export {
1415
clearAllCliSessions,
1516
getCliSessionBinding,
@@ -18,6 +19,13 @@ export {
1819

1920
const CLAUDE_CLI_BACKEND_ID = "claude-cli";
2021

22+
/** Whether a failover proves the provider-side conversation can no longer be resumed. */
23+
export function isCliSessionInvalidatingFailoverReason(reason: FailoverReason): boolean {
24+
// Auth identity changes are handled by the reuse fingerprint's auth epoch.
25+
// Other execution failures say nothing about the persisted transcript.
26+
return reason === "session_expired";
27+
}
28+
2129
/** Hash CLI session-sensitive text so reuse checks can compare stable fingerprints. */
2230
export function hashCliSessionText(value: string | undefined): string | undefined {
2331
const trimmed = normalizeOptionalString(value);
@@ -126,7 +134,7 @@ export function shouldClearFailedCliSessionBinding(params: {
126134
return false;
127135
}
128136
if (isFailoverError(params.error)) {
129-
return true;
137+
return isCliSessionInvalidatingFailoverReason(params.error.reason);
130138
}
131139
// A pre-successor fork abort keeps its one-shot marker for the next turn.
132140
return params.binding?.forkNextResume !== true && readErrorName(params.error) === "AbortError";

0 commit comments

Comments
 (0)