diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 348c2f38b0190..235d923a2f39d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -11452,6 +11452,15 @@ describe("AcpAdapterV2", () => { assert.equal(backgroundItem.turnItem.output ?? "", output); } }); + // A foreground tool still open at end_turn must not hold the deferred finalize. + yield* update({ + sessionUpdate: "tool_call", + toolCallId: "stale-foreground", + title: "Read file", + kind: "read", + status: "in_progress", + rawInput: { path: "a.ts" }, + }); yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); while (true) { const event = yield* Queue.take(events); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 55b313a9d3adc..a373b9ea54586 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -410,6 +410,29 @@ const claudeMarker = (title: string) => sessionUpdate: "session_info_update", title, }); +// Factory Droid speaks ACP v1, so its prompt ends with a `session/prompt` response. +const droidFirstTurn = (...frames: ReadonlyArray) => [ + ...claudeFrames.open.map((entry) => + entry.frame.method === "initialize" && entry.type === "emit_inbound" + ? { + ...entry, + frame: { + ...entry.frame, + result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] }, + }, + } + : entry, + ), + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + ...frames, + { + type: "emit_inbound", + frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } }, + }, +]; const claudeChild = [ claudeFrames.update(CLAUDE_ROOT_SESSION, { sessionUpdate: "tool_call_update", @@ -3197,6 +3220,371 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("continues Factory Droid when its background Task finishes after end_turn", () => + Effect.gen(function* () { + const { update } = claudeFrames; + const gate = makeProviderReplayGate(["task-completed", "answer"]); + const launchTask = (toolCallId: string) => + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call", + toolCallId, + title: "Task", + kind: "other", + status: "completed", + rawInput: { subagent_type: "explorer", prompt: `sleep 20; echo ${toolCallId}` }, + rawOutput: { type: "Text", text: "Task launched in background" }, + }); + // A Task the previous run never saw must still merge with the run that launched it. + const assertTaskCard = ( + events: ReadonlyArray, + toolCallId: string, + ) => { + const task = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === toolCallId, + ); + if (task?.type !== "turn_item.updated") throw new Error(`Missing ${toolCallId} update`); + assert.include(task.turnItem, { title: "Task", status: "completed" }); + assert.deepInclude(task.turnItem, { + input: { subagent_type: "explorer", prompt: `sleep 20; echo ${toolCallId}` }, + }); + }; + const session = yield* openClaudeReplaySession( + [ + ...droidFirstTurn( + launchTask("task-1"), + launchTask("task-2"), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "waiting" }, + }), + ), + { + ...update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "task-1", + status: "completed", + rawOutput: { type: "Text", text: "The command ran and exited with code 0." }, + }), + label: "task-completed", + }, + claudeMarker("task done"), + { + ...update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "task-2", + status: "completed", + rawOutput: { type: "Text", text: "The second task exited with code 0." }, + }), + label: "answer", + }, + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "usage_update", + used: 2_000, + size: 10_000, + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "The background task exited with code 0." }, + }), + claudeMarker("late answer"), + claudeFrames.closeRequest, + claudeFrames.closed, + ], + gate, + true, + "factory-droid", + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("task-completed"); + yield* session.throughMarker("task done"); + assert.lengthOf(session.offers, 1, "Droid's Task completion must offer a continuation run"); + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + const taskSettled = yield* Effect.forkScoped( + session.until((event) => event.type === "turn.terminal"), + ); + yield* TestClock.adjust("3 seconds"); + const taskRun = yield* Fiber.join(taskSettled); + assert.include(taskRun.at(-1), { runOrdinal: 2, status: "completed" }); + assertTaskCard(taskRun, "task-1"); + // Droid answers ~4 s after the Task result, past the quiet window. + gate.release("answer"); + yield* session.throughMarker("late answer"); + assert.lengthOf(session.offers, 2, "Droid's late answer must offer another continuation"); + yield* session.offers[1]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(3, { continuation: true })); + const answerRun = yield* session.until( + (event) => + event.type === "message.updated" && + event.message.text === "The background task exited with code 0.", + ); + assertTaskCard(answerRun, "task-2"); + const answer = answerRun.at(-1); + if (answer?.type !== "message.updated") throw new Error("Missing late answer"); + assert.equal(answer.message.runId, session.turnInput(3).runId); + const answerSettled = yield* Effect.forkScoped(session.terminal); + yield* TestClock.adjust("3 seconds"); + assert.include(yield* Fiber.join(answerSettled), { runOrdinal: 3, status: "completed" }); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect.each([ + { + blocker: "an unanswered question", + frames: [ + { + type: "emit_inbound", + label: "blocker", + frame: { + kind: "request", + method: "elicitation/create", + params: { + sessionId: CLAUDE_ROOT_SESSION, + mode: "form", + message: "Which file?", + requestedSchema: { + type: "object", + properties: { + question_1: { + type: "string", + title: "File", + description: "Which file should I inspect?", + oneOf: [ + { const: "option_0", title: "a.ts" }, + { const: "other", title: "Other" }, + ], + }, + question_1_other: { type: "string" }, + }, + required: ["question_1"], + }, + }, + }, + }, + { ...claudeMarker("still waiting"), label: "check" }, + { + type: "expect_outbound", + frame: { + kind: "response", + method: "elicitation/create", + result: { action: "accept", content: { question_1: "option_0" } }, + }, + }, + ], + response: { answers: { question_1: "option_0" } }, + }, + { + blocker: "an unanswered approval", + frames: [ + { + type: "emit_inbound", + label: "blocker", + frame: { + kind: "request", + method: "session/request_permission", + params: { + sessionId: CLAUDE_ROOT_SESSION, + toolCall: { + toolCallId: "approve-command", + title: "Run tests", + kind: "execute", + status: "pending", + rawInput: { command: "vp test run" }, + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }, + }, + }, + { ...claudeMarker("still waiting"), label: "check" }, + { + type: "expect_outbound", + frame: { + kind: "response", + method: "session/request_permission", + result: { outcome: { outcome: "selected", optionId: "allow" } }, + }, + }, + ], + response: { decision: "accept" as const }, + }, + { + blocker: "a running tool", + frames: [ + { + ...claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call", + toolCallId: "slow-tool", + title: "Execute", + kind: "execute", + status: "in_progress", + rawInput: { command: "sleep 20; echo done" }, + }), + label: "blocker", + }, + claudeMarker("blocked"), + { ...claudeMarker("still waiting"), label: "check" }, + { + ...claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "slow-tool", + status: "completed", + rawOutput: { type: "Text", text: "done" }, + }), + label: "resolve", + }, + claudeMarker("resolved"), + ], + response: undefined, + }, + ])( + "keeps a Factory Droid continuation open past the quiet window for $blocker", + ({ frames, response }) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["wake", "blocker", "check", "resolve"]); + const session = yield* openClaudeReplaySession( + [ + ...droidFirstTurn(), + { + ...claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Checking the background result" }, + }), + label: "wake", + }, + claudeMarker("woke"), + ...frames, + claudeFrames.closeRequest, + claudeFrames.closed, + ], + gate, + true, + "factory-droid", + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("wake"); + yield* session.throughMarker("woke"); + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + gate.release("blocker"); + const blocked = (yield* session.until( + (event) => + (event.type === "runtime_request.updated" && + event.runtimeRequest.status === "pending") || + (event.type === "provider_thread.updated" && + event.providerThread.nativeMetadata?.title === "blocked"), + )).at(-1)!; + yield* TestClock.adjust("3 seconds"); + gate.release("check"); + assert.notInclude( + (yield* session.throughMarker("still waiting")).map((event) => event.type), + "turn.terminal", + "the continuation must not settle while Droid still waits", + ); + // Requests are answered with no later update, so only their resolution rearms the finalize. + if (blocked.type === "runtime_request.updated" && response !== undefined) { + yield* session.runtime.respondToRuntimeRequest({ + requestId: blocked.runtimeRequest.id, + ...response, + }); + } else { + gate.release("resolve"); + yield* session.throughMarker("resolved"); + } + const settled = yield* Effect.forkScoped(session.terminal); + yield* TestClock.adjust("3 seconds"); + assert.include(yield* Fiber.join(settled), { runOrdinal: 2, status: "completed" }); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + const permissionRequest = (toolCallId: string, kind: string) => ({ + kind: "request", + method: "session/request_permission", + params: { + sessionId: CLAUDE_ROOT_SESSION, + toolCall: { toolCallId, title: toolCallId, kind, status: "pending", rawInput: {} }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }, + }); + it.effect.each([ + { + request: "a question", + frame: { + kind: "request", + method: "elicitation/create", + params: { + sessionId: CLAUDE_ROOT_SESSION, + mode: "form", + message: "Which file?", + requestedSchema: { + type: "object", + properties: { + question_1: { + type: "string", + title: "File", + oneOf: [{ const: "option_0", title: "a.ts" }], + }, + }, + required: ["question_1"], + }, + }, + }, + reply: { + method: "elicitation/create", + result: { action: "accept", content: { question_1: "option_0" } }, + }, + response: { answers: { question_1: "option_0" } }, + }, + { + request: "an approval", + frame: permissionRequest("run-tests", "execute"), + reply: { + method: "session/request_permission", + result: { outcome: { outcome: "selected", optionId: "allow" } }, + }, + response: { decision: "accept" as const }, + }, + ])("admits $request Factory Droid sends after its run settled", ({ frame, reply, response }) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["request"]); + const session = yield* openClaudeReplaySession( + [ + ...droidFirstTurn(), + { type: "emit_inbound", label: "request", frame }, + { type: "expect_outbound", frame: { kind: "response", ...reply } }, + claudeMarker("answered"), + claudeFrames.closeRequest, + claudeFrames.closed, + ], + gate, + true, + "factory-droid", + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("request"); + yield* Queue.take(session.offered); + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + const pending = (yield* session.until( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + )).at(-1); + if (pending?.type !== "runtime_request.updated") throw new Error("Missing request"); + yield* session.runtime.respondToRuntimeRequest({ + requestId: pending.runtimeRequest.id, + ...response, + }); + yield* session.throughMarker("answered"); + const settled = yield* Effect.forkScoped(session.terminal); + yield* TestClock.adjust("3 seconds"); + assert.include(yield* Fiber.join(settled), { runOrdinal: 2, status: "completed" }); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect.each(["error", "end_turn"])( "hands live Claude child tools to the next run after %s and keeps nested output in the child", (stopReason) => diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..ffbbf2106edc3 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -273,7 +273,8 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : AcpProviderCapabilitiesV2, customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug), compactViaAdvertisedCommand: true, - ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}), + ...(isAntigravityCli ? { replyEndsWithUsageUpdate: true } : {}), + ...(isAntigravityCli || isDroid ? { wakeOnDetachedRequest: true } : {}), promptFailure: (cause) => acpRegistryPromptFailure(isVibe ? "mistral-vibe" : registryAgentId, cause), ...(isDroid @@ -308,14 +309,13 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu extractSubagentSessionEvent: extractClaudeSubagentSessionEvent, } : {}), - // Hermes replies on the root session when a background process it started exits; no - // prompt response follows, so the continuation ends on the deferred-finalize debounce. - // Hermes is not in the public registry and may run through a wrapper, so only its - // initialize reply identifies it. agy does the same and is known by its command. + // Hermes, agy and Droid reply on the root session when background work ends, with no + // prompt response, so the continuation ends on the deferred-finalize debounce. Hermes + // may run through a wrapper, so only its initialize reply identifies it. enablePostSettleContinuation: (initializeResult) => - isAntigravityCli || isHermes(initializeResult), + isAntigravityCli || isDroid || isHermes(initializeResult), deferFinalizeForBackgroundWork: (initializeResult) => - isAntigravityCli || isHermes(initializeResult), + isAntigravityCli || isDroid || isHermes(initializeResult), ...(isDevin ? { clientCapabilitiesMeta: { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e214a51586f4c..a7ec35dadc73a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1674,6 +1674,8 @@ interface ActiveAcpTurn { readonly stoppedToolCallIds: Set; readonly toolUpdatesSkipped: Map; readonly toolStartedAt: Map; + /** A continuation's sparse tool updates merge from the finalized run before it. */ + readonly precedingRunTools: AcpRunTools | null; readonly subagents: Map; readonly subagentsBySessionId: Map; readonly pendingSubagentNotifications: Map>; @@ -1941,6 +1943,8 @@ function acpSubagentHasPendingBackgroundWork(subagent: ActiveAcpSubagent): boole ); } +type AcpRunTools = Pick; + type AcpCarryoverSubagents = { readonly sessionId: string; /** The root's subscriber keeps ingesting, so late child terminals can still project. */ @@ -2607,6 +2611,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const stoppedRunQuarantine = yield* Ref.make(false); // Native subagents can outlive interrupts; carry lineage forward to finish their original turn items. const carryoverSubagents = yield* Ref.make(null); + const finalizedRunTools = yield* Ref.make< + (AcpRunTools & { readonly sessionId: string }) | null + >(null); const handledBackgroundTaskIdsInActiveTurn = yield* Ref.make>( new Set(), ); @@ -4333,6 +4340,35 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( acpSubagentStatusBlocksTurnSettlement(subagent.task.status), ); + const awaitsRequestOrTool = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + countsTool: (tool: AcpToolCallState) => boolean, + ) { + if (openAgentRequests.size > 0) return true; + if ((yield* Ref.get(pendingRuntimeRequests)).size > 0) return true; + for (const tool of context.tools.values()) { + const status = toolStatus(tool.status); + if (status !== "pending" && status !== "running" && status !== "waiting") continue; + if (countsTool(tool)) return true; + } + return false; + }); + + // Background tools and subagents are `hasDeferredBackgroundWork`'s, which skips + // persistent tasks that never end. + const isForegroundTool = ( + tool: AcpToolCallState & { readonly backgroundCommandTaskId?: string }, + ) => + tool.backgroundCommandTaskId === undefined && + flavor.extractBackgroundTaskId?.(tool) === undefined && + extractSubagentUpdate(tool) === undefined && + flavor.toolOutlivesPrompt?.(tool) !== true; + + const blocksDeferredFinalize = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + if (hasDeferredBackgroundWork(context)) return true; + return yield* awaitsRequestOrTool(context, isForegroundTool); + }); + const rearmDeferredFinalize = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (context: ActiveAcpTurn) { @@ -4341,6 +4377,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (hasDeferredBackgroundWork(context)) return; yield* scheduleDeferredFinalize(context); }); + const rearmActiveDeferredFinalize = Ref.get(activeTurn).pipe( + Effect.flatMap((context) => + context === null ? Effect.void : rearmDeferredFinalize(context), + ), + ); + const forgetPendingRuntimeRequest = (requestId: string) => + Ref.update(pendingRuntimeRequests, (current) => { + const updated = new Map(current); + updated.delete(requestId); + return updated; + }).pipe(Effect.andThen(rearmActiveDeferredFinalize)); // let breaks circular inference from monitor hydration re-entry. let emitTool: ( @@ -4407,7 +4454,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.reasoning.current?.sourceMessageId == null) yield* closeTextStream(context, "reasoning"); yield* closeTextStream(context, "user"); - const previous = context.tools.get(incoming.toolCallId); + const previous = + context.tools.get(incoming.toolCallId) ?? + context.precedingRunTools?.tools.get(incoming.toolCallId); const merged = mergeToolCallState(previous, incoming); const normalized = flavor.normalizeToolCall?.(merged) ?? merged; const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized); @@ -4607,7 +4656,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeId: toolCall.toolCallId, strength: "strong" as const, }; - const startedAt = context.toolStartedAt.get(toolCall.toolCallId) ?? now; + const startedAt = + context.toolStartedAt.get(toolCall.toolCallId) ?? + context.precedingRunTools?.toolStartedAt.get(toolCall.toolCallId) ?? + now; context.toolStartedAt.set(toolCall.toolCallId, startedAt); const completedAt = completedAtForStatus(status, now); const title = toolCall.title ?? null; @@ -6602,11 +6654,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.ensuring( runRuntimeCallbackAtGeneration( generation, - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(requestId)); - return updated; - }), + forgetPendingRuntimeRequest(String(requestId)), ).pipe(Effect.asVoid), ), ); @@ -7437,11 +7485,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.ensuring( runRuntimeCallbackAtGeneration( handlerGeneration, - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(requestId)); - return updated; - }), + forgetPendingRuntimeRequest(String(requestId)), ).pipe(Effect.asVoid), ), ); @@ -8494,13 +8538,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const terminalizeOpenForegroundTools = Effect.fnUntraced(function* ( context: ActiveAcpTurn, status: "completed" | "failed" = "completed", - options?: { readonly unstartedOnly?: boolean }, + options?: { readonly unstartedOnly?: boolean; readonly keepOutliving?: boolean }, ) { for (const tool of context.tools.values()) { if (!acpCompletedTurnShouldTerminalizeTool(tool, { ...flavor, extractSubagentUpdate })) continue; if (options?.unstartedOnly === true && tool.status !== "pending") continue; - yield* emitTool(context, tool, status); + if (options?.keepOutliving === true && flavor.toolOutlivesPrompt?.(tool) === true) + continue; + // Store the status too, so the deferred finalize stops counting the tool as open. + yield* emitTool(context, { ...tool, status }, status); } }); @@ -8725,6 +8772,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } } + if (postSettleContinuationEnabled && settledStatus === "completed") { + yield* Ref.set(finalizedRunTools, { + sessionId: context.nativeThreadId, + tools: new Map([...(context.precedingRunTools?.tools ?? []), ...context.tools]), + toolStartedAt: new Map([ + ...(context.precedingRunTools?.toolStartedAt ?? []), + ...context.toolStartedAt, + ]), + }); + } yield* Ref.set(activeTurn, null); if (settledStatus === "completed" && !directStopQuarantine) { yield* detachBackgroundCommands(context); @@ -8753,7 +8810,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) { if (!defersFinalizeForBackgroundWork) return; if (!context.promptSettled || context.finalized || context.interrupted) return; - if (hasDeferredBackgroundWork(context)) return; + if (yield* blocksDeferredFinalize(context)) return; context.backgroundFinalizeGeneration += 1; const generation = context.backgroundFinalizeGeneration; const replyOpen = context.replyOpen; @@ -8776,6 +8833,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* scheduleDeferredFinalize(context); return; } + if (yield* blocksDeferredFinalize(context)) return; const status = context.promptSettledStatus ?? "completed"; yield* finalizeTurn(context, status); }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); @@ -8785,12 +8843,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { - if (openAgentRequests.size > 0) return true; - if ((yield* Ref.get(pendingRuntimeRequests)).size > 0) return true; - for (const tool of context.tools.values()) { - const status = toolStatus(tool.status); - if (status === "pending" || status === "running" || status === "waiting") return true; - } + if (yield* awaitsRequestOrTool(context, () => true)) return true; for (const subagent of context.subagents.values()) { if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) return true; } @@ -9211,6 +9264,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : false; if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { + // A foreground tool still open at end_turn is stale; left open it would + // hold the deferred finalize until Stop. + if (deferredBackgroundWork) + yield* terminalizeOpenForegroundTools(context, "completed", { + keepOutliving: true, + }); yield* closeTextStreams(context); if (pendingReply) { context.replyOpen = true; @@ -9423,6 +9482,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( new Map(current).set(requestedSessionId, initialNativeMetadata), ); } + const precedingRunTools = yield* Ref.getAndSet(finalizedRunTools, null); const context: ActiveAcpTurn = { input: turnInput, providerTurnId, @@ -9444,6 +9504,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stoppedToolCallIds: new Set(), toolUpdatesSkipped: new Map(), toolStartedAt: new Map(), + precedingRunTools: + isContinuationTurn && precedingRunTools?.sessionId === requestedSessionId + ? precedingRunTools + : null, subagents: new Map(), subagentsBySessionId: new Map(), pendingSubagentNotifications: new Map(),