diff --git a/packages/provider-bridge-acp/src/bridge/bridge.test.ts b/packages/provider-bridge-acp/src/bridge/bridge.test.ts index a74bea63840..ad39ed80e48 100644 --- a/packages/provider-bridge-acp/src/bridge/bridge.test.ts +++ b/packages/provider-bridge-acp/src/bridge/bridge.test.ts @@ -5658,6 +5658,152 @@ describe("acp bridge: busy agents, restored sessions and stop reasons", () => { } }); + const lostSessionErrors = [ + { + agent: "an agent using the ACP resource-not-found code", + error: { code: -32002, message: "Resource not found" }, + }, + { + agent: "OpenCode", + error: { + code: -32602, + message: "Invalid params: session not found: ses_lost", + data: { sessionId: "ses_lost" }, + }, + }, + { + agent: "Copilot", + error: { code: -32602, message: "Session ses_lost not found" }, + }, + { + agent: "Cursor", + error: { + code: -32603, + message: "Internal error", + data: { details: "Session ses_lost not found" }, + }, + }, + { + agent: "Copilot with a stuck session lock", + error: { + code: -32603, + message: "Internal error", + data: { + details: + "session lock unavailable during is_session_generation_current: acquisition timed out", + }, + }, + }, + ]; + + function lostSessionAgentEnv(error: object): { + envVars: Record; + launchCount: () => number; + requestLog: string; + } { + const launchLog = join(workspaceDir, "launches.log"); + const requestLog = join(workspaceDir, "requests.log"); + return { + envVars: { + FAKE_ACP_LOAD_SESSION: "1", + FAKE_ACP_LOST_SESSION_ERROR: JSON.stringify(error), + FAKE_ACP_LOST_SESSION_FILE: join(workspaceDir, "lost-session"), + FAKE_ACP_LAUNCH_LOG: launchLog, + FAKE_ACP_REQUEST_LOG: requestLog, + }, + launchCount: () => + readFileSync(launchLog, "utf8").split("\n").filter(Boolean).length, + requestLog, + }; + } + + async function turnStatus( + providerThreadId: string, + input: unknown[], + ): Promise { + const completedBefore = threadEventsOfType("turn/completed").length; + const turnId = sendTurnRequest("turn/start", providerThreadId, { input }); + expect((await waitForResponse(turnId)).error).toBeUndefined(); + const completed = await waitFor( + () => threadEventsOfType("turn/completed")[completedBefore], + "next turn/completed thread event", + ); + return completed["status"]; + } + + it.each(lostSessionErrors)( + "rebuilds the session before the next turn after $agent reports it lost", + async ({ error }) => { + const agent = lostSessionAgentEnv(error); + const { providerThreadId } = await startThread({ + envVars: agent.envVars, + }); + const text = (value: string) => [ + { type: "text", text: value, mentions: [] }, + ]; + + expect(await turnStatus(providerThreadId, text("first"))).toBe("failed"); + expect(await turnStatus(providerThreadId, text("second"))).toBe( + "completed", + ); + + expect(agentMessageTexts()).toEqual(["echo:second"]); + expect(agent.launchCount()).toBe(2); + expect( + loggedAcpRequests(agent.requestLog).filter( + (request) => request.method === "session/load", + ), + ).toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ sessionId: providerThreadId }), + }), + ]); + expect(notifications("session/replaced")).toHaveLength(1); + expect(notifications("session/replaced")[0]?.params).toMatchObject({ + providerThreadId, + reason: + "The ACP agent lost its session; the session was rebuilt before continuing.", + contextLost: false, + }); + }, + ); + + it("rebuilds the session before the next turn after a compaction finds it lost", async () => { + const agent = lostSessionAgentEnv(lostSessionErrors[1]!.error); + const { providerThreadId } = await startThread({ envVars: agent.envVars }); + + expect(await turnStatus(providerThreadId, compactCommandInput())).toBe( + "failed", + ); + expect( + await turnStatus(providerThreadId, [ + { type: "text", text: "after compaction", mentions: [] }, + ]), + ).toBe("completed"); + + expect(agentMessageTexts()).toEqual(["echo:after compaction"]); + expect(agent.launchCount()).toBe(2); + expect(notifications("session/replaced")).toHaveLength(1); + }); + + it("keeps the session when a prompt fails for another reason", async () => { + const agent = lostSessionAgentEnv({ + code: -32603, + message: "Internal error", + data: { details: "upstream model overloaded" }, + }); + const { providerThreadId } = await startThread({ envVars: agent.envVars }); + const text = (value: string) => [ + { type: "text", text: value, mentions: [] }, + ]; + + expect(await turnStatus(providerThreadId, text("first"))).toBe("failed"); + expect(await turnStatus(providerThreadId, text("second"))).toBe("failed"); + + expect(agent.launchCount()).toBe(1); + expect(notifications("session/replaced")).toEqual([]); + }); + it("restores a session with session/resume when the agent offers it, without replaying history", async () => { const requestLog = join(workspaceDir, "requests.log"); const envVars = { diff --git a/packages/provider-bridge-acp/src/bridge/bridge.ts b/packages/provider-bridge-acp/src/bridge/bridge.ts index 2ea3424e413..093ec405d31 100644 --- a/packages/provider-bridge-acp/src/bridge/bridge.ts +++ b/packages/provider-bridge-acp/src/bridge/bridge.ts @@ -144,6 +144,7 @@ import { type AcpAgentRequestResponder, } from "./agent-connection.js"; import type { AcpAgentCapabilities } from "../client/capabilities.js"; +import { ACP_RESOURCE_NOT_FOUND_CODE } from "../client/acp-client.js"; import { createAcpSessionModel, type AcpSessionModel, @@ -204,6 +205,8 @@ interface AcpNativeConfigState { models: AcpSessionModels | undefined; } +type AcpSessionRebuildCause = "cancel-error" | "lost-session"; + interface AcpThreadSession { bbThreadId: string; construction: AcpSessionParams; @@ -232,7 +235,7 @@ interface AcpThreadSession { promptRequestPending: boolean; cancelRequested: boolean; turnStartedAtMs: number | undefined; - restartAfterCancelError: boolean; + rebuildBeforeNextPrompt: AcpSessionRebuildCause | null; loading: boolean; loadingSessionId: string | undefined; pendingLoadUsageUpdate: AcpUsageUpdate | undefined; @@ -296,6 +299,8 @@ const SESSION_BUSY_QUIET_MS = 2_000; const SESSION_BUSY_MAX_WAITS = 300; const SESSION_BUSY_MAX_RETRIES = 3; const ACP_SESSION_BUSY_ERROR_CODE = -32003; +const ACP_LOST_SESSION_MESSAGE = + /\bsession\b(?:\s+\S+)?\s+not found|\bsession lock unavailable\b/i; const ACP_SESSION_SETUP_TIMEOUT_MS = 300_000; const ACP_SESSION_CONFIG_TIMEOUT_MS = 60_000; const ACP_AUTHENTICATE_TIMEOUT_MS = 120_000; @@ -2445,7 +2450,7 @@ async function startAgentSession( promptRequestPending: false, cancelRequested: false, turnStartedAtMs: undefined, - restartAfterCancelError: false, + rebuildBeforeNextPrompt: null, loading: false, loadingSessionId: undefined, pendingLoadUsageUpdate: undefined, @@ -3135,6 +3140,23 @@ function finishTurn( }); } +function isLostSessionError(error: unknown): boolean { + return ( + error instanceof AcpAgentResponseError && + (error.code === ACP_RESOURCE_NOT_FOUND_CODE || + ACP_LOST_SESSION_MESSAGE.test(error.message)) + ); +} + +function scheduleRebuildIfSessionLost( + session: AcpThreadSession, + error: unknown, +): void { + if (isLostSessionError(error)) { + session.rebuildBeforeNextPrompt ??= "lost-session"; + } +} + function isSessionBusyError(error: unknown): boolean { return ( error instanceof AcpAgentResponseError && @@ -3261,7 +3283,10 @@ function runTurn( } } } catch (error) { - session.restartAfterCancelError = session.cancelRequested; + session.rebuildBeforeNextPrompt = session.cancelRequested + ? "cancel-error" + : null; + scheduleRebuildIfSessionLost(session, error); session.promptRequestPending = false; dropTurnInput(pending, "ACP turn failed before the prompt was sent"); dropQueuedTurnInputs( @@ -3384,7 +3409,7 @@ function reconcileExecutionSettings( launchModelChanged; const restart = session.connection.exited || - session.restartAfterCancelError || + session.rebuildBeforeNextPrompt !== null || launchArgsChanged || !isDeepStrictEqual(envVars ?? {}, session.construction.envVars ?? {}); cancelPendingPermissions(session); @@ -3442,9 +3467,11 @@ async function rebuildAgentSession( const previousProviderThreadId = session.providerThreadId; const reason = session.connection.exited ? "The ACP agent exited unexpectedly; its session was rebuilt before continuing." - : session.restartAfterCancelError + : session.rebuildBeforeNextPrompt === "cancel-error" ? "The ACP agent failed during cancellation; its session was rebuilt before continuing." - : "Execution settings changed; the ACP session was rebuilt to apply them."; + : session.rebuildBeforeNextPrompt === "lost-session" + ? "The ACP agent lost its session; the session was rebuilt before continuing." + : "Execution settings changed; the ACP session was rebuilt to apply them."; const queuedInputs = session.queuedInputs.splice(0); const continuingTurn = session.activePromptKind === "turn"; if (continuingTurn) { @@ -3563,6 +3590,7 @@ function startCompaction( ); }) .catch((error: unknown) => { + scheduleRebuildIfSessionLost(session, error); finish({ status: "failed", error: error instanceof Error ? error.message : String(error), @@ -4126,10 +4154,15 @@ async function handleRequest( const reconciled = reconcileExecutionSettings(session, params.options); session = reconciled instanceof Promise ? await reconciled : reconciled; if (params.options.sessionOptions !== undefined) { - await applySessionOptionSelections( - session, - params.options.sessionOptions, - ); + try { + await applySessionOptionSelections( + session, + params.options.sessionOptions, + ); + } catch (error) { + scheduleRebuildIfSessionLost(session, error); + throw error; + } } const pending: AcpPendingTurnInput = { clientRequestId: params.clientRequestId, diff --git a/packages/provider-bridge-acp/src/bridge/fake-acp-agent.mjs b/packages/provider-bridge-acp/src/bridge/fake-acp-agent.mjs index 412b4d20759..873e51fe225 100755 --- a/packages/provider-bridge-acp/src/bridge/fake-acp-agent.mjs +++ b/packages/provider-bridge-acp/src/bridge/fake-acp-agent.mjs @@ -79,6 +79,13 @@ * count model-discovery spawns in cache/TTL tests) * - FAKE_ACP_PROMPT_LOG → append one JSON-encoded prompt text per request * - FAKE_ACP_PROMPT_ERROR=1 → reject every session/prompt request + * - FAKE_ACP_LOST_SESSION_ERROR + * → JSON-RPC error object; the first launched + * process rejects every session/prompt with it, + * as an agent that lost its session does + * - FAKE_ACP_LOST_SESSION_FILE + * → marker that limits the lost session to the + * first launch * - FAKE_ACP_GROK_CONTEXT=1 → advertise Grok model _meta.totalContextTokens * and prompt-result _meta.usage * - FAKE_ACP_COMPACT_STOP_REASON @@ -294,6 +301,16 @@ if (process.env.FAKE_ACP_LAUNCH_LOG) { appendFileSync(process.env.FAKE_ACP_LAUNCH_LOG, `launch ${process.pid}\n`); } +let lostSessionError = null; +if ( + process.env.FAKE_ACP_LOST_SESSION_ERROR && + process.env.FAKE_ACP_LOST_SESSION_FILE && + !existsSync(process.env.FAKE_ACP_LOST_SESSION_FILE) +) { + writeFileSync(process.env.FAKE_ACP_LOST_SESSION_FILE, ""); + lostSessionError = JSON.parse(process.env.FAKE_ACP_LOST_SESSION_ERROR); +} + function send(message) { process.stdout.write(JSON.stringify(message) + "\n"); } @@ -614,6 +631,12 @@ async function handlePrompt(message) { return; } + if (lostSessionError !== null) { + activePromptId = null; + send({ jsonrpc: "2.0", id: message.id, error: lostSessionError }); + return; + } + if (process.env.FAKE_ACP_PROMPT_ERROR === "1") { activePromptId = null; send({ diff --git a/packages/provider-bridge-acp/src/delta-translation.test.ts b/packages/provider-bridge-acp/src/delta-translation.test.ts index b28c905bbc3..a36cca028fe 100644 --- a/packages/provider-bridge-acp/src/delta-translation.test.ts +++ b/packages/provider-bridge-acp/src/delta-translation.test.ts @@ -2114,6 +2114,50 @@ describe("acp delta translation (raw payloads and real results)", () => { return harness; } + it("settles a call from updates that send the SDK's null fields", () => { + const harness = startedHarness(); + const updates = [ + { + sessionUpdate: "tool_call", + toolCallId: "call-null", + title: "`pnpm test`", + kind: "execute", + status: "pending", + rawInput: { command: "pnpm test" }, + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "call-null", + status: "in_progress", + title: null, + content: null, + locations: null, + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "call-null", + status: "failed", + title: null, + locations: null, + content: [ + { type: "content", content: { type: "text", text: "3 failed\n" } }, + ], + }, + ]; + const events = updates.flatMap((update) => + harness.translate(updateEvent(update)), + ); + + expect(completedItems(events)).toEqual([ + expect.objectContaining({ + type: "commandExecution", + command: "pnpm test", + status: "failed", + aggregatedOutput: "3 failed\n", + }), + ]); + }); + it("reports the exit code and stderr Cursor sent, not a status guess", () => { const events = startedHarness().translate( updateEvent({ diff --git a/packages/provider-bridge-acp/src/wire.test.ts b/packages/provider-bridge-acp/src/wire.test.ts index 4ccb866f1eb..5e2c23908d4 100644 --- a/packages/provider-bridge-acp/src/wire.test.ts +++ b/packages/provider-bridge-acp/src/wire.test.ts @@ -26,6 +26,24 @@ describe("acpToolCallUpdateEventSchema", () => { expect(nulls.status).toBeUndefined(); }); + it("reads the SDK's nullable title, name, content and locations as absent", () => { + const parsed = acpToolCallUpdateEventSchema.parse({ + sessionUpdate: "tool_call_update", + toolCallId: "call-1", + status: "failed", + title: null, + name: null, + content: null, + locations: null, + }); + + expect(parsed).toEqual({ + sessionUpdate: "tool_call_update", + toolCallId: "call-1", + status: "failed", + }); + }); + it("skips a content entry of an unknown type instead of dropping the call", () => { const parsed = acpToolCallUpdateEventSchema.parse({ sessionUpdate: "tool_call_update", @@ -42,6 +60,21 @@ describe("acpToolCallUpdateEventSchema", () => { ]); }); + it("accepts a permission request whose tool call carries SDK nulls", () => { + const parsed = acpRequestPermissionParamsSchema.parse({ + sessionId: "s", + toolCall: { + toolCallId: "call-1", + title: null, + content: null, + locations: null, + }, + options: [{ optionId: "y", name: "Allow", kind: "allow_once" }], + }); + + expect(parsed.toolCall).toEqual({ toolCallId: "call-1" }); + }); + it("opens the enums on a permission request's tool call too", () => { const parsed = acpRequestPermissionParamsSchema.parse({ sessionId: "s", diff --git a/packages/provider-bridge-acp/src/wire.ts b/packages/provider-bridge-acp/src/wire.ts index a24ae313d57..3b3c915700e 100644 --- a/packages/provider-bridge-acp/src/wire.ts +++ b/packages/provider-bridge-acp/src/wire.ts @@ -96,20 +96,24 @@ const acpToolCallLocationSchema = z }) .passthrough(); -const acpToolCallNameSchema = z - .union([z.string(), z.null()]) - .transform((value) => value ?? undefined) - .optional(); +function acpNullAsAbsent(schema: Schema) { + return schema + .nullable() + .transform((value) => value ?? undefined) + .optional(); +} + +const acpOptionalString = acpNullAsAbsent(z.string()); const acpToolCallFieldsSchema = z.object({ toolCallId: z.string(), - title: z.string().optional(), - name: acpToolCallNameSchema, + title: acpOptionalString, + name: acpOptionalString, kind: acpToolKindSchema.optional(), rawKind: z.string().optional(), status: acpToolCallStatusSchema.optional(), - content: acpToolCallContentListSchema.optional(), - locations: z.array(acpToolCallLocationSchema).optional(), + content: acpNullAsAbsent(acpToolCallContentListSchema), + locations: acpNullAsAbsent(z.array(acpToolCallLocationSchema)), rawInput: z.unknown().optional(), rawOutput: z.unknown().optional(), }); @@ -252,11 +256,6 @@ export const acpSessionNotificationParamsSchema = z }) .passthrough(); -const acpOptionalString = z - .union([z.string(), z.null()]) - .transform((value) => value ?? undefined) - .optional(); - const acpConfigOptionSelectOptionSchema = z .object({ value: z.string(),