Skip to content

Commit b9d01e7

Browse files
VACIncroboclaw-bot
andauthored
fix(agents): continue settled tool batches after a transport drop (#130721)
* fix(agents): continue settled tool batches after a transport drop A transient provider transport failure (WebSocket drop, socket reset) that lands after every tool call in the batch has settled used to kill the turn: any executed side-effecting tool marks the attempt replay-unsafe, and every recovery path is gated on replay safety, so the runner surfaced the generic "Agent couldn't generate a response" warning even though the tool results were already persisted and nothing needed to be re-run. Under code mode every tool call is exec, so any turn with a tool call died on a socket hiccup. Continue such attempts from the persisted transcript with the existing mid-turn continuation prompt, bounded to two continuations per run and only for silent errored turns with transient evidence; prompt resubmission, profile rotation, and model fallback stay closed for side-effecting attempts. * fix(agents): narrow settled transport recovery Require provider transport diagnostics before continuing a replay-unsafe settled tool batch, leaving rate-limit failures with the existing failover owner. Preserve the prior last-call usage only when a compaction retry fails before recording a replacement, without overwriting a newer successful call after later processing errors. * fix(agents): restore retry usage only on failure Keep the previous exact usage hidden while a compaction retry is active. Restore it only when the retry terminates with an error before recording a new call; a successful replacement call remains authoritative across later processing failures. * fix(agents): require settled tools for transport resume Keep the parked Code Mode exception scoped to overflow recovery. Provider transport recovery now requires every tool lifecycle item to be settled, with regression coverage for a suspended nested Code Mode run. * fix(agents): fence suspended code mode recovery Reject transcript continuation whenever the settled batch still carries producer-recorded suspended Code Mode work, even if the outer lifecycle count has reached zero. Cover that exact state in the recovery regression. * fix(agents): resume parked code mode after transport drop Use the canonical mid-turn settled evidence for transport continuation so producer-recorded parked Code Mode runs can resume from the current transcript. This lets the model call wait for the existing cell without replaying the original prompt or exec. Cover parked active-count states and preserve the terminal, abort, timeout, visible-output, diagnostic, rate-limit, retry-budget, and no-fallback gates. Worked on by: - @VACInc Co-authored-by: VACInc <[email protected]> --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: roboclaw-bot <[email protected]>
1 parent a9f163f commit b9d01e7

7 files changed

Lines changed: 320 additions & 8 deletions

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

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, expect, it, vi } from "vitest";
2+
import type { AssistantMessage } from "../../../llm/types.js";
23
import {
34
buildEmbeddedRunnerAssistant,
45
createMockUsage,
@@ -10,7 +11,183 @@ import { recoverEmbeddedRunAttempt } from "./attempt-recovery.js";
1011
import { createEmbeddedRunContextRecoveryState } from "./context-recovery-state.js";
1112
import { resolveEmbeddedRunAttemptTerminalState } from "./terminal-outcome.js";
1213

14+
type TransportDropScenario = {
15+
errorMessage?: string;
16+
content?: AssistantMessage["content"];
17+
diagnostics?: AssistantMessage["diagnostics"];
18+
activeCount?: number;
19+
codeModeSuspended?: boolean;
20+
transportDropContinuations?: number;
21+
terminal?: Parameters<typeof makeEmbeddedRunnerAttempt>[0]["terminal"];
22+
yieldDetected?: boolean;
23+
};
24+
25+
// Live shape: a code-mode exec batch settled, then the ChatGPT Responses stream
26+
// died while the model was still reasoning, so the errored turn is thinking-only.
27+
async function recoverAfterTransportDrop(scenario: TransportDropScenario = {}) {
28+
const toolCalls = ["call_1", "call_2"];
29+
const toolAssistant = buildEmbeddedRunnerAssistant({
30+
stopReason: "toolUse",
31+
content: toolCalls.map((id) => ({ type: "toolCall", id, name: "exec", arguments: {} })),
32+
});
33+
const erroredAssistant = buildEmbeddedRunnerAssistant({
34+
stopReason: "error",
35+
errorMessage: scenario.errorMessage ?? "WebSocket error",
36+
diagnostics:
37+
scenario.diagnostics ??
38+
([
39+
{
40+
type: "provider_transport_failure",
41+
error: { message: "WebSocket error" },
42+
details: { phase: "after_message_stream_start" },
43+
},
44+
] as never),
45+
content: scenario.content ?? [{ type: "thinking", thinking: "checking the results" }],
46+
usage: createMockUsage(0, 0),
47+
});
48+
const messagesSnapshot = [
49+
{ role: "user", content: "why is it unauthorized?" },
50+
toolAssistant,
51+
...toolCalls.map((id) => ({ role: "toolResult", toolCallId: id, toolName: "exec" })),
52+
erroredAssistant,
53+
] as never;
54+
const attempt = makeEmbeddedRunnerAttempt({
55+
messagesSnapshot,
56+
toolMetas: toolCalls.map((toolCallId) => ({
57+
toolCallId,
58+
toolName: "exec",
59+
replaySafe: false,
60+
...(scenario.codeModeSuspended ? { codeModeSuspended: true } : {}),
61+
})) as never,
62+
lastAssistant: erroredAssistant,
63+
currentAttemptAssistant: erroredAssistant,
64+
itemLifecycle: {
65+
startedCount: toolCalls.length,
66+
completedCount: toolCalls.length,
67+
activeCount: scenario.activeCount ?? 0,
68+
},
69+
...(scenario.terminal ? { terminal: scenario.terminal } : {}),
70+
...(scenario.yieldDetected ? { yieldDetected: true } : {}),
71+
});
72+
const terminalState = resolveEmbeddedRunAttemptTerminalState({
73+
attempt,
74+
assistant: erroredAssistant,
75+
});
76+
const continueFromCurrentTranscript = vi.fn();
77+
const contextRecoveryState = createEmbeddedRunContextRecoveryState();
78+
contextRecoveryState.transportDropContinuations = scenario.transportDropContinuations ?? 0;
79+
const failoverRetryController = {
80+
resolveAuthProfileFailureReason: vi.fn(),
81+
advanceAuthProfile: vi.fn(),
82+
advanceRateLimitAuthProfile: vi.fn(),
83+
maybeMarkAuthProfileFailure: vi.fn(),
84+
maybeBackoffBeforeOverloadFailover: vi.fn(),
85+
};
86+
const recovery = await recoverEmbeddedRunAttempt({
87+
runInput: {
88+
runParams: {
89+
config: {},
90+
agentId: "main",
91+
sessionId: "session:transport-drop",
92+
runId: "run:transport-drop",
93+
},
94+
resolvedSessionKey: "agent:main:transport-drop",
95+
startedAtMs: Date.now(),
96+
laneController: { throwIfAborted: vi.fn() },
97+
},
98+
preparedRuntime: {
99+
provider: "openai",
100+
modelId: "gpt-5.6-luna",
101+
model: { id: "gpt-5.6-luna" },
102+
genericCompactionRecoveryAllowed: false,
103+
snapshot: () => ({
104+
thinkLevel: "off",
105+
agentHarness: { id: "openclaw" },
106+
outerContextTokenMeta: {},
107+
pluginHarnessOwnsTransport: false,
108+
}),
109+
},
110+
normalizedAttempt: {
111+
attempt,
112+
sessionIdUsed: attempt.sessionIdUsed,
113+
attemptAssistant: erroredAssistant,
114+
currentAttemptAssistant: erroredAssistant,
115+
currentAttemptCompletedAssistant: undefined,
116+
terminalState,
117+
setTerminalLifecycleMeta: vi.fn(),
118+
attemptCompactionCount: 0,
119+
activeErrorContext: { provider: "openai", model: "gpt-5.6-luna" },
120+
resolveReplayInvalidForAttempt: () => true,
121+
canRestartForLiveSwitch: false,
122+
},
123+
runtimePlan: { auth: {} },
124+
sessionPromptState: { sessionFile: "/tmp/session.jsonl", continueFromCurrentTranscript },
125+
failoverRetryController,
126+
compactionRuntime: {},
127+
contextRecoveryState,
128+
usageAccumulator: createUsageAccumulator(),
129+
lastRunPromptUsage: undefined,
130+
runtimeAuthRetry: false,
131+
codexAppServerRecoveryRetryAvailable: false,
132+
codexAppServerRecoveryRetries: 0,
133+
lastRetryFailoverReason: null,
134+
traceAttempts: [],
135+
sessionAgentId: "main",
136+
} as never);
137+
return { recovery, continueFromCurrentTranscript, contextRecoveryState, failoverRetryController };
138+
}
139+
13140
describe("recoverEmbeddedRunAttempt", () => {
141+
it("continues from the transcript after a transient transport drop on a settled exec batch", async () => {
142+
const {
143+
recovery,
144+
continueFromCurrentTranscript,
145+
contextRecoveryState,
146+
failoverRetryController,
147+
} = await recoverAfterTransportDrop();
148+
149+
expect(recovery).toMatchObject({ action: "retry" });
150+
expect(contextRecoveryState.transportDropContinuations).toBe(1);
151+
expect(continueFromCurrentTranscript).toHaveBeenCalledTimes(1);
152+
expect(failoverRetryController.advanceAuthProfile).not.toHaveBeenCalled();
153+
expect(failoverRetryController.maybeMarkAuthProfileFailure).not.toHaveBeenCalled();
154+
});
155+
156+
it.each([0, 1])(
157+
"continues a parked Code Mode run from its persisted waiting result with activeCount=%i",
158+
async (activeCount) => {
159+
const { recovery, continueFromCurrentTranscript } = await recoverAfterTransportDrop({
160+
codeModeSuspended: true,
161+
activeCount,
162+
});
163+
164+
expect(recovery).toMatchObject({ action: "retry" });
165+
expect(continueFromCurrentTranscript).toHaveBeenCalledTimes(1);
166+
},
167+
);
168+
169+
it.each<[string, TransportDropScenario]>([
170+
["the exec batch is still running", { activeCount: 1 }],
171+
["the run was externally aborted", { terminal: { kind: "aborted", source: "external" } }],
172+
["the run timed out", { terminal: { kind: "timeout", phase: "prompt", source: "runtime" } }],
173+
["the attempt already has terminal state", { yieldDetected: true }],
174+
["the assistant error is not transient", { errorMessage: "invalid request: bad schema" }],
175+
[
176+
"the failure is retryable but not a transport drop",
177+
{ errorMessage: "429 rate limit exceeded; retry after 2 seconds", diagnostics: [] },
178+
],
179+
[
180+
"the errored turn already carried visible text",
181+
{ content: [{ type: "text", text: "Partial" }] },
182+
],
183+
["the continuation budget is spent", { transportDropContinuations: 2 }],
184+
])("keeps the replay gate closed when %s", async (_label, scenario) => {
185+
const { recovery, continueFromCurrentTranscript } = await recoverAfterTransportDrop(scenario);
186+
187+
expect(recovery).toEqual({ action: "proceed", shouldSurfaceCodexCompletionTimeout: false });
188+
expect(continueFromCurrentTranscript).not.toHaveBeenCalled();
189+
});
190+
14191
it("surfaces before_agent_run blocks with current carried usage", async () => {
15192
const historicalAssistant = buildEmbeddedRunnerAssistant({
16193
usage: createMockUsage(128_814, 3_000),

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

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
11
import { formatErrorMessage, toErrorObject } from "../../../infra/errors.js";
2+
import type { AssistantMessage } from "../../../llm/types.js";
3+
import { isRetryableAssistantError } from "../../../llm/utils/retry.js";
24
import { projectAgentRunAttemptTerminal } from "../../agent-run-terminal-outcome.js";
35
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "../../defaults.js";
46
import type { FailoverReason } from "../../embedded-agent-helpers.js";
57
import { LiveSessionModelSwitchError } from "../../live-model-switch-error.js";
68
import { shouldSwitchToLiveModel, clearLiveModelSwitchPending } from "../../live-model-switch.js";
9+
import { hasOnlyAssistantReasoningContent } from "../../replay-turn-classification.js";
710
import type { normalizeUsage } from "../../usage.js";
811
import { log } from "../logger.js";
912
import { getEmbeddedSessionPromptState } from "../session-prompt-state.js";
1013
import type { EmbeddedAgentRunResult, TraceAttempt } from "../types.js";
1114
import type { createUsageAccumulator } from "../usage-accumulator.js";
1215
import type { prepareAndDispatchEmbeddedRunAttempt } from "./attempt-dispatch-preparation.js";
1316
import type { normalizeEmbeddedRunAttempt } from "./attempt-normalization.js";
14-
import { hasAsyncActivity, isCurrentAttemptReplaySafe } from "./attempt-terminal-evidence.js";
17+
import {
18+
hasAsyncActivity,
19+
hasAttemptTerminalState,
20+
isCurrentAttemptReplaySafe,
21+
} from "./attempt-terminal-evidence.js";
1522
import { buildEmbeddedRunBlockedResult } from "./blocked-run-result.js";
1623
import { resolveCodexAppServerRecoveryRetry } from "./codex-app-server-recovery.js";
1724
import { resolveCompactionLiveModelSelection } from "./compaction-live-model-selection.js";
@@ -28,6 +35,22 @@ import type { createEmbeddedRunSessionPromptState } from "./session-prompt-state
2835
import { isEmbeddedRunTerminalInterrupted } from "./terminal-outcome.js";
2936
import { recoverEmbeddedRunTimeout } from "./timeout-context-recovery.js";
3037

38+
const MAX_TRANSPORT_DROP_CONTINUATIONS = 2;
39+
40+
/** Errored assistant turn with transient transport evidence and no visible output. */
41+
function isSilentTransportDropAssistant(assistant: AssistantMessage | undefined): boolean {
42+
if (
43+
!assistant ||
44+
assistant.stopReason !== "error" ||
45+
!isRetryableAssistantError(assistant) ||
46+
!assistant.diagnostics?.some((diagnostic) => diagnostic.type === "provider_transport_failure")
47+
) {
48+
return false;
49+
}
50+
const content = Array.isArray(assistant.content) ? assistant.content : [];
51+
return content.length === 0 || hasOnlyAssistantReasoningContent(assistant);
52+
}
53+
3154
type PreparedRuntime = Awaited<ReturnType<typeof prepareEmbeddedRunRuntime>>;
3255
type NormalizedAttempt = Extract<
3356
Awaited<ReturnType<typeof normalizeEmbeddedRunAttempt>>,
@@ -126,6 +149,26 @@ export async function recoverEmbeddedRunAttempt(input: {
126149
attempt.preflightRecovery?.source === "mid-turn" &&
127150
midTurnBatchSettled &&
128151
!hasAsyncActivity(attempt.toolMetas);
152+
// A transient transport failure that lands after the whole tool batch settled
153+
// is a resume, not a replay: the continuation prompt re-enters after the
154+
// persisted tool results and nothing from the failed attempt is resubmitted.
155+
// Only a silent errored assistant qualifies; partial visible text would be
156+
// duplicated or replaced. Everything #122516 closed for side-effecting
157+
// attempts (prompt resubmission, profile rotation, model fallback) stays
158+
// closed below this branch.
159+
const settledTransportDropAssistant =
160+
!currentAttemptReplaySafe &&
161+
!promptError &&
162+
!aborted &&
163+
!timedOut &&
164+
!terminalInterrupted &&
165+
!hasAttemptTerminalState(attempt) &&
166+
midTurnBatchSettled &&
167+
// A parked Code Mode result is persisted same-session state. Continuing is
168+
// how the model reaches wait; it does not resubmit the prompt or exec call.
169+
isSilentTransportDropAssistant(currentAttemptAssistant)
170+
? currentAttemptAssistant
171+
: undefined;
129172
const { signalOwnedInterruption } = terminalState;
130173
const assistantOverflowCandidate =
131174
currentAttemptCompletedAssistant !== undefined
@@ -184,7 +227,11 @@ export async function recoverEmbeddedRunAttempt(input: {
184227
}),
185228
};
186229
}
187-
if (!currentAttemptReplaySafe && !canContinueSettledMidTurnOverflow) {
230+
if (
231+
!currentAttemptReplaySafe &&
232+
!canContinueSettledMidTurnOverflow &&
233+
!settledTransportDropAssistant
234+
) {
188235
return replayUnsafeOutcome;
189236
}
190237

@@ -313,8 +360,26 @@ export async function recoverEmbeddedRunAttempt(input: {
313360
}),
314361
};
315362
}
316-
// Settled-tool continuation authorizes only current-transcript overflow recovery.
317-
// Every path below can replay or replace the original attempt and remains fail-closed.
363+
const recoveryState = input.contextRecoveryState;
364+
if (
365+
settledTransportDropAssistant &&
366+
recoveryState.transportDropContinuations < MAX_TRANSPORT_DROP_CONTINUATIONS
367+
) {
368+
runInput.laneController.throwIfAborted();
369+
recoveryState.transportDropContinuations += 1;
370+
sessionPromptState.continueFromCurrentTranscript();
371+
log.warn(
372+
`provider transport dropped after a settled tool batch; continuing from the transcript ` +
373+
`attempt=${recoveryState.transportDropContinuations}/${MAX_TRANSPORT_DROP_CONTINUATIONS} ` +
374+
`provider=${preparedRuntime.provider} model=${preparedRuntime.modelId} ` +
375+
`error=${settledTransportDropAssistant.errorMessage?.trim() ?? "unknown"} ` +
376+
`runId=${params.runId} sessionId=${params.sessionId}`,
377+
);
378+
return retry();
379+
}
380+
// Settled-tool continuation authorizes only current-transcript overflow and
381+
// transport-drop recovery. Every path below can replay or replace the original
382+
// attempt and remains fail-closed.
318383
if (!currentAttemptReplaySafe) {
319384
return replayUnsafeOutcome;
320385
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export function createEmbeddedRunContextRecoveryState() {
88
overflowCompactionAttempts: 0,
99
timeoutCompactionAttempts: 0,
1010
toolResultTruncationAttempted: false,
11+
transportDropContinuations: 0,
1112
};
1213
}
1314

‎src/agents/embedded-agent-subscribe.handlers.types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ export type EmbeddedAgentSubscribeState = {
178178
lastReasoningSent?: string;
179179
pendingAssistantUsage?: NormalizedUsage;
180180
assistantUsageCommitted: boolean;
181+
retryUsage?: NormalizedUsage;
181182

182183
compactionInFlight: boolean;
183184
lastCompactionTokensAfter?: number;

‎src/agents/embedded-agent-subscribe.run-state.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ export function createEmbeddedAgentSubscribeState(
6363
lastReasoningSent: undefined,
6464
pendingAssistantUsage: undefined,
6565
assistantUsageCommitted: false,
66+
retryUsage: undefined,
6667
compactionInFlight: false,
6768
lastCompactionTokensAfter: undefined,
6869
pendingCompactionRetry: 0,

0 commit comments

Comments
 (0)