TypeScript
fix(acp): idle agent errors fail their turns (#24615)
Julius Marminge5a969c17e763
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.tsindex 7a749b501bd..440e3ffa6d0 100644--- a/apps/server/scripts/acp-mock-agent.ts+++ b/apps/server/scripts/acp-mock-agent.ts@@ -962,6 +962,124 @@ const program = Effect.gen(function* () {const requestedSessionId = String(request.sessionId ?? sessionId);beginAcpMockPrompt(cancelledSessions, requestedSessionId);promptCount += 1;+ const idleError = process.env.T3_ACP_IDLE_ERROR;+ if (idleError === "grok-background" && promptCount === 1) {+ // The structured completion lands before the prompt settles, so it is buffered.+ const taskId = "call-idle-error-background";+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call",+ toolCallId: taskId,+ title: "run_terminal_command",+ kind: "execute",+ status: "in_progress",+ rawInput: { command: "sleep 1; echo done" },+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: taskId,+ status: "completed",+ rawOutput: {+ type: "BackgroundTaskStarted",+ task_id: taskId,+ task_type: "bash",+ status: "running",+ command: "sleep 1; echo done",+ },+ },+ });+ writeJsonRpcNotification("_x.ai/task_completed", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "task_completed",+ task_snapshot: { task_id: taskId, kind: "bash", exit_code: 0, output: "done\n" },+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: { sessionUpdate: "state_update", state: "idle", stopReason: "error" },+ });+ return {};+ }+ if (idleError !== undefined && promptCount === 1) {+ const toolCallId = "tool-call-idle-error-1";+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId,+ title: "Terminal",+ kind: "execute",+ status: "in_progress",+ rawInput: { command: ["long-running-tool"] },+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "tool-call-idle-error-monitor",+ title: "Monitor",+ kind: "execute",+ status: "in_progress",+ rawInput: { command: ["background-monitor"] },+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "tool-call-idle-error-subagent",+ title: "Subagent",+ kind: "other",+ status: "in_progress",+ rawInput: {},+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId: "mock-child-session-idle-error",+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "tool-call-idle-error-child",+ title: "Child tool",+ kind: "execute",+ status: "in_progress",+ rawInput: { command: ["child-tool"] },+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "state_update",+ state: "idle",+ stopReason: "error",+ ...(idleError === "details"+ ? { error: { code: -32000, message: "Missing Authentication header" } }+ : {}),+ },+ });+ // The agent outlives the failed prompt, so its subagent finishes afterwards.+ yield* Effect.sleep("50 millis").pipe(+ Effect.andThen(+ Effect.sync(() =>+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "tool-call-idle-error-subagent",+ status: "completed",+ },+ }),+ ),+ ),+ Effect.forkDetach,+ );+ return {};+ }if (process.env.T3_ACP_CRASH_PROMPT === "1" &&request.prompt.some((part) => part.type === "text" && part.text === "crash now")diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.tsindex 12d1a0846bb..c636915c893 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts@@ -399,6 +399,151 @@ function assertReinjectedInstructions(}describe("AcpAdapterV2", () => {+ it.live.each(["details", "none"] as const)(+ "fails the turn on an ACP v2 idle error with %s, settles its open tool, and accepts the next prompt",+ (details) =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const instanceId = ProviderInstanceId.make(`idle-error-${details}`);+ const threadId = ThreadId.make(`thread-idle-error-${details}`);+ const childSessionId = "mock-child-session-idle-error";+ const adapter = yield* makeAcpAdapterV2({+ instanceId,+ selfInvocation: yield* resolveSelfInvocation(),+ flavor: {+ driver: ACP_TEST_DRIVER,+ capabilities: AcpProviderCapabilitiesV2,+ extractBackgroundTaskId: (toolCall) =>+ toolCall.toolCallId === "tool-call-idle-error-monitor"+ ? "idle-error-monitor"+ : undefined,+ extractSubagentUpdate: (toolCall) =>+ toolCall.toolCallId === "tool-call-idle-error-subagent"+ ? {+ nativeTaskId: "task-idle-error",+ prompt: "child work",+ title: "child work",+ model: null,+ status: toolCall.status === "completed" ? "completed" : "running",+ childSessionId,+ result: null,+ suppressNormalTool: true,+ }+ : undefined,+ makeRuntime: makeMockRuntime({+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,+ mockAgentPath: yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ ),+ environment: { T3_ACP_IDLE_ERROR: details },+ }),+ },+ });+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const modelSelection = { instanceId, model: "default" } as const;+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make(`session-idle-error-${details}`),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ const runTurn = (ordinal: number) =>+ Effect.gen(function* () {+ yield* runtime.startTurn(+ makeTurnInput({+ threadId,+ providerThread,+ instanceId,+ runtimePolicy,+ now: yield* DateTime.now,+ ordinal,+ }),+ );+ return yield* runtime.events.pipe(+ Stream.takeUntil((event) => event.type === "turn.terminal"),+ Stream.runCollect,+ );+ });++ const failedEvents = yield* runTurn(1);+ const failed = failedEvents.at(-1);+ assert.equal(failed?.type, "turn.terminal");+ if (failed?.type !== "turn.terminal" || failed.status !== "failed") {+ return assert.fail("expected a failed terminal");+ }+ assert.isTrue(+ failed.childTurnsContinue,+ "the run keeps ingesting work that outlives the failed prompt",+ );+ const lateSubagent = yield* runtime.events.pipe(+ Stream.filter(+ (event) => event.type === "subagent.updated" && event.subagent.status === "completed",+ ),+ Stream.runHead,+ Effect.timeoutOption("2 seconds"),+ );+ assert.isTrue(+ Option.isSome(lateSubagent) && Option.isSome(lateSubagent.value),+ "a subagent finishing after the failed prompt still reports to the run",+ );+ assert.deepEqual(+ failed.failure,+ details === "details"+ ? {+ class: "provider_error",+ message: "Missing Authentication header",+ code: "-32000",+ retryable: null,+ }+ : {+ class: "provider_error",+ message: "Provider turn failed.",+ code: null,+ retryable: null,+ },+ );+ const toolItems = (nativeId: string) =>+ failedEvents.flatMap((event) =>+ event.type === "turn_item.updated" &&+ event.turnItem.nativeItemRef?.nativeId === nativeId+ ? [event.turnItem]+ : [],+ );+ const toolStatuses = toolItems("tool-call-idle-error-1").map((item) => item.status);+ assert.include(toolStatuses, "running");+ assert.equal(toolStatuses.at(-1), "failed");+ assert.deepEqual(+ toolItems("tool-call-idle-error-monitor").map((item) => item.status),+ ["running"],+ "a background monitor outlives the failed turn and keeps its running row",+ );+ const childItems = toolItems("task-idle-error:tool:tool-call-idle-error-child");+ assert.deepEqual(+ childItems.map((item) => item.status),+ ["running"],+ "a child-session tool keeps running in its own thread",+ );+ assert.isTrue(childItems.every((item) => item.threadId !== threadId));+ assert.isEmpty(+ toolItems("tool-call-idle-error-child"),+ "the failed turn must not reproject the child tool as a root tool",+ );++ const nextEvents = yield* runTurn(2);+ const next = nextEvents.at(-1);+ assert.equal(next?.type === "turn.terminal" ? next.status : undefined, "completed");+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );+// Factory Droid 0.243.0 sends an optional text companion for every AskUser choice.const droidChoice = {type: "string",@@ -3082,6 +3227,72 @@ describe("AcpAdapterV2", () => {}).pipe(Effect.provide(layerTest), Effect.scoped),);+ it.live("settles a Grok background command that completed before an ACP v2 idle error", () =>+ Effect.gen(function* () {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const path = yield* Path.Path;+ const mockAgentPath = yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ );+ const instanceId = ProviderInstanceId.make("grok-idle-error-background");+ const adapter = yield* makeGrokAdapterV2({+ instanceId,+ settings: DEFAULT_GROK_SETTINGS,+ environment: {},+ hostPlatform: yield* HostProcess.Platform,+ selfInvocation: yield* resolveSelfInvocation(),+ makeRuntime: (input) =>+ makeMockRuntime({+ childProcessSpawner,+ mockAgentPath,+ environment: { T3_ACP_IDLE_ERROR: "grok-background" },+ })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)),+ });+ const threadId = ThreadId.make("grok-idle-error-background");+ const modelSelection = { instanceId, model: "default" } as const;+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("grok-idle-error-background"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ yield* runtime.startTurn(+ makeTurnInput({+ threadId,+ providerThread,+ instanceId,+ runtimePolicy,+ now: yield* DateTime.now,+ }),+ );+ const events = yield* runtime.events.pipe(+ Stream.takeUntil((event) => event.type === "turn.terminal"),+ Stream.runCollect,+ );+ const terminal = events.at(-1);+ assert.equal(terminal?.type === "turn.terminal" ? terminal.status : undefined, "failed");+ const command = events.findLast(+ (event) =>+ event.type === "turn_item.updated" &&+ event.turnItem.nativeItemRef?.nativeId === "call-idle-error-background",+ );+ assert.equal(+ command?.type === "turn_item.updated" ? command.turnItem.status : undefined,+ "completed",+ );+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );+// Oracle: Grok incident frames. Command completion must release the turn even// when the CLI keeps the prompt RPC and process alive. Command polls stay visible.it.live(diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex 89d83941bd8..03bbbf0506b 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -1850,6 +1850,17 @@ it.effect.each([null, "run:nested-sdk"] as const)(}),);+it.effect("keeps ingesting a failed root's background item when its work continues", () =>+ Effect.gen(function* () {+ const observed = yield* runBackgroundItemScenario("bg-failed-continues", (ids) => [+ backgroundTurnItemEvent(ids, "command_execution", "running", 1),+ { ...rootTerminalEvent(ids, "failed"), childTurnsContinue: true },+ backgroundTurnItemEvent(ids, "command_execution", "completed", 2),+ ]);+ assert.deepEqual(observed, ["turn_item:running", "root-finalized", "turn_item:completed"]);+ }),+);+it.effect("does not pin ingestion on background items when the root turn is interrupted", () =>Effect.gen(function* () {const observed = yield* runBackgroundItemScenario("bg-interrupted", (ids) => [diff --git a/packages/effect-acp/src/client.test.ts b/packages/effect-acp/src/client.test.tsindex db8630ab27c..58823a5de54 100644--- a/packages/effect-acp/src/client.test.ts+++ b/packages/effect-acp/src/client.test.ts@@ -1307,6 +1307,37 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {}),);+ it.effect("returns the ACP v2 idle error as the prompt result", () =>+ Effect.gen(function* () {+ const { stdio, input, output } = yield* makeInMemoryStdio();+ const acp = yield* AcpClient.make(stdio);+ const error = { code: -32000, message: "Missing Authentication header" };+ const prompt = yield* acp.agent+ .prompt({ sessionId: "idle-error", prompt: [{ type: "text", text: "Hello" }] })+ .pipe(Effect.forkScoped);+ const request = yield* decodePromptRequestLine(yield* Queue.take(output));+ yield* Queue.offer(+ input,+ concatBytes([+ yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {+ jsonrpc: "2.0",+ id: request.id,+ result: { messageId: `user-${request.id}` },+ }),+ yield* encodeJsonl(SessionUpdateNotification, {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: "idle-error",+ update: { sessionUpdate: "state_update", state: "idle", stopReason: "error", error },+ },+ }),+ ]),+ );+ assert.deepEqual(yield* Fiber.join(prompt), { stopReason: "error", error });+ }).pipe(Effect.scoped),+ );+it.effect("routes MCP-over-ACP connect, message, notification, and disconnect callbacks", () =>Effect.gen(function* () {const handle = yield* makeHandle({ ACP_MOCK_MCP_OVER_ACP: "1" });diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.tsindex 785d8153605..0527883acc7 100644--- a/packages/effect-acp/src/client.ts+++ b/packages/effect-acp/src/client.ts@@ -797,6 +797,7 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (return Deferred.succeed(completion, {stopReason: idle.stopReason ?? "end_turn",...(idle.usage === undefined ? {} : { usage: idle.usage }),+ ...(idle.error === undefined ? {} : { error: idle.error }),...(idle._meta === undefined ? {} : { _meta: idle._meta }),}).pipe(Effect.asVoid);})diff --git a/packages/effect-acp/src/compat.ts b/packages/effect-acp/src/compat.tsindex 586a0b3048c..e2328b51b37 100644--- a/packages/effect-acp/src/compat.ts+++ b/packages/effect-acp/src/compat.ts@@ -242,6 +242,7 @@ export type PromptRequest = Omit<V2.PromptRequest, "prompt"> & {export interface PromptResponse {readonly stopReason: StopReason;readonly usage?: V2.Usage | null;+ readonly error?: V2.Error | null;readonly _meta?: Meta;}diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex 7d4438a64df..54409011f58 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -1314,7 +1314,8 @@ function acpSubagentHasPendingBackgroundWork(subagent: ActiveAcpSubagent): booletype AcpCarryoverSubagents = {readonly sessionId: string;- readonly rootTerminalStatus: "completed" | "interrupted" | "failed" | "cancelled";+ /** The root's subscriber keeps ingesting, so late child terminals can still project. */+ readonly projectsLateTerminals: boolean;readonly subagents: ReadonlyArray<ActiveAcpSubagent>;};@@ -3373,6 +3374,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (return false;};+ const hasSurvivingBackgroundWork = (context: ActiveAcpTurn): boolean =>+ [...context.toolCallIdsByBackgroundTaskId.values()].some((toolCallId) => {+ const tool = context.tools.get(toolCallId);+ const status = tool === undefined ? undefined : toolStatus(tool.status);+ return status === "pending" || status === "running";+ }) ||+ [...context.subagents.values()].some((subagent) =>+ acpSubagentStatusBlocksTurnSettlement(subagent.task.status),+ );+const rearmDeferredFinalize =/* Provider events include streaming deltas; avoid a span for each update. */Effect.fnUntraced(function* (context: ActiveAcpTurn) {@@ -4443,6 +4454,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (return true;});+ const idleErrorFailure = (error: EffectAcpSchema.PromptResponse["error"]) =>+ flavor.promptFailure?.(+ new EffectAcpErrors.AcpRequestError({+ code: error?.code ?? -32603,+ errorMessage: error?.message ?? "Provider turn failed.",+ ...(error?.data === undefined ? {} : { data: error.data }),+ }),+ ) ??+ makeProviderFailure({+ message: error?.message,+ code: error == null ? null : String(error.code),+ class: "provider_error",+ });+const settleIdleWork = Effect.fnUntraced(function* (context: ActiveAcpTurn,): Effect.fn.Return<void> {@@ -4459,16 +4484,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (if (work.stopReason === "cancelled" && pendingStopCloseTurn === context) {context.interrupted = true;}- const failure =- work.stopReason === "error"- ? (flavor.promptFailure?.(- new EffectAcpErrors.AcpRequestError({- code: work.error?.code ?? -32603,- errorMessage: work.error?.message ?? "Provider turn failed.",- ...(work.error?.data === undefined ? {} : { data: work.error.data }),- }),- ) ?? makeProviderFailure({ message: work.error?.message, class: "provider_error" }))- : undefined;+ const failure = work.stopReason === "error" ? idleErrorFailure(work.error) : undefined;yield* finalizeTurn(context,failure !== undefined@@ -4684,7 +4700,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (const rootTerminalCanStillProject =carryover !== null &&carryover.sessionId === (yield* Ref.get(activeSessionId)) &&- carryover.rootTerminalStatus === "completed";+ carryover.projectsLateTerminals;const projectCarryover = rootTerminalCanStillProject;let carryoverTerminalized = false;if (@@ -5677,7 +5693,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (project:carryover !== null &&carryover.sessionId === (yield* Ref.get(activeSessionId)) &&- carryover.rootTerminalStatus === "completed",+ carryover.projectsLateTerminals,},);});@@ -6932,11 +6948,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (const terminalizeOpenForegroundTools = Effect.fnUntraced(function* (context: ActiveAcpTurn,+ status: "completed" | "failed" = "completed",) {for (const tool of context.tools.values()) {if (!acpCompletedTurnShouldTerminalizeTool(tool, { ...flavor, extractSubagentUpdate }))continue;- yield* emitTool(context, tool, "completed");+ yield* emitTool(context, tool, status);}});@@ -6960,6 +6977,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (context: ActiveAcpTurn,status: "completed" | "interrupted" | "failed" | "cancelled",failure?: OrchestrationV2ProviderFailure,+ options?: { readonly childTurnsContinue?: boolean },): Effect.fn.Return<void> {if (context.finalized) return;const settledStatus = context.interrupted ? "interrupted" : status;@@ -7059,6 +7077,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (providerThread: updatedProviderThread,});const rootSessionId = yield* Ref.get(activeSessionId);+ const childTurnsContinue =+ settledStatus === "failed" &&+ (options?.childTurnsContinue === true ||+ (followsAgentWorkState &&+ rootSessionId !== null &&+ hasWorkingDescendant(rootSessionId)));yield* emitProviderEvent(settledStatus === "failed"? {@@ -7072,11 +7096,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (`terminal-failure:${context.providerTurnId}`,),status: settledStatus,- ...(followsAgentWorkState &&- rootSessionId !== null &&- hasWorkingDescendant(rootSessionId)- ? { childTurnsContinue: true }- : {}),+ ...(childTurnsContinue ? { childTurnsContinue: true } : {}),failure: failure ?? makeProviderFailure({ class: "provider_error" }),...(context.providerRetry === undefined? {}@@ -7105,7 +7125,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (if (sessionId !== null) {yield* Ref.set(carryoverSubagents, {sessionId,- rootTerminalStatus: settledStatus,+ projectsLateTerminals: settledStatus === "completed" || childTurnsContinue,subagents: subagentsRequiringCarryover,});}@@ -7590,8 +7610,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (promptGeneration,Effect.gen(function* () {if (context.finalized || followsAgentWorkState) return;- const status =- result.stopReason === "cancelled"+ // ACP v2 reports a failed prompt as an idle `error`, not an RPC error.+ const idleError = result.stopReason === "error" && !context.interrupted;+ const status = idleError+ ? "failed"+ : result.stopReason === "cancelled"? context.interrupted? "interrupted": "cancelled"@@ -7604,6 +7627,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (yield* finishRegisteredBackgroundTool({ taskId, ...completion });}}+ if (idleError) {+ yield* terminalizeOpenForegroundTools(context, "failed");+ // Unlike an RPC failure, the agent survives an idle error, so its+ // background tools and subagents keep reporting to this run.+ yield* finalizeTurn(context, "failed", idleErrorFailure(result.error), {+ childTurnsContinue: hasSurvivingBackgroundWork(context),+ });+ return;+ }if (flavor.deferFinalizeForBackgroundWork === true &&!context.interrupted &&