Skip to content

Commit e77967b

Browse files
committed
fix(agents): run embedded gateway fallback on a fresh session after abnormal close
1 parent 40acbb0 commit e77967b

3 files changed

Lines changed: 70 additions & 52 deletions

File tree

‎src/agents/command/types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export type ImageContent = {
3232
export type AgentCommandResultMetaOverrides = {
3333
transport?: "embedded";
3434
fallbackFrom?: "gateway";
35-
fallbackReason?: "gateway_timeout";
35+
fallbackReason?: "gateway_timeout" | "gateway_closed";
3636
fallbackSessionId?: string;
3737
fallbackSessionKey?: string;
3838
};

‎src/commands/agent-via-gateway.test.ts‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -183,10 +183,12 @@ function createGatewayTimeoutError() {
183183
}
184184

185185
function createGatewayClosedError() {
186-
const err = new Error("gateway closed before response");
186+
const err = new Error("gateway closed (1006 abnormal closure): no close reason");
187187
err.name = "GatewayTransportError";
188188
return Object.assign(err, {
189189
kind: "closed",
190+
code: 1006,
191+
reason: "no close reason",
190192
connectionDetails: {
191193
url: "ws://127.0.0.1:18789",
192194
urlSource: "local loopback",
@@ -1606,9 +1608,12 @@ describe("agentCliCommand", () => {
16061608
);
16071609
expect(resultMetaOverrides.transport).toBe("embedded");
16081610
expect(resultMetaOverrides.fallbackFrom).toBe("gateway");
1611+
expect(resultMetaOverrides.fallbackReason).toBe("gateway_closed");
16091612
expect(
16101613
mockMessages(runtime.error).some((message) =>
1611-
message.includes("EMBEDDED FALLBACK: Gateway agent failed"),
1614+
message.includes(
1615+
"Gateway agent connection closed; running embedded agent with fresh session",
1616+
),
16121617
),
16131618
).toBe(true);
16141619
expect(runtime.log).toHaveBeenCalledWith("local");
@@ -1654,9 +1659,18 @@ describe("agentCliCommand", () => {
16541659
}
16551660
});
16561661

1657-
it("preserves explicit session keys for embedded fallback when the gateway closes", async () => {
1662+
it("uses a fresh embedded session when an accepted gateway turn closes abnormally", async () => {
16581663
await withTempStore(async () => {
1659-
callGateway.mockRejectedValue(createGatewayClosedError());
1664+
callGateway.mockImplementationOnce(async (requestValue: unknown) => {
1665+
const request = requireRecord(requestValue, "gateway request");
1666+
const onAccepted = request.onAccepted as ((payload: unknown) => void) | undefined;
1667+
onAccepted?.({
1668+
status: "accepted",
1669+
runId: "accepted-run",
1670+
sessionKey: "agent:main:incident-42",
1671+
});
1672+
throw createGatewayClosedError();
1673+
});
16601674
mockLocalAgentReply();
16611675

16621676
await agentCliCommand({ message: "hi", sessionKey: "agent:main:incident-42" }, runtime);
@@ -1667,29 +1681,39 @@ describe("agentCliCommand", () => {
16671681
requireFirstCallArg(agentCommand, "embedded agent"),
16681682
"embedded agent options",
16691683
);
1670-
expect(fallbackOpts.sessionKey).toBe("agent:main:incident-42");
1684+
const fallbackSessionId = String(fallbackOpts.sessionId);
1685+
const fallbackSessionKey = String(fallbackOpts.sessionKey);
1686+
expect(fallbackSessionId).toMatch(/^gateway-fallback-/);
1687+
expect(fallbackSessionKey).toBe(`agent:main:explicit:${fallbackSessionId}`);
1688+
expect(fallbackSessionKey).not.toBe("agent:main:incident-42");
1689+
expect(fallbackOpts.runId).toBe(fallbackSessionId);
16711690
expect(fallbackOpts.resultMetaOverrides).toMatchObject({
16721691
transport: "embedded",
16731692
fallbackFrom: "gateway",
1693+
fallbackReason: "gateway_closed",
1694+
fallbackSessionId,
1695+
fallbackSessionKey,
16741696
});
16751697
});
16761698
});
16771699

1678-
it("propagates harness-owned session rejection from embedded gateway fallback", async () => {
1700+
it("does not pass a harness-owned session key into closed gateway fallback", async () => {
16791701
await withTempStore(async () => {
16801702
const sessionKey = "agent:main:harness:codex:supervision:missing-fallback";
16811703
callGateway.mockRejectedValue(createGatewayClosedError());
1682-
agentCommand.mockRejectedValueOnce(new Error(AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE));
1704+
mockLocalAgentReply();
16831705

1684-
await expect(agentCliCommand({ message: "hi", sessionKey }, runtime)).rejects.toThrow(
1685-
AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE,
1686-
);
1706+
await agentCliCommand({ message: "hi", sessionKey }, runtime);
16871707

16881708
expect(callGateway).toHaveBeenCalledOnce();
16891709
expect(agentCommand).toHaveBeenCalledOnce();
1690-
expect(
1691-
requireRecord(requireFirstCallArg(agentCommand, "embedded agent"), "options"),
1692-
).toMatchObject({ sessionKey });
1710+
const fallbackOpts = requireRecord(
1711+
requireFirstCallArg(agentCommand, "embedded agent"),
1712+
"options",
1713+
);
1714+
const fallbackSessionId = String(fallbackOpts.sessionId);
1715+
expect(fallbackOpts.sessionKey).toBe(`agent:main:explicit:${fallbackSessionId}`);
1716+
expect(fallbackOpts.sessionKey).not.toBe(sessionKey);
16931717
});
16941718
});
16951719

@@ -1887,7 +1911,7 @@ describe("agentCliCommand", () => {
18871911
expect(resultMetaOverrides.fallbackFrom).toBe("gateway");
18881912
expect(
18891913
mockMessages(jsonRuntime.error).some((message) =>
1890-
message.includes("EMBEDDED FALLBACK: Gateway agent failed"),
1914+
message.includes("EMBEDDED FALLBACK: Gateway agent connection closed"),
18911915
),
18921916
).toBe(true);
18931917
expect(loggingState.forceConsoleToStderr).toBe(true);

‎src/commands/agent-via-gateway.ts‎

Lines changed: 31 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ const EMBEDDED_FALLBACK_META = {
6464
transport: "embedded",
6565
fallbackFrom: "gateway",
6666
} as const;
67-
const GATEWAY_TIMEOUT_FALLBACK_SESSION_PREFIX = "gateway-fallback-";
67+
const GATEWAY_FALLBACK_SESSION_PREFIX = "gateway-fallback-";
6868
const GATEWAY_TRANSIENT_CONNECT_RETRY_DELAYS_MS = [1_000, 2_000, 5_000, 10_000, 15_000] as const;
6969

7070
type AgentCliOpts = {
@@ -308,8 +308,15 @@ function shouldRetryGatewayDispatchWithShellEnvFallback(err: unknown): boolean {
308308
);
309309
}
310310

311-
function isGatewayAgentEmbeddedFallbackError(err: unknown): boolean {
312-
return isGatewayTransportError(err);
311+
function resolveGatewayAgentEmbeddedFallbackReason(
312+
err: unknown,
313+
): "gateway_timeout" | "gateway_closed" | undefined {
314+
if (isGatewayAgentTimeoutError(err)) {
315+
return "gateway_timeout";
316+
}
317+
// GatewayTransportErrorKind is exactly "closed" | "timeout", so this branch
318+
// pair covers every transport error; non-transport errors never fell back.
319+
return isGatewayTransportError(err) && err.kind === "closed" ? "gateway_closed" : undefined;
313320
}
314321

315322
function isTransientGatewayAgentConnectClose(err: unknown): boolean {
@@ -612,22 +619,22 @@ function returnAfterSignalExit<T>(
612619
return exitForReceivedSignal(signal, runtime) ? undefined : value;
613620
}
614621

615-
function createGatewayTimeoutFallbackSessionId(): string {
616-
return `${GATEWAY_TIMEOUT_FALLBACK_SESSION_PREFIX}${randomUUID()}`;
622+
function createGatewayFallbackSessionId(): string {
623+
return `${GATEWAY_FALLBACK_SESSION_PREFIX}${randomUUID()}`;
617624
}
618625

619-
function createGatewayTimeoutFallbackSession(agentId?: string): {
626+
function createGatewayFallbackSession(agentId?: string): {
620627
sessionId: string;
621628
sessionKey: string;
622629
} {
623-
const sessionId = createGatewayTimeoutFallbackSessionId();
630+
const sessionId = createGatewayFallbackSessionId();
624631
return {
625632
sessionId,
626633
sessionKey: `agent:${normalizeAgentId(agentId)}:explicit:${sessionId.trim()}`,
627634
};
628635
}
629636

630-
async function resolveAgentIdForGatewayTimeoutFallback(
637+
async function resolveAgentIdForGatewayFallback(
631638
opts: AgentDispatchOpts,
632639
): Promise<string | undefined> {
633640
const explicitSessionKey = opts.sessionKey?.trim();
@@ -963,44 +970,31 @@ export async function agentCliCommand(
963970
}
964971
throw err;
965972
}
966-
if (isGatewayAgentTimeoutError(err)) {
967-
const fallbackAgentId = await resolveAgentIdForGatewayTimeoutFallback(dispatchOpts);
968-
const fallbackSession = createGatewayTimeoutFallbackSession(fallbackAgentId);
969-
runtime.error?.(
970-
`EMBEDDED FALLBACK: Gateway agent timed out; running embedded agent with fresh session ${fallbackSession.sessionId}: ${String(err)}`,
971-
);
972-
const agentCommand = await loadEmbeddedAgentCommand();
973-
const result = await agentCommand(
974-
{
975-
...localOpts,
976-
sessionId: fallbackSession.sessionId,
977-
sessionKey: fallbackSession.sessionKey,
978-
runId: fallbackSession.sessionId,
979-
resultMetaOverrides: {
980-
...EMBEDDED_FALLBACK_META,
981-
fallbackReason: "gateway_timeout",
982-
fallbackSessionId: fallbackSession.sessionId,
983-
fallbackSessionKey: fallbackSession.sessionKey,
984-
},
985-
},
986-
runtime,
987-
deps,
988-
);
989-
return returnAfterSignalExit(result, signalBridge.getReceivedSignal(), runtime);
990-
}
991-
992-
if (!isGatewayAgentEmbeddedFallbackError(err)) {
973+
const fallbackReason = resolveGatewayAgentEmbeddedFallbackReason(err);
974+
if (!fallbackReason) {
993975
throw err;
994976
}
995977

978+
const fallbackAgentId = await resolveAgentIdForGatewayFallback(dispatchOpts);
979+
const fallbackSession = createGatewayFallbackSession(fallbackAgentId);
980+
// Transport loss is ambiguous: the Gateway may still own or recover the original turn.
981+
// Keep embedded work on a separate session so both processes cannot write one transcript.
996982
runtime.error?.(
997-
`EMBEDDED FALLBACK: Gateway agent failed; running embedded agent: ${String(err)}`,
983+
`EMBEDDED FALLBACK: Gateway agent ${fallbackReason === "gateway_timeout" ? "timed out" : "connection closed"}; running embedded agent with fresh session ${fallbackSession.sessionId}: ${String(err)}`,
998984
);
999985
const agentCommand = await loadEmbeddedAgentCommand();
1000986
const result = await agentCommand(
1001987
{
1002988
...localOpts,
1003-
resultMetaOverrides: EMBEDDED_FALLBACK_META,
989+
sessionId: fallbackSession.sessionId,
990+
sessionKey: fallbackSession.sessionKey,
991+
runId: fallbackSession.sessionId,
992+
resultMetaOverrides: {
993+
...EMBEDDED_FALLBACK_META,
994+
fallbackReason,
995+
fallbackSessionId: fallbackSession.sessionId,
996+
fallbackSessionKey: fallbackSession.sessionKey,
997+
},
1004998
},
1005999
runtime,
10061000
deps,

0 commit comments

Comments
 (0)