Skip to content

Commit b336984

Browse files
authored
refactor(agents): unify CLI spawn/live failure policy lanes (#122164)
1 parent ebb2770 commit b336984

9 files changed

Lines changed: 286 additions & 232 deletions

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,52 @@ describe("runCliAgent reliability", () => {
841841
expect(supervisorSpawnMock).toHaveBeenCalledTimes(2);
842842
});
843843

844+
it("does not treat unsupported-flag wording fragments as a Claude downgrade", async () => {
845+
supervisorSpawnMock.mockClear();
846+
supervisorSpawnMock.mockResolvedValueOnce(
847+
makeManagedRun({
848+
exitCode: 1,
849+
durationMs: 25,
850+
stderr: "Claude exited unexpectedly while using --resume-session-at",
851+
}),
852+
);
853+
const clearBeforeRetry = vi.fn(async () => true);
854+
const context = makeClaudePreparedContext({
855+
sessionKey: "agent:main:resume-token-boundary",
856+
runId: "run-resume-token-boundary",
857+
cliSessionId: "existing-session",
858+
openClawHistoryPrompt: CLI_RESEED_PROMPT,
859+
});
860+
context.preparedBackend.backend = {
861+
...context.preparedBackend.backend,
862+
resumeArgs: ["--resume", "{sessionId}"],
863+
forkArg: "--fork-session",
864+
resumeAtArg: "--resume-session-at",
865+
};
866+
context.params.cliSessionBinding = {
867+
sessionId: "existing-session",
868+
resumeCheckpointId: "assistant-before-stall",
869+
forkNextResume: true,
870+
};
871+
872+
await expect(
873+
runPreparedCliAgent({
874+
...context,
875+
params: {
876+
...context.params,
877+
forkCliSessionOnResume: true,
878+
claimCliSessionFork: vi.fn(async () => true),
879+
restoreCliSessionFork: vi.fn(async () => {}),
880+
persistCliSessionForkSuccessor: vi.fn(async () => {}),
881+
onBeforeFreshCliSessionRetry: clearBeforeRetry,
882+
},
883+
}),
884+
).rejects.toThrow("exited unexpectedly");
885+
886+
expect(clearBeforeRetry).not.toHaveBeenCalled();
887+
expect(supervisorSpawnMock).toHaveBeenCalledTimes(1);
888+
});
889+
844890
it("preserves fresh retry for direct CLI callers without a pre-clear hook", async () => {
845891
supervisorSpawnMock.mockClear();
846892
supervisorSpawnMock.mockResolvedValueOnce(

‎src/agents/cli-runner.ts‎

Lines changed: 38 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import {
4747
attachCliMessagingDeliveryEvidence,
4848
getCliMessagingDeliveryEvidence,
4949
} from "./cli-runner/delivery-evidence.js";
50+
import { createCliFailoverError } from "./cli-runner/exit-error.js";
5051
import { cliBackendLog, formatCliBackendOutputDigest } from "./cli-runner/log.js";
5152
import { hashCliReseedPrompt } from "./cli-runner/reseed-envelope.js";
5253
import {
@@ -63,13 +64,12 @@ import type {
6364
RunCliAgentParams,
6465
} from "./cli-runner/types.js";
6566
import { claudeCliSessionTranscriptHasContent as claudeCliSessionTranscriptHasContentImpl } from "./command/attempt-execution.helpers.js";
66-
import { classifyFailoverReason, isFailoverErrorMessage } from "./embedded-agent-helpers.js";
6767
import type { EmbeddedAgentRunResult } from "./embedded-agent-runner.js";
6868
import { waitForDeferredTurnMaintenanceForSession } from "./embedded-agent-runner/context-engine-maintenance.js";
6969
import { resolveExplicitFinalSourceReplyDeliveryEvidence } from "./embedded-agent-runner/delivery-evidence.js";
7070
import { resolveAuthProfileFailureReason } from "./embedded-agent-runner/run/auth-profile-failure-policy.js";
7171
import { buildEmbeddedRunPayloads } from "./embedded-agent-runner/run/payloads.js";
72-
import { FailoverError, isFailoverError, resolveFailoverStatus } from "./failover-error.js";
72+
import { coerceToFailoverError, FailoverError, isFailoverError } from "./failover-error.js";
7373
import {
7474
awaitAgentEndSideEffects,
7575
runAgentEndSideEffects,
@@ -216,31 +216,10 @@ function isUnsupportedCliResumeAtError(error: unknown, resumeAtArg: string): boo
216216
const message = formatErrorMessage(error).toLowerCase();
217217
return (
218218
message.includes(resumeAtArg.toLowerCase()) &&
219-
["unknown", "unexpected", "unrecognized", "not recognized"].some((token) =>
220-
message.includes(token),
221-
)
219+
/\b(?:unknown|unexpected|unrecognized)\b|\bnot\s+recognized\b/.test(message)
222220
);
223221
}
224222

225-
function formatCliEmptyOutputDiagnostics(output: CliOutput): string | undefined {
226-
const process = output.diagnostics?.process;
227-
if (!process) {
228-
return undefined;
229-
}
230-
return [
231-
`backend=${process.backendId}`,
232-
`reason=${process.processReason}`,
233-
`exitCode=${process.exitCode ?? "null"}`,
234-
`exitSignal=${process.exitSignal ?? "null"}`,
235-
`durationMs=${process.durationMs}`,
236-
`stdoutBytes=${process.stdoutBytes}`,
237-
`stdoutHash=${process.stdoutHash}`,
238-
`stderrBytes=${process.stderrBytes}`,
239-
`stderrHash=${process.stderrHash}`,
240-
`useResume=${process.useResume ? "true" : "false"}`,
241-
].join(" ");
242-
}
243-
244223
/** Checks whether a Claude CLI session binding has reached its transcript file. */
245224
export async function isCliBindingFlushed(
246225
sessionId: string | undefined,
@@ -802,6 +781,12 @@ export async function runPreparedCliAgent(
802781
): Promise<EmbeddedAgentRunResult> {
803782
const { executePreparedCliRun } = await import("./cli-runner/execute.runtime.js");
804783
const { params } = context;
784+
const cliFailoverContext = {
785+
provider: params.provider,
786+
model: context.modelId,
787+
sessionId: params.sessionId,
788+
lane: params.lane,
789+
};
805790
const sessionBindingDisabled = context.preparedBackend.backend.sessionMode === "none";
806791
const preparedContextAgentMeta =
807792
isClaudeCliProvider(params.provider) && context.contextWindowInfo
@@ -1145,26 +1130,6 @@ export async function runPreparedCliAgent(
11451130
}
11461131
};
11471132

1148-
const toCliRunFailure = (error: unknown): never => {
1149-
if (isFailoverError(error)) {
1150-
throw error;
1151-
}
1152-
const message = formatErrorMessage(error);
1153-
if (isFailoverErrorMessage(message, { provider: params.provider })) {
1154-
const reason = classifyFailoverReason(message, { provider: params.provider }) ?? "unknown";
1155-
const status = resolveFailoverStatus(reason);
1156-
throw new FailoverError(message, {
1157-
reason,
1158-
provider: params.provider,
1159-
model: context.modelId,
1160-
sessionId: params.sessionId,
1161-
lane: params.lane,
1162-
status,
1163-
});
1164-
}
1165-
throw error;
1166-
};
1167-
11681133
const executeCliAttempt = async (
11691134
cliSessionIdToUse?: string,
11701135
options?: {
@@ -1223,18 +1188,28 @@ export async function runPreparedCliAgent(
12231188
!output.didSendViaMessagingTool &&
12241189
params.allowEmptyAssistantReplyAsSilent !== true
12251190
) {
1226-
const emptyOutputDiagnostics = formatCliEmptyOutputDiagnostics(output);
1227-
if (emptyOutputDiagnostics) {
1228-
cliBackendLog.warn(`cli empty response diagnostics: ${emptyOutputDiagnostics}`);
1191+
const process = output.diagnostics?.process;
1192+
if (process) {
1193+
const diagnostics = [
1194+
`backend=${process.backendId}`,
1195+
`reason=${process.processReason}`,
1196+
`exitCode=${process.exitCode ?? "null"}`,
1197+
`exitSignal=${process.exitSignal ?? "null"}`,
1198+
`durationMs=${process.durationMs}`,
1199+
`stdoutBytes=${process.stdoutBytes}`,
1200+
`stdoutHash=${process.stdoutHash}`,
1201+
`stderrBytes=${process.stderrBytes}`,
1202+
`stderrHash=${process.stderrHash}`,
1203+
`useResume=${process.useResume ? "true" : "false"}`,
1204+
].join(" ");
1205+
cliBackendLog.warn(`cli empty response diagnostics: ${diagnostics}`);
12291206
}
12301207
throw attachCliMessagingDeliveryEvidence(
1231-
new FailoverError("CLI backend returned an empty response.", {
1232-
reason: "empty_response",
1233-
provider: params.provider,
1234-
model: context.modelId,
1235-
sessionId: params.sessionId,
1236-
lane: params.lane,
1237-
}),
1208+
createCliFailoverError(
1209+
"CLI backend returned an empty response.",
1210+
"empty_response",
1211+
cliFailoverContext,
1212+
),
12381213
output,
12391214
);
12401215
}
@@ -1673,15 +1648,12 @@ export async function runPreparedCliAgent(
16731648
context.preparedBackend.backend.resumeAtArg &&
16741649
isUnsupportedCliResumeAtError(err, context.preparedBackend.backend.resumeAtArg)
16751650
) {
1676-
recoveryError = new FailoverError("CLI backend cannot resume from the stored checkpoint.", {
1677-
reason: "session_expired",
1678-
provider: params.provider,
1679-
model: context.modelId,
1680-
sessionId: params.sessionId,
1681-
lane: params.lane,
1682-
status: resolveFailoverStatus("session_expired"),
1683-
cause: err,
1684-
});
1651+
recoveryError = createCliFailoverError(
1652+
"CLI backend cannot resume from the stored checkpoint.",
1653+
"session_expired",
1654+
cliFailoverContext,
1655+
{ cause: err },
1656+
);
16851657
}
16861658
if (isFailoverError(recoveryError)) {
16871659
if (
@@ -1777,7 +1749,7 @@ export async function runPreparedCliAgent(
17771749
ctx: hookContext,
17781750
hookRunner,
17791751
});
1780-
return toCliRunFailure(retryErr);
1752+
throw retryErr;
17811753
}
17821754
}
17831755
}
@@ -1795,7 +1767,7 @@ export async function runPreparedCliAgent(
17951767
ctx: hookContext,
17961768
hookRunner,
17971769
});
1798-
return toCliRunFailure(recoveryError);
1770+
throw recoveryError;
17991771
}
18001772
};
18011773

@@ -1825,7 +1797,7 @@ export async function runPreparedCliAgent(
18251797
);
18261798
}
18271799
if (runFailed) {
1828-
throw runError;
1800+
throw coerceToFailoverError(runError, cliFailoverContext) ?? runError;
18291801
}
18301802
if (!runResult) {
18311803
throw new Error("CLI run completed without a result");

‎src/agents/cli-runner/claude-live-process.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,17 @@ describe("Claude live process", () => {
785785
code: "cli_unknown_empty_failure",
786786
},
787787
},
788+
{
789+
name: "marks quiet Claude live nonzero exits as retryable unknown failures",
790+
exitCode: 1,
791+
stderr: "",
792+
events: [],
793+
expected: {
794+
name: "FailoverError",
795+
reason: "unknown",
796+
code: "cli_unknown_empty_failure",
797+
},
798+
},
788799
{
789800
name: "preserves Claude live stderr classification on exit-zero failures",
790801
exitCode: 0,

‎src/agents/cli-runner/claude-live-turn-timeouts.ts‎

Lines changed: 32 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { BLOCKED_TOOL_CALL_ABORT_FLOOR_MS } from "../../logging/diagnostic-run-activity.js";
2-
import { type CliTimeoutContext, FailoverError, resolveFailoverStatus } from "../failover-error.js";
2+
import {
3+
createCliTimeoutError,
4+
resolveCliNoOutputTimeoutDecision,
5+
} from "./no-output-timeout-policy.js";
36

47
type ClaudeLiveTimeoutTurn = {
58
startedAtMs: number;
@@ -23,22 +26,6 @@ type ClaudeLiveTimeoutHost = {
2326
close(reason: "idle" | "restart" | "abort" | "mcp-capture-rotation", error?: unknown): void;
2427
};
2528

26-
function createClaudeTimeoutError(
27-
host: ClaudeLiveTimeoutHost,
28-
message: string,
29-
code?: string,
30-
cliTimeout?: CliTimeoutContext,
31-
): FailoverError {
32-
return new FailoverError(message, {
33-
reason: "timeout",
34-
provider: host.providerId,
35-
model: host.modelId,
36-
status: resolveFailoverStatus("timeout"),
37-
code,
38-
cliTimeout,
39-
});
40-
}
41-
4229
function armNoOutputTimer(
4330
host: ClaudeLiveTimeoutHost,
4431
turn: ClaudeLiveTimeoutTurn,
@@ -49,41 +36,30 @@ function armNoOutputTimer(
4936
}
5037
turn.noOutputTimer = setTimeout(() => {
5138
const quietSinceMs = turn.lastOutputAtMs ?? turn.startedAtMs;
52-
const hasOutstandingWork =
53-
turn.activeTools.size > 0 || host.outstandingBackgroundTaskIds.size > 0;
54-
if (hasOutstandingWork) {
55-
const remainingMs =
56-
quietSinceMs +
57-
Math.max(host.noOutputTimeoutMs, BLOCKED_TOOL_CALL_ABORT_FLOOR_MS) -
58-
Date.now();
59-
if (remainingMs > 0) {
60-
armNoOutputTimer(host, turn, remainingMs);
61-
return;
62-
}
39+
const quietDurationMs = Date.now() - quietSinceMs;
40+
const decision = resolveCliNoOutputTimeoutDecision({
41+
context: { provider: host.providerId, model: host.modelId },
42+
timeoutMs: host.noOutputTimeoutMs,
43+
quietDurationMs,
44+
cliTimeout: {
45+
mode: "no-output",
46+
timeoutSeconds: Math.round(quietDurationMs / 1000),
47+
observedActivity:
48+
turn.lastOutputAtMs !== null || turn.toolEventCount > 0 || turn.rawLines.length > 0,
49+
activeToolCount: turn.activeTools.size,
50+
backgroundTaskCount: host.outstandingBackgroundTaskIds.size,
51+
},
52+
hasOutputText: host.stdoutBuffer.pending.trim().length > 0,
53+
useResume: turn.useResume,
54+
hasReplayUnsafeActivity: turn.hasReplayUnsafeActivity,
55+
allowResumeControlOnlyRetry: true,
56+
outstandingWorkGraceMs: BLOCKED_TOOL_CALL_ABORT_FLOOR_MS,
57+
});
58+
if (decision.deferMs !== undefined) {
59+
armNoOutputTimer(host, turn, decision.deferMs);
60+
return;
6361
}
64-
const retryableResumeStall =
65-
turn.useResume &&
66-
host.stdoutBuffer.pending.trim().length === 0 &&
67-
!turn.hasReplayUnsafeActivity &&
68-
turn.toolEventCount === 0 &&
69-
turn.activeTools.size === 0 &&
70-
host.outstandingBackgroundTaskIds.size === 0;
71-
host.close(
72-
"abort",
73-
createClaudeTimeoutError(
74-
host,
75-
`CLI produced no output for ${Math.round((Date.now() - quietSinceMs) / 1000)}s and was terminated.`,
76-
turn.lastOutputAtMs === null || retryableResumeStall ? "cli_no_output_timeout" : undefined,
77-
{
78-
mode: "no-output",
79-
timeoutSeconds: Math.round((Date.now() - quietSinceMs) / 1000),
80-
observedActivity:
81-
turn.lastOutputAtMs !== null || turn.toolEventCount > 0 || turn.rawLines.length > 0,
82-
activeToolCount: turn.activeTools.size,
83-
backgroundTaskCount: host.outstandingBackgroundTaskIds.size,
84-
},
85-
),
86-
);
62+
host.close("abort", decision.error);
8763
}, delayMs);
8864
}
8965

@@ -116,20 +92,20 @@ export function armClaudeTurnTimers(
11692
): void {
11793
armNoOutputTimer(host, turn, host.noOutputTimeoutMs);
11894
turn.timeoutTimer = setTimeout(() => {
95+
const timeoutSeconds = Math.round(overallTimeoutMs / 1000);
11996
host.close(
12097
"abort",
121-
createClaudeTimeoutError(
122-
host,
123-
`CLI exceeded timeout (${Math.round(overallTimeoutMs / 1000)}s) and was terminated.`,
124-
"cli_overall_timeout",
98+
createCliTimeoutError(
99+
{ provider: host.providerId, model: host.modelId },
125100
{
126101
mode: "overall",
127-
timeoutSeconds: Math.round(overallTimeoutMs / 1000),
102+
timeoutSeconds,
128103
observedActivity:
129104
turn.observedStdout || turn.rawLines.length > 0 || turn.toolEventCount > 0,
130105
activeToolCount: turn.activeTools.size,
131106
backgroundTaskCount: host.outstandingBackgroundTaskIds.size,
132107
},
108+
"cli_overall_timeout",
133109
),
134110
);
135111
}, overallTimeoutMs);

0 commit comments

Comments
 (0)