From 31eba8560e474a655dacb954aba280f994ea93d2 Mon Sep 17 00:00:00 2001 From: Omar <76748259+omar9848492@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:22:58 -0500 Subject: [PATCH] fix(antigravity): keep threads waiting on background tasks and handle reactive wakes When Antigravity (ACP 1.5.10) leaves a background run_command, schedule, run_workflow, or invoke_subagent in_progress at end_turn, AcpAdapterV2 previously force-completed the tool call, left pendingBackgroundTasks empty (marking the thread Completed instead of Waiting), and rejected post-settle session/request_permission calls during Antigravity's spontaneous reactive wake with -32603. Track open Antigravity background tasks across end_turn into pendingBackgroundTasks (non-daemon commands awaited by default; IsDaemon commands non-blocking unless marked via t3_background_wait), wire step-ID resolution for t3_background_wait, keep the session watching for post-settle completions, offer a reactive continuation run on wake, hold post-settle permission requests until the continuation turn attaches, settle reactive wake turns after their trailing usage_update, and clear/quarantine background work on Stop. Done with Antigravity (Gemini 3.1 Pro). --- .../Adapters/AntigravityAdapterV2.test.ts | 630 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 12 + .../provider/acp/AntigravityChildWork.test.ts | 47 ++ .../src/provider/acp/AntigravityChildWork.ts | 56 ++ .../provider/acp/AntigravityProtocol.test.ts | 148 ++++ .../src/provider/acp/AntigravityProtocol.ts | 100 ++- packages/provider-acp/src/server/adapter.ts | 501 +++++++++++++- 7 files changed, 1464 insertions(+), 30 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b281ecc16ab84..e9bfd12ba7ea6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -23,17 +23,27 @@ import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { ChildProcessSpawner } from "effect/process"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as EffectAcpErrors from "effect-acp/errors"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; +import { + CHILD, + invokeStep, + LAUNCH, + makeProfile, + ROOT, +} from "../../provider/acp/AntigravityChildWork.testkit.ts"; import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -1274,3 +1284,623 @@ describe("AntigravityAdapterV2 session system prompt", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 background tasks and reactive wakes", () => { + const makeHarness = Effect.fn("AntigravityAdapterV2.test.makeBackgroundHarness")( + function* (input: { + readonly name: string; + readonly runtimeMode: "full-access" | "approval-required"; + readonly profileDirectory?: string; + readonly onPrompt: (helpers: { + readonly sendUpdate: ( + update: EffectAcpSchema.SessionUpdate, + ) => Effect.Effect; + readonly requestPermission: ( + request: EffectAcpSchema.RequestPermissionRequest, + ) => Effect.Effect; + }) => Effect.Effect; + }) { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let requestPermissionHandler: + | Parameters[0] + | undefined; + let onOutgoingResponse: ((requestId: string) => Effect.Effect) | undefined; + let permissionCounter = 0; + const continuations = + yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make(`antigravity-bg-${input.name}`); + const threadId = ThreadId.make(`thread-antigravity-bg-${input.name}`); + const sendUpdate = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("sessionUpdate handler was not wired") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + const requestPermission = (request: EffectAcpSchema.RequestPermissionRequest) => { + const requestId = `perm-${++permissionCounter}`; + return requestPermissionHandler === undefined + ? Effect.die("requestPermission handler was not wired") + : requestPermissionHandler(request, { + requestId, + method: "session/request_permission", + }).pipe(Effect.tap(() => onOutgoingResponse?.(requestId) ?? Effect.void)); + }; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + ...(input.profileDirectory === undefined + ? {} + : { profileDirectory: input.profileDirectory }), + continuationRequests: { + offer: (request) => Queue.offer(continuations, request).pipe(Effect.asVoid), + }, + makeRuntime: (runtimeInput) => { + onOutgoingResponse = runtimeInput.onOutgoingResponse; + return makeAntigravityAcpRuntime({ + ...runtimeInput, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: runtimeInput.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + handleRequestPermission: (handler) => + Effect.sync(() => { + requestPermissionHandler = handler; + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), + prompt: () => input.onPrompt({ sendUpdate, requestPermission }), + })), + ); + }, + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: input.runtimeMode, + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make(`provider-session-antigravity-bg-${input.name}`), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + createdBy: "user" as const, + creationSource: "web" as const, + id: threadId, + projectId: ProjectId.make(`project-antigravity-bg-${input.name}`), + title: `Antigravity background ${input.name}`, + providerInstanceId: instanceId, + modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: "default" as const, + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const startTurn = (turn: { + readonly ordinal: number; + readonly providerTurnOrdinal: number; + readonly text: string; + readonly continuation?: boolean; + readonly providerThread?: typeof providerThread; + }) => + session.startTurn({ + appThread, + threadId, + runId: RunId.make(`run-antigravity-bg-${input.name}-${turn.ordinal}`), + runOrdinal: turn.ordinal, + providerTurnOrdinal: turn.providerTurnOrdinal, + attemptId: RunAttemptId.make(`attempt-antigravity-bg-${input.name}-${turn.ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-bg-${input.name}-${turn.ordinal}`), + providerThread: turn.providerThread ?? providerThread, + message: { + createdBy: turn.continuation ? "agent" : "user", + creationSource: turn.continuation ? "provider" : "web", + messageId: MessageId.make(`message-antigravity-bg-${input.name}-${turn.ordinal}`), + text: turn.text, + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + return { + session, + providerThread, + continuations, + sendUpdate, + requestPermission, + startTurn, + }; + }, + ); + + it.effect( + "tracks open background commands across end_turn, wakes on completion, handles post-settle permission requests, and settles after usage_update", + () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + name: "reactive-wake", + runtimeMode: "full-access", + onPrompt: ({ sendUpdate }) => + Effect.gen(function* () { + yield* sendUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call_bg_1", + name: "run_command", + kind: "execute", + title: "aside repl --file pull.js", + status: "in_progress", + rawInput: { + CommandLine: "aside repl --file pull.js", + WaitMsBeforeAsync: 500, + }, + }); + yield* sendUpdate({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Started pull; waiting for it to finish." }, + }); + yield* sendUpdate({ + sessionUpdate: "usage_update", + used: 9682, + size: 1_048_576, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + assert.isTrue(harness.session.backgroundTasksEndWithProcess); + yield* harness.startTurn({ ordinal: 1, providerTurnOrdinal: 1, text: "run pull" }); + + const turn1Events = Array.from( + yield* harness.session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + + // Background command must stay running (not force-completed on end_turn). + const bgItemAfterTurn1 = turn1Events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "call_bg_1", + ); + assert.equal(bgItemAfterTurn1?.type, "turn_item.updated"); + if (bgItemAfterTurn1?.type === "turn_item.updated") { + assert.equal(bgItemAfterTurn1.turnItem.status, "running"); + } + + const threadAfterTurn1 = turn1Events.findLast( + (event) => event.type === "provider_thread.updated", + ); + assert.equal(threadAfterTurn1?.type, "provider_thread.updated"); + if (threadAfterTurn1?.type === "provider_thread.updated") { + assert.equal(threadAfterTurn1.pendingBackgroundWork, true); + assert.deepEqual(threadAfterTurn1.providerThread.pendingBackgroundTasks, [ + { + taskId: "call_bg_1", + kind: "command", + awaited: true, + description: "aside repl --file pull.js", + runId: RunId.make("run-antigravity-bg-reactive-wake-1"), + }, + ]); + } + assert.isTrue(yield* harness.session.hasPendingBackgroundWork!); + assert.isTrue( + yield* harness.session.hasPendingBackgroundWorkForThread!(harness.providerThread), + ); + + // Post-settle completion of call_bg_1 updates the Turn 1 row, clears the roster, and offers a continuation. + yield* harness.sendUpdate({ + sessionUpdate: "tool_call_update", + toolCallId: "call_bg_1", + status: "completed", + rawOutput: { + output: "Command exited with code 0.\n\nCommand output:\nPULL_OK\n", + exit_code: 0, + }, + content: [ + { + type: "content", + content: { + type: "text", + text: "Command exited with code 0.\n\nCommand output:\nPULL_OK\n", + }, + }, + ], + }); + + const continuation = yield* Queue.take(harness.continuations); + assert.equal(continuation.driver, "antigravity"); + + // Start the continuation run and collect events until its turn.terminal. + const updatedThread = + threadAfterTurn1?.type === "provider_thread.updated" + ? threadAfterTurn1.providerThread + : harness.providerThread; + yield* harness.startTurn({ + ordinal: 2, + providerTurnOrdinal: 2, + text: "", + continuation: true, + providerThread: updatedThread, + }); + + const wakeEventsFiber = yield* harness.session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + + // Multi-second thinking gap (>3s) must NOT prematurely settle the wake turn. + yield* harness.sendUpdate({ + sessionUpdate: "agent_thought_chunk", + content: { type: "text", text: "Pull finished; running ingest." }, + }); + yield* TestClock.adjust("5 seconds"); + yield* harness.sendUpdate({ + sessionUpdate: "usage_update", + used: 11_000, + size: 1_048_576, + }); + // Tool call arrives immediately after step 1 usage_update and requests permission. + yield* harness.sendUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call_wake_ingest", + name: "run_command", + kind: "execute", + title: "python -m hdads.ingest", + status: "in_progress", + rawInput: { CommandLine: "python -m hdads.ingest", WaitMsBeforeAsync: 5000 }, + }); + const permissionResponse = yield* harness.requestPermission({ + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_wake_ingest", + kind: "execute", + title: "python -m hdads.ingest", + status: "pending", + rawInput: { CommandLine: "python -m hdads.ingest" }, + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + assert.deepEqual(permissionResponse, { + outcome: { outcome: "selected", optionId: "allow" }, + }); + yield* harness.sendUpdate({ + sessionUpdate: "tool_call_update", + toolCallId: "call_wake_ingest", + status: "completed", + rawOutput: { output: "INGEST_OK\n", exit_code: 0 }, + }); + // Post-tool thinking gap (>3s) must ALSO wait for step 2 usage_update. + yield* TestClock.adjust("5 seconds"); + yield* harness.sendUpdate({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Ingest complete." }, + }); + yield* harness.sendUpdate({ + sessionUpdate: "usage_update", + used: 11_200, + size: 1_048_576, + }); + yield* TestClock.adjust("2 seconds"); + + const wakeEvents = Array.from(yield* Fiber.join(wakeEventsFiber)); + const completedBgItem = wakeEvents.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "call_bg_1", + ); + assert.equal(completedBgItem?.type, "turn_item.updated"); + if ( + completedBgItem?.type === "turn_item.updated" && + completedBgItem.turnItem.type === "command_execution" + ) { + assert.equal(completedBgItem.turnItem.status, "completed"); + assert.equal(completedBgItem.turnItem.exitCode, 0); + assert.include(completedBgItem.turnItem.output ?? "", "PULL_OK"); + } + const assistantReply = wakeEvents.findLast( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message", + ); + assert.equal(assistantReply?.type, "turn_item.updated"); + if ( + assistantReply?.type === "turn_item.updated" && + assistantReply.turnItem.type === "assistant_message" + ) { + assert.equal(assistantReply.turnItem.text, "Ingest complete."); + } + const wakeTerminal = wakeEvents.findLast((event) => event.type === "turn.terminal"); + assert.equal(wakeTerminal?.type, "turn.terminal"); + if (wakeTerminal?.type === "turn.terminal") { + assert.equal(wakeTerminal.status, "completed"); + } + assert.isFalse(yield* harness.session.hasPendingBackgroundWork!); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "keeps IsDaemon commands non-blocking by default and supports t3_background_wait by step task ID or toolCallId", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { profile } = yield* makeProfile({ + steps: (logUri) => [ + [ + 50, + 132, + invokeStep({ + callId: "call_daemon_1", + launches: [LAUNCH], + children: [{ id: CHILD, logUri }], + }), + ], + ], + }); + yield* fileSystem.copyFile( + path.join(profile, "antigravity-acp", "conversations", `${ROOT}.db`), + path.join(profile, "antigravity-acp", "conversations", "mock-session-1.db"), + ); + const harness = yield* makeHarness({ + name: "daemon-and-wait", + runtimeMode: "full-access", + profileDirectory: profile, + onPrompt: ({ sendUpdate }) => + Effect.gen(function* () { + yield* sendUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call_daemon_1", + name: "run_command", + kind: "execute", + title: "vp run dev", + status: "in_progress", + rawInput: { CommandLine: "vp run dev", IsDaemon: true, WaitMsBeforeAsync: 500 }, + }); + yield* sendUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call_timer_1", + name: "schedule", + kind: "other", + title: "Run schedule", + status: "in_progress", + rawInput: { DurationSeconds: 30, Prompt: "Check status" }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* harness.startTurn({ ordinal: 1, providerTurnOrdinal: 1, text: "start dev & timer" }); + const events = Array.from( + yield* harness.session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const threadAfter = events.findLast((event) => event.type === "provider_thread.updated"); + assert.equal(threadAfter?.type, "provider_thread.updated"); + if (threadAfter?.type === "provider_thread.updated") { + assert.deepEqual(threadAfter.providerThread.pendingBackgroundTasks, [ + { + taskId: "call_daemon_1", + kind: "command", + description: "vp run dev", + runId: RunId.make("run-antigravity-bg-daemon-and-wait-1"), + }, + { + taskId: "call_timer_1", + kind: "background_task", + description: "Check status", + runId: RunId.make("run-antigravity-bg-daemon-and-wait-1"), + }, + ]); + } + + // t3_background_wait matches the native Antigravity task ID (`/task-50`) and marks awaited. + const markResult = yield* harness.session.awaitBackgroundTasks!({ + providerThread: harness.providerThread, + taskIds: ["mock-session-1/task-50", "unknown-task"], + awaited: true, + }); + assert.deepEqual(markResult, { matched: ["mock-session-1/task-50"] }); + + const afterMark = yield* harness.session.events.pipe( + Stream.filter((event) => event.type === "provider_thread.updated"), + Stream.runHead, + ); + assert.equal(afterMark._tag, "Some"); + if (afterMark._tag === "Some" && afterMark.value.type === "provider_thread.updated") { + assert.equal(afterMark.value.providerThread.pendingBackgroundTasks?.[0]?.awaited, true); + } + + // Unmarking via toolCallId clears `awaited`. + const unmarkResult = yield* harness.session.awaitBackgroundTasks!({ + providerThread: harness.providerThread, + taskIds: ["call_daemon_1"], + awaited: false, + }); + assert.deepEqual(unmarkResult, { matched: ["call_daemon_1"] }); + const afterUnmark = yield* harness.session.events.pipe( + Stream.filter((event) => event.type === "provider_thread.updated"), + Stream.runHead, + ); + assert.equal(afterUnmark._tag, "Some"); + if (afterUnmark._tag === "Some" && afterUnmark.value.type === "provider_thread.updated") { + assert.isUndefined(afterUnmark.value.providerThread.pendingBackgroundTasks?.[0]?.awaited); + } + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "clears pending background tasks and quarantines late wakes when Stop interrupts a Waiting thread", + () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + name: "stop-while-waiting", + runtimeMode: "full-access", + onPrompt: ({ sendUpdate }) => + Effect.gen(function* () { + yield* sendUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call_stop_1", + name: "run_command", + kind: "execute", + title: "sleep 60", + status: "in_progress", + rawInput: { CommandLine: "sleep 60", WaitMsBeforeAsync: 500 }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* harness.startTurn({ ordinal: 1, providerTurnOrdinal: 1, text: "sleep" }); + const turn1Events = Array.from( + yield* harness.session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const turn1Terminal = turn1Events.findLast((event) => event.type === "turn.terminal"); + assert.equal(turn1Terminal?.type, "turn.terminal"); + assert.isTrue(yield* harness.session.hasPendingBackgroundWork!); + + yield* harness.session.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: + turn1Terminal?.type === "turn.terminal" ? turn1Terminal.providerTurnId : ("" as never), + requestRuntimeRestart: true, + }); + + assert.isFalse(yield* harness.session.hasPendingBackgroundWork!); + // A late post-settle completion after Stop must not offer a continuation run. + yield* harness.sendUpdate({ + sessionUpdate: "tool_call_update", + toolCallId: "call_stop_1", + status: "completed", + rawOutput: { output: "LATE\n", exit_code: 0 }, + }); + assert.equal(yield* Queue.size(harness.continuations), 0); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "holds a post-settle permission request until the reactive continuation turn attaches in approval-required mode", + () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + name: "wake-approval", + runtimeMode: "approval-required", + onPrompt: ({ sendUpdate }) => + Effect.gen(function* () { + yield* sendUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call_bg_approval", + name: "run_command", + kind: "execute", + title: "sleep 5", + status: "in_progress", + rawInput: { CommandLine: "sleep 5", WaitMsBeforeAsync: 500 }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* harness.startTurn({ ordinal: 1, providerTurnOrdinal: 1, text: "sleep" }); + yield* harness.session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Agent wakes up and requests permission BEFORE the continuation turn has attached. + const permissionFiber = yield* harness + .requestPermission({ + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_after_wake_ask", + kind: "execute", + title: "echo APPROVED", + status: "pending", + rawInput: { CommandLine: "echo APPROVED" }, + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }) + .pipe(Effect.forkScoped); + + const continuation = yield* Queue.take(harness.continuations); + assert.equal(continuation.driver, "antigravity"); + + const runtimeRequestEventFiber = yield* harness.session.events.pipe( + Stream.filter((event) => event.type === "runtime_request.updated"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + + yield* harness.startTurn({ + ordinal: 2, + providerTurnOrdinal: 2, + text: "", + continuation: true, + }); + + const runtimeRequestEvent = yield* Fiber.join(runtimeRequestEventFiber); + assert.equal(runtimeRequestEvent._tag, "Some"); + if ( + runtimeRequestEvent._tag === "Some" && + runtimeRequestEvent.value.type === "runtime_request.updated" + ) { + yield* harness.session.respondToRuntimeRequest({ + requestId: runtimeRequestEvent.value.runtimeRequest.id, + decision: "accept", + }); + } + + const outcome = yield* Fiber.join(permissionFiber); + assert.deepEqual(outcome, { + outcome: { outcome: "selected", optionId: "allow" }, + }); + }).pipe(Effect.provide(layerSession)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b6f746269a6f2..3da3436220fc3 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -31,6 +31,7 @@ import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, describeAntigravitySubagentLaunches, + resolveAntigravityStepToolCallId, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; @@ -38,6 +39,7 @@ import { antigravityApprovalOptions, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, + extractAntigravityBackgroundWorkTask, extractAntigravityUserInputQuestion, makeAntigravityReadRepair, makeAntigravityUserInputResponse, @@ -272,6 +274,16 @@ export function makeAntigravityAcpAdapterFlavor( }, normalizeToolCall: normalizeAntigravityToolCall, extractSubagentUpdate: extractAntigravitySubagentUpdate, + extractBackgroundWorkTask: extractAntigravityBackgroundWorkTask, + ...(profileDirectory === undefined + ? {} + : { + resolveBackgroundTaskId: ({ sessionId, taskId }) => + resolveAntigravityStepToolCallId({ profileDirectory, sessionId, taskId }), + }), + backgroundTasksEndWithProcess: true, + enablePostSettleContinuation: true, + reactiveBackgroundWakes: true, supportsImagePrompts: true, // ACP 1.3.0 treats /compact as ordinary model input. supportsCompaction: false, diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index 78927b09d74e3..ada25432caa23 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -12,6 +12,7 @@ import { antigravitySubagentLaunches, describeAntigravitySubagentLaunches, readAntigravityChildWork, + resolveAntigravityStepToolCallId, } from "./AntigravityChildWork.ts"; import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts"; import { @@ -341,4 +342,50 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { expect(JSON.stringify(children).length).toBeLessThan(600 * 1024); }), ); + + it.effect("resolves background task step IDs to their ACP toolCallId", () => + Effect.gen(function* () { + const { profile } = yield* makeProfile({ + steps: (logUri) => [ + [ + 50, + 132, + invokeStep({ + callId: "call_10484616887436816983", + launches: [LAUNCH], + children: [{ id: CHILD, logUri }], + }), + ], + ], + }); + expect( + yield* resolveAntigravityStepToolCallId({ + profileDirectory: profile, + sessionId: ROOT, + taskId: `${ROOT}/task-50`, + }), + ).toBe("call_10484616887436816983"); + expect( + yield* resolveAntigravityStepToolCallId({ + profileDirectory: profile, + sessionId: ROOT, + taskId: "task-50", + }), + ).toBe("call_10484616887436816983"); + expect( + yield* resolveAntigravityStepToolCallId({ + profileDirectory: profile, + sessionId: ROOT, + taskId: "other-session/task-50", + }), + ).toBeUndefined(); + expect( + yield* resolveAntigravityStepToolCallId({ + profileDirectory: profile, + sessionId: ROOT, + taskId: `${ROOT}/task-999`, + }), + ).toBeUndefined(); + }), + ); }); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index ea12e0e2b20de..a33cf14747e88 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -417,6 +417,62 @@ class AntigravityChildWorkReadError extends Schema.TaggedError + text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1), +); + +const ANTIGRAVITY_BACKGROUND_TASK_ID = /^(?:([A-Za-z0-9-]{1,64})\/)?task-(\d+)$/; + +/** + * Resolves an Antigravity background task ID (`/task-` or `task-`) + * to the ACP `toolCallId` stored on that step in the session's own unlinked SQLite log. + */ +export const resolveAntigravityStepToolCallId = Effect.fn("resolveAntigravityStepToolCallId")( + function* (input: { + readonly profileDirectory: string; + readonly sessionId: string; + readonly taskId: string; + }): Effect.fn.Return { + if (!NATIVE_ID.test(input.sessionId)) return undefined; + const match = ANTIGRAVITY_BACKGROUND_TASK_ID.exec(input.taskId.trim()); + if (match === null) return undefined; + const [, prefixSessionId, stepIndexText] = match; + if (prefixSessionId !== undefined && prefixSessionId !== input.sessionId) return undefined; + const stepIndex = Number(stepIndexText); + if (!Number.isSafeInteger(stepIndex) || stepIndex < 0) return undefined; + return yield* Effect.tryPromise({ + try: async (): Promise => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + const databasePath = + profileRoot === undefined + ? undefined + : ( + await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "conversations", `${input.sessionId}.db`], + "file", + ) + )?.path; + if (profileRoot === undefined || databasePath === undefined) return undefined; + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const row = database + .prepare( + "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?", + ) + .get(stepIndex, MAX_STEP_BYTES); + const payload = payloadOf(row); + return payload === undefined ? undefined : decodeStepToolCallId(payload); + } finally { + database.close(); + } + }, + catch: () => undefined, + }).pipe(Effect.orElseSucceed(() => undefined)); + }, +); + /** Children a subagent tool call launched, proven by the parent's own session record. */ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: { readonly profileDirectory: string; diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index a2d7c86f4c2d3..45f0ab8a408cb 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -4,6 +4,7 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import * as AcpWireSchema from "effect-acp/schema-v1"; import { + extractAntigravityBackgroundWorkTask, extractAntigravityUserInputQuestion, antigravityApprovalOptions, antigravitySubagentOutput, @@ -623,3 +624,150 @@ describe("Antigravity served reads", () => { }); }); }); + +describe("Antigravity background work classification", () => { + it("classifies awaited commands, daemons, schedules, workflows, and async subagents", () => { + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_cmd", + kind: "execute", + title: "sleep 5", + command: "sleep 5", + status: "inProgress", + data: { name: "run_command", rawInput: { CommandLine: "sleep 5", WaitMsBeforeAsync: 500 } }, + }), + ).toEqual({ + taskId: "call_cmd", + kind: "command", + awaited: true, + description: "sleep 5", + }); + + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_daemon", + kind: "execute", + title: "vp run dev", + command: "vp run dev", + status: "inProgress", + data: { + name: "run_command", + rawInput: { CommandLine: "vp run dev", IsDaemon: true, WaitMsBeforeAsync: 500 }, + }, + }), + ).toEqual({ + taskId: "call_daemon", + kind: "command", + description: "vp run dev", + }); + + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_timer", + kind: "other", + title: "Run schedule", + status: "inProgress", + data: { name: "schedule", rawInput: { DurationSeconds: 10, Prompt: "Check build" } }, + }), + ).toEqual({ + taskId: "call_timer", + kind: "background_task", + description: "Check build", + }); + + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_cron_daemon", + kind: "other", + title: "Run schedule", + status: "inProgress", + data: { + name: "schedule", + rawInput: { CronExpression: "*/5 * * * *", IsDaemon: true }, + }, + }), + ).toEqual({ + taskId: "call_cron_daemon", + kind: "monitor", + description: "Schedule (*/5 * * * *)", + }); + + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_workflow", + kind: "other", + title: "Run run_workflow", + status: "inProgress", + data: { name: "run_workflow", rawInput: { Description: "Fan out audit" } }, + }), + ).toEqual({ + taskId: "call_workflow", + kind: "background_task", + description: "Fan out audit", + }); + + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_subagent_v15", + kind: "other", + title: "Run invoke_subagent", + status: "inProgress", + data: { name: "invoke_subagent", rawInput: { Role: "Codebase Researcher" } }, + }), + ).toEqual({ + taskId: "call_subagent_v15", + kind: "subagent", + description: "Codebase Researcher", + }); + + // Legacy subagent titles stay owned by extractSubagentUpdate; MCP and ordinary reads are ignored. + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_legacy_subagent", + kind: "other", + title: "Running invoke_subagent", + status: "inProgress", + data: { name: "invoke_subagent" }, + }), + ).toBeUndefined(); + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_mcp", + kind: "execute", + title: "run_command", + status: "inProgress", + data: { name: "run_command", meta: { is_mcp_tool_call: true } }, + }), + ).toBeUndefined(); + expect( + extractAntigravityBackgroundWorkTask({ + toolCallId: "call_read", + kind: "read", + title: "Read file", + status: "inProgress", + data: { name: "read_file" }, + }), + ).toBeUndefined(); + }); + + it("extracts rawOutput.output into command aggregatedOutput", () => { + const normalized = normalizeAntigravityToolCall({ + toolCallId: "call_out", + kind: "execute", + title: "sleep 5 && echo DONE", + status: "completed", + data: { + rawInput: { CommandLine: "sleep 5 && echo DONE" }, + rawOutput: { + output: "Command exited with code 0.\n\nCommand output:\nDONE\n", + exit_code: 0, + }, + }, + }); + expect(normalized.data.item).toEqual({ + command: "sleep 5 && echo DONE", + aggregatedOutput: "Command exited with code 0.\n\nCommand output:\nDONE\n", + exitCode: 0, + }); + }); +}); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 5b74756a1de11..ef70508712946 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as AcpWireSchema from "effect-acp/schema-v1"; +import type { AcpBackgroundWorkTask } from "@t3tools/provider-acp/server/adapter"; import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; import { @@ -35,6 +36,7 @@ const NativeToolFields = Schema.Struct({ workingDir: Schema.optional(Schema.String), combinedOutput: Schema.optional(Schema.String), combined_output: Schema.optional(Schema.String), + output: Schema.optional(Schema.String), exitCode: Schema.optional(Schema.Int), exit_code: Schema.optional(Schema.Int), imagePath: Schema.optional(Schema.String), @@ -435,7 +437,7 @@ export function normalizeAntigravityToolCall( output?.workingDir ?? output?.working_dir; const cwd = nativeCwd?.trim() ? boundText(nativeCwd.trim()) : undefined; - const nativeOutput = output?.combinedOutput ?? output?.combined_output; + const nativeOutput = output?.combinedOutput ?? output?.combined_output ?? output?.output; const aggregatedOutput = nativeOutput === undefined ? undefined : boundText(nativeOutput); const exitCode = output?.exitCode ?? output?.exit_code; const imagePath = localImagePath(output?.imagePath); @@ -507,3 +509,99 @@ export function antigravitySubagentOutput(toolCall: AcpToolCallState): string | const output = toolCall.data.rawOutput; return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined; } + +const ANTIGRAVITY_BACKGROUND_DESCRIPTION_LIMIT = 240; + +function antigravityBackgroundDescription(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + if (trimmed.length === 0) return undefined; + return trimmed.length > ANTIGRAVITY_BACKGROUND_DESCRIPTION_LIMIT + ? copyBoundedText(`${trimmed.slice(0, ANTIGRAVITY_BACKGROUND_DESCRIPTION_LIMIT - 3)}...`) + : trimmed; +} + +function isAntigravityDaemonInput(rawInput: unknown): boolean { + return ( + Predicate.isObject(rawInput) && + (rawInput.IsDaemon === true || rawInput.isDaemon === true || rawInput.is_daemon === true) + ); +} + +/** + * Antigravity keeps background commands, timers, workflows, and async subagents `in_progress` + * across `session/prompt` return and completes them later before waking the agent reactively. + * Daemon processes (`IsDaemon: true`) stay tracked without holding thread completion. + */ +export function extractAntigravityBackgroundWorkTask( + toolCall: AcpToolCallState, +): AcpBackgroundWorkTask | undefined { + const meta = toolCall.data.meta; + if (Predicate.isObject(meta) && meta.is_mcp_tool_call === true) return undefined; + const toolName = typeof toolCall.data.name === "string" ? toolCall.data.name.trim() : undefined; + const rawInput = Predicate.isObject(toolCall.data.rawInput) ? toolCall.data.rawInput : undefined; + const isDaemon = isAntigravityDaemonInput(rawInput); + + if (toolName === "run_command" || toolCall.kind === "execute") { + const description = + antigravityBackgroundDescription(toolCall.command) ?? + antigravityBackgroundDescription(rawInput?.toolSummary) ?? + antigravityBackgroundDescription(toolCall.title); + return { + taskId: toolCall.toolCallId, + kind: "command", + ...(!isDaemon ? { awaited: true } : {}), + ...(description === undefined ? {} : { description }), + }; + } + + if ( + toolName === "schedule" || + toolCall.title === "Run schedule" || + toolCall.title === "Running schedule" + ) { + const description = + antigravityBackgroundDescription(rawInput?.Prompt) ?? + (typeof rawInput?.DurationSeconds === "number" + ? `Timer (${rawInput.DurationSeconds}s)` + : typeof rawInput?.CronExpression === "string" + ? antigravityBackgroundDescription(`Schedule (${rawInput.CronExpression})`) + : antigravityBackgroundDescription(toolCall.title)); + return { + taskId: toolCall.toolCallId, + kind: isDaemon ? "monitor" : "background_task", + ...(description === undefined ? {} : { description }), + }; + } + + if ( + toolName === "run_workflow" || + toolCall.title === "Run run_workflow" || + toolCall.title === "Running run_workflow" + ) { + const description = + antigravityBackgroundDescription(rawInput?.Description) ?? + antigravityBackgroundDescription(toolCall.title); + return { + taskId: toolCall.toolCallId, + kind: "background_task", + ...(description === undefined ? {} : { description }), + }; + } + + if ( + (toolName === "invoke_subagent" || toolCall.title === "Run invoke_subagent") && + classifyAntigravitySubagentToolCall(toolCall) === undefined + ) { + const description = + antigravityBackgroundDescription(rawInput?.Role) ?? + antigravityBackgroundDescription(toolCall.title); + return { + taskId: toolCall.toolCallId, + kind: "subagent", + ...(description === undefined ? {} : { description }), + }; + } + + return undefined; +} diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 7abc540793aff..3acb91e817614 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -5,6 +5,7 @@ import { type ModelSelection, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2PlanArtifact, type OrchestrationV2PlanStep, type OrchestrationV2ProviderCapabilities, @@ -27,6 +28,7 @@ import { type ProviderRequestKind, type ProviderThreadId, type ProviderUserInputAnswers, + type RunId, type RuntimeMode, type RuntimeRequestId, type ThreadTokenUsageSnapshot, @@ -38,6 +40,7 @@ import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope"; import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime"; +import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation"; import { compactDynamicToolOutput, @@ -143,6 +146,9 @@ export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const; // Grok summaries can trail hydrated tools by over two seconds; shorter waits split the wake. const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis"; +// Antigravity emits usage_update at the end of each LLM step, 1-5ms before any tool_call. +const ACP_REACTIVE_WAKE_FINALIZE_DEBOUNCE: Duration.Input = "1500 millis"; +const ACP_REACTIVE_WAKE_NO_RESPONSE_TIMEOUT: Duration.Input = "90 seconds"; const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -558,6 +564,18 @@ export interface AcpAdapterV2Flavor { readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined; readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined; + /** Classifies background-capable tools that stay open across `session/prompt` return. */ + readonly extractBackgroundWorkTask?: ( + toolCall: AcpToolCallState, + ) => AcpBackgroundWorkTask | undefined; + /** Maps provider-native background task IDs (e.g. `/task-50`) to tracked toolCallIds. */ + readonly resolveBackgroundTaskId?: (input: { + readonly sessionId: string; + readonly taskId: string; + readonly runningTaskIds: ReadonlyArray; + }) => Effect.Effect; + /** All session background tasks and open tool calls end when the ACP process exits. */ + readonly backgroundTasksEndWithProcess?: true; /** Distinguishes commands from monitors when lifecycle notifications omit their kind. */ readonly isBackgroundCommandTool?: (toolCall: AcpToolCallState) => boolean; readonly extractBackgroundToolMutation?: (text: string) => ReadonlyArray<{ @@ -581,6 +599,12 @@ export interface AcpAdapterV2Flavor { notification: EffectAcpSchema.SessionNotification, ) => boolean; readonly deferFinalizeForBackgroundWork?: boolean; + /** + * Reactive-wake ACP v1 agents (Antigravity) keep background tools `in_progress` across + * `session/prompt` return, then stream spontaneous wake turns (including permission requests) + * without a second `session/prompt` RPC, ending each LLM step with `usage_update`. + */ + readonly reactiveBackgroundWakes?: true; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -667,6 +691,13 @@ export type AcpSubagentSessionEvent = readonly prompt: string; }; +export interface AcpBackgroundWorkTask { + readonly taskId: string; + readonly kind: OrchestrationV2PendingBackgroundTask["kind"]; + readonly awaited?: boolean; + readonly description?: string; +} + export interface AcpAdapterV2SubagentUpdate { readonly nativeTaskId: string; readonly prompt: string; @@ -1534,6 +1565,9 @@ interface ActiveAcpTurn { readonly promptStarted: Deferred.Deferred; promptUsage: EffectAcpSchema.Usage | undefined; backgroundFinalizeGeneration: number; + reactiveWake: boolean; + reactiveWakeSawActivity: boolean; + reactiveWakeFinalizeGeneration: number; /** The agent's own id for this turn's prompt, from `forkFromTurn.nativeTurnId`. */ nativePromptId: string | undefined; /** Clock millis of the prompt's last progress, for `promptInactivityTimeout`. */ @@ -1682,13 +1716,17 @@ function acpPostSettleMonitorPromptShouldSuppress( export function acpCompletedTurnShouldTerminalizeTool( tool: AcpToolCallState & { readonly backgroundCommandTaskId?: string }, - flavor: Pick, + flavor: Pick< + AcpAdapterV2Flavor, + "extractBackgroundTaskId" | "extractBackgroundWorkTask" | "extractSubagentUpdate" + >, ): boolean { const status = toolStatus(tool.status); if (status !== "pending" && status !== "running") return false; // Progress output replaces the start ACK, so the registered task id outlives it. if (tool.backgroundCommandTaskId !== undefined) return false; if (flavor.extractBackgroundTaskId?.(tool) !== undefined) return false; + if (flavor.extractBackgroundWorkTask?.(tool) !== undefined) return false; return flavor.extractSubagentUpdate?.(tool) === undefined; } @@ -1844,6 +1882,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const continuationRequests = options.continuationRequests; const postSettleContinuationEnabled = flavor.enablePostSettleContinuation === true && continuationRequests !== undefined; + const reactiveBackgroundWakes = + flavor.reactiveBackgroundWakes === true && postSettleContinuationEnabled; const readCapabilities = Effect.gen(function* () { if (flavor.supportsNativeGoals === undefined) return flavor.capabilities; @@ -2405,6 +2445,62 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // Grok re-prompts on stale monitor notices; suppress output until a genuine terminal or app turn. const suppressPostSettleMonitorPrompt = yield* Ref.make(false); const runningBackgroundTaskIds = yield* Ref.make>(new Set()); + type TrackedAcpBackgroundTask = { + readonly taskId: string; + readonly toolCallId: string; + readonly kind: OrchestrationV2PendingBackgroundTask["kind"]; + readonly awaited: boolean; + readonly description: string | undefined; + readonly runId: RunId; + }; + const trackedBackgroundTasks = yield* Ref.make< + ReadonlyMap + >(new Map()); + const currentPendingBackgroundTasks = Ref.get(trackedBackgroundTasks).pipe( + Effect.map((tasks): ReadonlyArray => + [...tasks.values()].map((task) => ({ + taskId: task.taskId, + kind: task.kind, + ...(task.awaited ? { awaited: true as const } : {}), + ...(task.description === undefined ? {} : { description: task.description }), + runId: task.runId, + })), + ), + ); + const withTrackedPendingBackgroundTasks = ( + providerThread: OrchestrationV2ProviderThread, + ): Effect.Effect => + flavor.extractBackgroundWorkTask === undefined + ? Effect.succeed(providerThread) + : currentPendingBackgroundTasks.pipe( + Effect.map((pendingBackgroundTasks) => ({ + ...providerThread, + pendingBackgroundTasks: [...pendingBackgroundTasks], + })), + ); + const emitBackgroundRosterUpdate = Effect.fnUntraced(function* (sessionId: string) { + if (flavor.extractBackgroundWorkTask === undefined) return; + const knownProviderThread = (yield* Ref.get(providerThreadByNativeSessionId)).get( + sessionId, + ); + if (knownProviderThread === undefined) return; + const now = yield* DateTime.now; + const pendingBackgroundTasks = yield* currentPendingBackgroundTasks; + const updatedProviderThread: OrchestrationV2ProviderThread = { + ...knownProviderThread, + pendingBackgroundTasks: [...pendingBackgroundTasks], + updatedAt: now, + }; + yield* Ref.update(providerThreadByNativeSessionId, (current) => + new Map(current).set(sessionId, updatedProviderThread), + ); + yield* emitProviderEvent({ + type: "provider_thread.updated", + driver, + providerThread: updatedProviderThread, + pendingBackgroundWork: pendingBackgroundTasks.length > 0, + }); + }); // Background command task id → the completed turn that owns its row. Ended commands stay, // bounded, so a later authoritative terminal still corrects the row on its run. const detachedBackgroundCommands = yield* Ref.make>( @@ -2496,6 +2592,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Queue.offer(events, event).pipe(Effect.asVoid); let scheduleDeferredFinalize: (context: ActiveAcpTurn) => Effect.Effect = () => Effect.void; + let scheduleReactiveWakeFinalize: (context: ActiveAcpTurn) => Effect.Effect = () => + Effect.void; const nativeLogging = options.nativeLogging?.(input.threadId); const promptInactivityTimeoutMillis = @@ -2537,6 +2635,33 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeGeneration, Effect.gen(function* () { yield* Ref.set(runtimeRestartRequired, true); + if (flavor.extractBackgroundWorkTask !== undefined) { + const hadTracked = (yield* Ref.get(trackedBackgroundTasks)).size > 0; + yield* Ref.set(trackedBackgroundTasks, new Map()); + yield* Ref.set(runningBackgroundTaskIds, new Set()); + if (hadTracked) { + const rootSessionId = yield* Ref.get(activeSessionId); + if (rootSessionId !== null) { + yield* emitBackgroundRosterUpdate(rootSessionId); + } + } + } + if (reactiveBackgroundWakes) { + yield* Ref.set(wakeBuffer, []); + yield* Ref.set(continuationRequested, false); + yield* cancelPendingRuntimeRequests(); + const context = yield* Ref.get(activeTurn); + if (context !== null && context.reactiveWake && !context.finalized) { + if (!context.interrupted) { + yield* terminalizeOpenForegroundTools(context, "failed"); + } + yield* finalizeTurn( + context, + "failed", + makeProviderFailure({ class: "transport_error" }), + ); + } + } if (!followsAgentWorkState) return; agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" }; for (const child of nativeChildren.values()) { @@ -4116,8 +4241,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const previous = context.tools.get(incoming.toolCallId); const merged = mergeToolCallState(previous, incoming); const normalized = flavor.normalizeToolCall?.(merged) ?? merged; - const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized); + const backgroundWorkTask = flavor.extractBackgroundWorkTask?.(normalized); + const backgroundTaskId = + flavor.extractBackgroundTaskId?.(normalized) ?? backgroundWorkTask?.taskId; const backgroundCommandTaskId = + backgroundWorkTask !== undefined || flavor.isBackgroundCommandTool?.(normalized) === true ? backgroundTaskId : previous?.backgroundCommandTaskId; @@ -4161,15 +4289,40 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.persistentBackgroundTaskIds.add(backgroundTaskId); } const backgroundStatus = projectedStatus ?? toolStatus(toolCall.status); - yield* setBackgroundTaskRunning( - backgroundTaskId, - backgroundStatus === "pending" || backgroundStatus === "running", - ); - if ( - !context.promptSettled && - backgroundStatus !== "pending" && - backgroundStatus !== "running" - ) { + const taskIsActive = backgroundStatus === "pending" || backgroundStatus === "running"; + yield* setBackgroundTaskRunning(backgroundTaskId, taskIsActive); + if (backgroundWorkTask !== undefined) { + const rosterChanged = yield* Ref.modify(trackedBackgroundTasks, (current) => { + const existing = current.get(backgroundWorkTask.taskId); + if (taskIsActive) { + const nextTask: TrackedAcpBackgroundTask = { + taskId: backgroundWorkTask.taskId, + toolCallId: toolCall.toolCallId, + kind: backgroundWorkTask.kind, + awaited: existing?.awaited ?? backgroundWorkTask.awaited === true, + description: backgroundWorkTask.description ?? existing?.description, + runId: existing?.runId ?? context.input.runId, + }; + if ( + existing !== undefined && + existing.kind === nextTask.kind && + existing.awaited === nextTask.awaited && + existing.description === nextTask.description + ) { + return [false, current] as const; + } + return [true, new Map(current).set(backgroundWorkTask.taskId, nextTask)] as const; + } + if (existing === undefined) return [false, current] as const; + const next = new Map(current); + next.delete(backgroundWorkTask.taskId); + return [true, next] as const; + }); + if (rosterChanged && context.finalized) { + yield* emitBackgroundRosterUpdate(context.nativeThreadId); + } + } + if (!context.promptSettled && !taskIsActive) { yield* Ref.update(handledBackgroundTaskIdsInActiveTurn, (current) => new Set(current).add(backgroundTaskId), ); @@ -5019,9 +5172,40 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (turn) => turn.tools.get(update.toolCallId)?.backgroundCommandTaskId !== undefined, ); if (owner === undefined) return false; + const detachedTaskId = owner.tools.get(update.toolCallId)?.backgroundCommandTaskId; + const previousTask = + detachedTaskId === undefined + ? undefined + : (yield* Ref.get(trackedBackgroundTasks)).get(detachedTaskId); for (const event of parseSessionUpdateEvent(notification).events) { if (event._tag === "ToolCallUpdated") yield* emitTool(owner, event.toolCall); } + if ( + reactiveBackgroundWakes && + active === null && + !(yield* Ref.get(stoppedRunQuarantine)) && + previousTask !== undefined && + backgroundWorkHoldsCompletion([ + { + kind: previousTask.kind, + ...(previousTask.awaited ? { awaited: true as const } : {}), + }, + ]) + ) { + const updatedTool = owner.tools.get(update.toolCallId); + const updatedStatus = + updatedTool === undefined ? undefined : toolStatus(updatedTool.status); + if (updatedStatus === "completed" || updatedStatus === "failed") { + yield* recordWakeReport(previousTask.taskId, { + kind: previousTask.kind, + ...(previousTask.description === undefined + ? {} + : { label: previousTask.description }), + outcome: updatedStatus, + }); + yield* offerContinuationRun(notification.sessionId); + } + } return true; }); @@ -5057,6 +5241,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stopProcessing: false, }; } + if (reactiveBackgroundWakes) { + yield* Ref.update(wakeBuffer, (current) => [...current, notification]); + return { + buffered: true, + offerContinuation: true, + stopProcessing: true, + }; + } const update = notification.update; let alreadyHandledToolUpdate = false; if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") { @@ -5260,7 +5452,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const awaitRequestTurn = Effect.fnUntraced(function* (generation: number) { - if (!followsAgentWorkState) return true; + if (!followsAgentWorkState && !reactiveBackgroundWakes) return true; while (true) { const waiting = yield* runRuntimeCallbackAtGeneration( generation, @@ -5353,7 +5545,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); if (knownProviderThread !== undefined) { const now = yield* DateTime.now; - const providerThread: OrchestrationV2ProviderThread = { + const providerThread = yield* withTrackedPendingBackgroundTasks({ ...knownProviderThread, contextUsage: (yield* Ref.get(contextUsageBySessionId)).get(notification.sessionId) ?? @@ -5364,7 +5556,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( knownProviderThread.nativeMetadata ?? null, updatedAt: now, - }; + }); yield* Ref.update(providerThreadByNativeSessionId, (current) => new Map(current).set(notification.sessionId, providerThread), ); @@ -5372,8 +5564,32 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( type: "provider_thread.updated", driver, providerThread, + ...(flavor.extractBackgroundWorkTask === undefined + ? {} + : { + pendingBackgroundWork: + (providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + }), }); } + if (reactiveBackgroundWakes && update.sessionUpdate === "usage_update") { + if ( + context === null && + !(yield* Ref.get(stoppedRunQuarantine)) && + notification.sessionId === (yield* Ref.get(activeSessionId)) && + ((yield* Ref.get(continuationRequested)) || (yield* Ref.get(wakeBuffer)).length > 0) + ) { + yield* Ref.update(wakeBuffer, (current) => [...current, notification]); + } else if ( + context !== null && + context.reactiveWake && + !context.finalized && + notification.sessionId === context.nativeThreadId + ) { + context.reactiveWakeSawActivity = true; + yield* scheduleReactiveWakeFinalize(context); + } + } return; } if (yield* followNativeChild(notification, context)) return; @@ -5666,6 +5882,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } // The activeSessionId yield may let idle/prompt settlement finalize this context. if (context.finalized) return; + if ( + context.reactiveWake && + (update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" || + update.sessionUpdate === "agent_message" || + update.sessionUpdate === "agent_thought" || + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_content_chunk" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "plan_update" || + update.sessionUpdate === "plan_removed" || + (update.sessionUpdate === "tool_call_update" && + (update.status === "pending" || update.status === "in_progress"))) + ) { + context.reactiveWakeSawActivity = true; + context.reactiveWakeFinalizeGeneration += 1; + } if ( context.promptSettled && !acpIsProviderContinuationMessage(context.input.message) && @@ -6903,16 +7136,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest = params, ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); - if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") { + if ( + (followsAgentWorkState || reactiveBackgroundWakes) && + dispositionFor(latestRuntimePolicy) === "ask" + ) { if (!(yield* awaitRequestTurn(handlerGeneration))) return { outcome: { outcome: "cancelled" } } as const; } const admitted = yield* runRuntimeCallbackAtGeneration( handlerGeneration, Effect.gen(function* () { - const context = followsAgentWorkState - ? yield* Ref.get(activeTurn) - : yield* activeContext; + const context = + followsAgentWorkState || reactiveBackgroundWakes + ? yield* Ref.get(activeTurn) + : yield* activeContext; + if (context?.reactiveWake) { + context.reactiveWakeSawActivity = true; + context.reactiveWakeFinalizeGeneration += 1; + } // Kiro sends the tool's kind on its `tool_call` and leaves it // off the permission request for that call; take it from the // tool already seen under the same id so policy can tell a @@ -8038,6 +8279,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(wakeReports, noWakeReports); yield* Ref.set(continuationRequested, false); yield* Ref.set(runningBackgroundTaskIds, new Set()); + const hadTracked = (yield* Ref.get(trackedBackgroundTasks)).size > 0; + yield* Ref.set(trackedBackgroundTasks, new Map()); + if (hadTracked) { + const rootSessionId = yield* Ref.get(activeSessionId); + if (rootSessionId !== null) { + yield* emitBackgroundRosterUpdate(rootSessionId); + } + } yield* Ref.set(detachedBackgroundCommands, new Map()); yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); yield* Ref.set(carryoverSubagents, null); @@ -8056,6 +8305,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const settledStatus = context.interrupted ? "interrupted" : status; context.finalizedStatus = settledStatus; context.finalized = true; + context.reactiveWakeFinalizeGeneration += 1; const watchdog = context.inactivityWatchdog; context.inactivityWatchdog = undefined; if (watchdog !== undefined) { @@ -8149,7 +8399,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: context.input.threadId, providerTurn: turn, }); - const updatedProviderThread: OrchestrationV2ProviderThread = { + const updatedProviderThread = yield* withTrackedPendingBackgroundTasks({ ...context.input.providerThread, providerSessionId: input.providerSessionId, status: "active", @@ -8159,7 +8409,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( contextUsage: context.contextUsage, nativeMetadata: context.nativeMetadata, updatedAt: now, - }; + }); yield* Ref.update(providerThreadByNativeSessionId, (current) => new Map(current).set(context.nativeThreadId, updatedProviderThread), ); @@ -8167,6 +8417,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( type: "provider_thread.updated", driver, providerThread: updatedProviderThread, + ...(flavor.extractBackgroundWorkTask === undefined + ? {} + : { + pendingBackgroundWork: + (updatedProviderThread.pendingBackgroundTasks?.length ?? 0) > 0, + }), }); const rootSessionId = yield* Ref.get(activeSessionId); const childTurnsContinue = @@ -8231,9 +8487,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( postSettleContinuationEnabled && settledStatus === "completed" && !directStopQuarantine && - (yield* Ref.get(runningBackgroundTaskIds)).size === 0 && + (reactiveBackgroundWakes || (yield* Ref.get(runningBackgroundTaskIds)).size === 0) && (yield* Ref.get(wakeBuffer)).some((notification) => - acpPostSettleContinuationOfferEvidence(notification, flavor), + reactiveBackgroundWakes + ? acpPostSettleWakeEvidence(notification, flavor) + : acpPostSettleContinuationOfferEvidence(notification, flavor), ) ) { const sessionId = yield* Ref.get(activeSessionId); @@ -8247,6 +8505,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Deferred.succeed(context.completed, undefined).pipe(Effect.ignore); }); + scheduleReactiveWakeFinalize = Effect.fn("scheduleReactiveWakeFinalize")( + function* (context) { + if (!reactiveBackgroundWakes) return; + if (!context.reactiveWake || context.finalized || context.interrupted) return; + context.reactiveWakeFinalizeGeneration += 1; + const generation = context.reactiveWakeFinalizeGeneration; + const callbackGeneration = yield* Ref.get(runtimeCallbackGeneration); + yield* Effect.gen(function* () { + yield* Effect.sleep(ACP_REACTIVE_WAKE_FINALIZE_DEBOUNCE); + yield* runRuntimeCallbackAtGeneration( + callbackGeneration, + Effect.gen(function* () { + if ( + context.finalized || + context.interrupted || + context.reactiveWakeFinalizeGeneration !== generation + ) { + return; + } + if ( + openAgentRequests.size > 0 || + (yield* Ref.get(pendingRuntimeRequests)).size > 0 + ) { + return; + } + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + }), + ).pipe(Effect.asVoid); + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) { if (!flavor.deferFinalizeForBackgroundWork) return; if (!context.promptSettled || context.finalized || context.interrupted) return; @@ -8706,6 +8996,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( promptStarted, promptUsage: undefined, backgroundFinalizeGeneration: 0, + reactiveWake: false, + reactiveWakeSawActivity: false, + reactiveWakeFinalizeGeneration: 0, nativePromptId: undefined, lastProgressAt: 0, inactivityWatchdog: undefined, @@ -8738,14 +9031,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: turnInput.threadId, providerTurn: runningTurn, }); - const activeProviderThread: OrchestrationV2ProviderThread = { + const activeProviderThread = yield* withTrackedPendingBackgroundTasks({ ...turnInput.providerThread, providerSessionId: input.providerSessionId, status: "active", contextUsage: context.contextUsage, nativeMetadata: context.nativeMetadata, updatedAt: startedAt, - }; + }); yield* Ref.update(providerThreadByNativeSessionId, (current) => new Map(current).set(requestedSessionId, activeProviderThread), ); @@ -8753,6 +9046,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( type: "provider_thread.updated", driver, providerThread: activeProviderThread, + ...(flavor.extractBackgroundWorkTask === undefined + ? {} + : { + pendingBackgroundWork: + (activeProviderThread.pendingBackgroundTasks?.length ?? 0) > 0, + }), }); yield* rememberSnapshotMessage({ createdBy: turnInput.message.createdBy, @@ -8776,6 +9075,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); if (followsAgentWorkState) yield* runtimeCallbackPermit.withPermit(syncNativeChildren(context)); + if (isContinuationTurn && reactiveBackgroundWakes) { + context.reactiveWake = true; + context.promptSettled = true; + context.promptSettledStatus = "completed"; + } const attached = turnAttached; turnAttached = yield* Deferred.make(); yield* Deferred.succeed(attached, true); @@ -8811,6 +9115,45 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); return; } + if (reactiveBackgroundWakes) { + context.reactiveWake = true; + context.promptSettled = true; + context.promptSettledStatus = "completed"; + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + yield* Effect.forEach(yield* takeWakeBuffer, handleSessionUpdate, { + concurrency: 1, + discard: true, + }); + }), + ); + if (!context.finalized && !context.reactiveWakeSawActivity) { + const callbackGeneration = yield* Ref.get(runtimeCallbackGeneration); + yield* Effect.gen(function* () { + yield* Effect.sleep(ACP_REACTIVE_WAKE_NO_RESPONSE_TIMEOUT); + yield* runRuntimeCallbackAtGeneration( + callbackGeneration, + Effect.gen(function* () { + if ( + context.finalized || + context.interrupted || + context.reactiveWakeSawActivity + ) { + return; + } + if ( + openAgentRequests.size > 0 || + (yield* Ref.get(pendingRuntimeRequests)).size > 0 + ) { + return; + } + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + }), + ).pipe(Effect.asVoid); + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + } + return; + } const drainedWakeCount = yield* takeWakeBuffer.pipe( Effect.tap((drained) => Effect.forEach(drained, handleSessionUpdate, { @@ -9144,9 +9487,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : flavor.getModelContextWindow?.(selection, session); }, }), - ...(postSettleContinuationEnabled || followsAgentWorkState - ? { - hasPendingBackgroundWork: Effect.gen(function* () { + ...(flavor.backgroundTasksEndWithProcess === true + ? { backgroundTasksEndWithProcess: true as const } + : {}), + ...(postSettleContinuationEnabled || + followsAgentWorkState || + flavor.extractBackgroundWorkTask !== undefined + ? (() => { + const hasPendingBackgroundWork = Effect.gen(function* () { const rootSessionId = yield* Ref.get(activeSessionId); if ( followsAgentWorkState && @@ -9165,6 +9513,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; if (yield* Ref.get(continuationRequested)) return true; if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; + if ((yield* Ref.get(trackedBackgroundTasks)).size > 0) return true; const active = yield* Ref.get(activeTurn); if ( active !== null && @@ -9180,9 +9529,72 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return true; } return false; - }), - } + }); + return { + hasPendingBackgroundWork, + hasPendingBackgroundWorkForThread: Effect.fnUntraced(function* ( + providerThread: OrchestrationV2ProviderThread, + ) { + const rootSessionId = yield* Ref.get(activeSessionId); + if ( + rootSessionId === null || + providerThread.nativeThreadRef?.nativeId !== rootSessionId + ) { + return false; + } + return yield* hasPendingBackgroundWork; + }), + }; + })() : {}), + ...(flavor.extractBackgroundWorkTask === undefined + ? {} + : { + awaitBackgroundTasks: Effect.fn("AcpAdapterV2.awaitBackgroundTasks")( + function* ({ providerThread, taskIds, awaited }) { + const sessionId = yield* Ref.get(activeSessionId); + if ( + sessionId === null || + providerThread.nativeThreadRef?.nativeId !== sessionId + ) { + return { matched: [] }; + } + const currentTasks = yield* Ref.get(trackedBackgroundTasks); + if (currentTasks.size === 0) return { matched: [] }; + const runningTaskIds = [...currentTasks.keys()]; + const matchedPairs: Array = []; + for (const rawTaskId of new Set(taskIds)) { + if (currentTasks.has(rawTaskId)) { + matchedPairs.push([rawTaskId, rawTaskId]); + continue; + } + if (flavor.resolveBackgroundTaskId !== undefined) { + const resolved = yield* flavor.resolveBackgroundTaskId({ + sessionId, + taskId: rawTaskId, + runningTaskIds, + }); + if (resolved !== undefined && currentTasks.has(resolved)) { + matchedPairs.push([rawTaskId, resolved]); + } + } + } + if (matchedPairs.length === 0) return { matched: [] }; + yield* Ref.update(trackedBackgroundTasks, (current) => { + const next = new Map(current); + for (const [, targetId] of matchedPairs) { + const existing = next.get(targetId); + if (existing === undefined) continue; + next.set(targetId, { ...existing, awaited }); + } + return next; + }); + yield* emitBackgroundRosterUpdate(sessionId); + return { matched: matchedPairs.map(([rawTaskId]) => rawTaskId) }; + }, + (effect) => runtimeCallbackPermit.withPermit(effect), + ), + }), ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( function* (threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) { return yield* runtimeTransitionPermit.withPermit( @@ -9570,6 +9982,37 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); yield* Ref.set(runtimeTeardownState, { _tag: "Idle" }); yield* Deferred.succeed(teardownBarrier, undefined).pipe(Effect.ignore); + } else if ( + context === null && + turnInput.requestRuntimeRestart === true && + ((yield* Ref.get(trackedBackgroundTasks)).size > 0 || + (yield* Ref.get(runningBackgroundTaskIds)).size > 0 || + (yield* Ref.get(wakeBuffer)).length > 0 || + (yield* Ref.get(continuationRequested))) + ) { + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + yield* awaitAdmittedNativeResponses; + const stoppedGeneration = yield* Ref.get(runtimeCallbackGeneration); + yield* quarantineNativeTransportAtGeneration(stoppedGeneration); + yield* advanceRuntimeCallbackGeneration; + yield* quarantineStoppedRun(); + yield* cancelPendingRuntimeRequests(); + }), + ); + const sessionCapabilities = (yield* Ref.get(activeSessionSetup)) + ?.initializeResult.agentCapabilities?.sessionCapabilities; + if (sessionCapabilities?.close != null) { + yield* runtime + .closeSession() + .pipe(Effect.timeoutOption("2 seconds"), Effect.ignore); + } + if (runtimeScope !== undefined) { + const closing = runtimeScope; + runtimeScope = undefined; + yield* Scope.close(closing, Exit.void).pipe(Effect.ignore); + } + yield* Ref.set(runtimeRestartRequired, true); } return undefined; }