Skip to content
TypeScript

fix(acp): a lost or locked Copilot session restarts on the next message instead of failing every time (#26651)

Ian Rowe28bfae00d4a4
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
index 5a18843d709..fa5b15bbc5f 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
@@ -2169,4 +2169,173 @@ describe("AcpRegistryAdapterV2", () => {
assert.isFalse(yield* queued.runtime.hasPendingBackgroundWork!);
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+
+ it.effect.each([
+ {
+ failure: "a lost session",
+ error: {
+ code: -32603,
+ message: "Internal error",
+ data: {
+ details:
+ "Request session.send failed with message: session event delivery failed: session not found: copilot-session",
+ },
+ },
+ restarts: true,
+ },
+ {
+ failure: "a lost session reported in the message",
+ error: {
+ code: -32603,
+ message:
+ "Request session.send failed with message: session event delivery failed: session not found: copilot-session",
+ },
+ restarts: true,
+ },
+ {
+ failure: "a session-lock timeout",
+ error: {
+ code: -32603,
+ message: "Internal error",
+ data: {
+ details:
+ "session lock unavailable during is_session_generation_current: acquisition timed out",
+ },
+ },
+ restarts: true,
+ },
+ {
+ failure: "a session-lock timeout reported in the message",
+ error: {
+ code: -32603,
+ message:
+ "Request session.send failed with message: session lock unavailable during is_session_generation_current: acquisition timed out",
+ },
+ restarts: true,
+ },
+ {
+ failure: "an unrelated internal error",
+ error: {
+ code: -32603,
+ message: "Request session.send failed with message: Session directory no longer exists",
+ },
+ restarts: false,
+ },
+ ] as const)("runs Copilot's next message after $failure", ({ error, restarts }) =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-copilot-lost-" });
+ const scriptPath = yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
+ );
+ const request = (method: string, params: unknown = "<any>") => ({
+ type: "expect_outbound",
+ frame: { kind: "request", method, params },
+ });
+ const respond = (method: string, response: object) => ({
+ type: "emit_inbound",
+ frame: { kind: "response", method, ...response },
+ });
+ const start = (sessionId: string) => [
+ request("initialize"),
+ respond("initialize", {
+ result: { protocolVersion: 1, agentCapabilities: { loadSession: true } },
+ }),
+ request("session/new"),
+ respond("session/new", { result: { sessionId } }),
+ ];
+ const failedPrompt = [
+ ...start("copilot-session"),
+ request("session/prompt"),
+ respond("session/prompt", { error }),
+ ];
+ const completedPrompt = [
+ request("session/prompt"),
+ respond("session/prompt", { result: { stopReason: "end_turn" } }),
+ ];
+ const processes = restarts
+ ? [
+ failedPrompt,
+ [
+ ...start("replacement-session"),
+ request("session/load", {
+ sessionId: "copilot-session",
+ cwd: "<workspace>",
+ mcpServers: "<any>",
+ }),
+ respond("session/load", { result: {} }),
+ ...completedPrompt,
+ ],
+ ]
+ : [[...failedPrompt, ...completedPrompt]];
+ let spawned = 0;
+ const instanceId = ProviderInstanceId.make("copilot-lost-session");
+ const adapter = yield* makeAcpRegistryAdapterV2({
+ selfInvocation: yield* resolveSelfInvocation(),
+ instanceId,
+ settings: yield* decodeAcpRegistryAdapterSettings({ agentId: "github-copilot-cli" }),
+ environment: {},
+ makeRuntime: (runtimeInput) =>
+ Effect.gen(function* () {
+ const index = spawned++;
+ const transcript = yield* decodeAcpReplayTranscript(
+ {
+ provider: ACP_REGISTRY_PROVIDER,
+ protocol: "acp.ndjson-jsonrpc",
+ version: "1",
+ scenario: `copilot-lost-session-${index}`,
+ entries: processes[index] as never,
+ },
+ ACP_REGISTRY_PROVIDER,
+ ).pipe(Effect.orDie);
+ return yield* makeAcpReplayRuntime({
+ transcript,
+ statusPath: path.join(replayDir, `status-${index}.json`),
+ scriptPath,
+ childProcessSpawner,
+ fileSystem,
+ })(runtimeInput);
+ }),
+ }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
+ const threadId = ThreadId.make("thread-copilot-lost-session");
+ const modelSelection = { instanceId, model: "default" } as const;
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ cwd: replayDir,
+ });
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("session-copilot-lost-session"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ const now = yield* DateTime.now;
+ const runTurn = (ordinal: number) =>
+ runtime
+ .startTurn(
+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),
+ )
+ .pipe(
+ Effect.andThen(
+ runtime.events.pipe(
+ Stream.filter((event) => event.type === "turn.terminal"),
+ Stream.take(1),
+ Stream.runCollect,
+ ),
+ ),
+ Effect.map(([terminal]) => terminal?.status),
+ );
+ assert.equal(yield* runTurn(1), "failed");
+ assert.equal(yield* runTurn(2), "completed");
+ assert.equal(spawned, restarts ? 2 : 1);
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
});
diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts
index 6c2b4a9f6a1..4a3fb1ecd59 100644
--- a/packages/provider-acp-registry/src/server/adapter.ts
+++ b/packages/provider-acp-registry/src/server/adapter.ts
@@ -12,6 +12,7 @@ import { extractDroidElicitationForm } from "./droidAcp.ts";
import {
copilotClientCapabilitiesMeta,
extractCopilotSubagentUpdate,
+ isCopilotLostSessionError,
makeCopilotSubagentRouting,
} from "./copilotAcp.ts";
import { defaultInstanceIdForDriver, ProviderDriverKind } from "@t3tools/contracts";
@@ -255,6 +256,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
registerExtensions: copilotRouting.registerExtensions,
normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
extractSubagentUpdate: extractCopilotSubagentUpdate,
+ restartRuntimeAfterPromptError: isCopilotLostSessionError,
}),
makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog),
...(runtimeCoordinator === undefined
diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts
index 6414d37b050..5f29c930e9a 100644
--- a/packages/provider-acp-registry/src/server/copilotAcp.ts
+++ b/packages/provider-acp-registry/src/server/copilotAcp.ts
@@ -1,6 +1,7 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import type * as AcpSchema from "effect-acp/compat";
+import * as AcpErrors from "effect-acp/errors";
import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
import type {
AcpAdapterV2ExtensionContext,
@@ -24,6 +25,26 @@ export const copilotClientCapabilitiesMeta = {
},
};
+const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
+
+/** Copilot keeps failing every prompt with these until its process is replaced. */
+const COPILOT_LOST_SESSION_MARKERS = [
+ "session event delivery failed: session not found: ",
+ "session lock unavailable during is_session_generation_current: acquisition timed out",
+];
+
+export function isCopilotLostSessionError(error: unknown): boolean {
+ if (!isAcpRequestError(error) || error.method !== "session/prompt" || error.code !== -32603) {
+ return false;
+ }
+ // Older Copilot reports the cause in data.details; its native ACP layer (1.0.105) in the message.
+ return [error.errorMessage, record(error.data)?.details].some(
+ (text) =>
+ typeof text === "string" &&
+ COPILOT_LOST_SESSION_MARKERS.some((marker) => text.includes(marker)),
+ );
+}
+
const CopilotSessionEvent = Schema.Struct({
sessionId: Schema.String,
type: Schema.String,
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 1997a23a249..10dd5d53d3d 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -407,6 +407,8 @@ export interface AcpAdapterV2Flavor {
readonly reportsPerTurnPromptUsage?: boolean;
/** Grok can retain task_already_running until process exit. */
readonly restartRuntimeAfterInterrupt?: boolean;
+ /** Prompt failures after which the agent process keeps failing until replaced. */
+ readonly restartRuntimeAfterPromptError?: (error: unknown) => boolean;
readonly restartRuntimeOnEveryInterrupt?: boolean;
readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
readonly preserveRuntimeOnSettledInterrupt?: boolean;
@@ -7840,12 +7842,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
Result.isSuccess(error) &&
error.success._tag === "AcpRequestError" &&
error.success.code === -32800);
+ const failure = Cause.squash(cause);
+ if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) {
+ yield* Ref.set(runtimeRestartRequired, true);
+ }
yield* finalizeTurn(
context,
interrupted ? "interrupted" : "failed",
- flavor.promptFailure?.(Cause.squash(cause)) ??
+ flavor.promptFailure?.(failure) ??
makeProviderFailure({
- cause: Cause.squash(cause),
+ cause: failure,
class: "provider_error",
}),
).pipe(