TypeScript
fix(acp): time out silent Antigravity prompts (#30377)
shivam3f905cac2e4d
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.tsindex de3fdb1a314..a8ca338c877 100644--- a/apps/server/scripts/acp-mock-agent.ts+++ b/apps/server/scripts/acp-mock-agent.ts@@ -1848,6 +1848,11 @@ const program = Effect.gen(function* () {if (method === "_test/finish-cancel") {return Deferred.succeed(nativeCancelRelease, undefined).pipe(Effect.as({}));}+ if (method === "_test/emit-update") {+ return agent.client+ .sessionUpdate(params as AcpSchema.SessionNotification)+ .pipe(Effect.as({}));+ }if (method === "_test/startup-metadata") {return Effect.gen(function* () {for (const [metadataSessionId, commandName, modeId] of [diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.tsindex 7234c561b91..dff370bd611 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts@@ -36,7 +36,7 @@ import { deriveBlockedOnThreadWait } from "@t3tools/shared/orchestrationV2Pendinimport { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";-import type * as Duration from "effect/Duration";+import * as Duration from "effect/Duration";import * as Cause from "effect/Cause";import * as Clock from "effect/Clock";import * as Effect from "effect/Effect";@@ -515,6 +515,90 @@ function makeMockRuntime(input: {});}+const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);++const makePromptInactivityHarness = Effect.fnUntraced(function* (input: {+ readonly environment: (runtimeOrdinal: number) => Readonly<Record<string, string>>;+ readonly runtimeMode?: "full-access" | "approval-required";+}) {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const path = yield* Path.Path;+ const natives: Array<AcpSessionRuntime.AcpSessionRuntime["Service"]> = [];+ const instanceId = ProviderInstanceId.make("acp-prompt-inactivity");+ const adapter = yield* makeAcpAdapterV2({+ instanceId,+ flavor: {+ driver: ACP_TEST_DRIVER,+ capabilities: AcpProviderCapabilitiesV2,+ promptInactivityTimeout: "15 minutes",+ makeRuntime: makeMockRuntime({+ childProcessSpawner,+ mockAgentPath: yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ ),+ environment: input.environment,+ wrapRuntime: (runtime) => {+ natives.push(runtime);+ return runtime;+ },+ }),+ },+ selfInvocation: yield* resolveSelfInvocation(),+ });+ const threadId = ThreadId.make("thread-acp-prompt-inactivity");+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: input.runtimeMode ?? "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const modelSelection = { instanceId, model: "default" } as const;+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-inactivity"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });+ const startTurn = (ordinal: number) =>+ DateTime.now.pipe(+ Effect.flatMap((now) =>+ runtime.startTurn(+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),+ ),+ ),+ );+ return {+ runtime,+ natives,+ startTurn,+ /** A turn still running makes the next start fail, without waiting on time. */+ nextTurnRejected: (ordinal: number) =>+ startTurn(ordinal).pipe(+ Effect.flip,+ Effect.map(+ (error) =>+ isProviderAdapterProtocolError(error.cause) &&+ error.cause.reason === "previous_turn_active",+ ),+ Effect.catchCause(() => Effect.succeed(false)),+ ),+ emitUpdate: (notification: EffectAcpSchema.SessionNotification) =>+ natives.at(-1)!.request("_test/emit-update", notification),+ terminals: (count: number) =>+ runtime.events.pipe(+ Stream.filter((event) => event.type === "turn.terminal"),+ Stream.take(count),+ Stream.runCollect,+ Effect.map((events) =>+ Array.from(events, (event) => {+ if (event.type !== "turn.terminal") throw new Error("Expected a turn terminal");+ return event;+ }),+ ),+ ),+ };+});+function rawProtocolMethod(event: EffectAcpProtocol.AcpProtocolLogEvent): string | undefined {if (event.stage !== "raw" || typeof event.payload !== "string") return undefined;for (const line of event.payload.split("\n")) {@@ -3924,6 +4008,157 @@ describe("AcpAdapterV2", () => {}).pipe(Effect.provide(layerTest), Effect.scoped),);+ it.effect("fails a prompt its agent leaves silent past the inactivity timeout", () =>+ Effect.gen(function* () {+ const harness = yield* makePromptInactivityHarness({+ environment: (runtimeOrdinal) =>+ runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {},+ });+ const thought = (sessionId: string) => ({+ sessionId,+ update: {+ sessionUpdate: "agent_thought_chunk" as const,+ content: { type: "text" as const, text: "Still working." },+ },+ });+ yield* harness.startTurn(1);+ yield* TestClock.adjust("10 minutes");+ yield* harness.emitUpdate(thought("mock-session-1"));+ yield* TestClock.adjust("5 minutes");+ // Neither another session's progress nor this session's metadata extends this turn.+ yield* harness.emitUpdate(thought("foreign-session"));+ yield* harness.emitUpdate({+ sessionId: "mock-session-1",+ update: { sessionUpdate: "available_commands_update", availableCommands: [] },+ });+ yield* TestClock.adjust(Duration.millis(10 * 60_000 - 1));+ assert.isTrue(yield* harness.nextTurnRejected(2));++ yield* TestClock.adjust("1 millis");+ yield* harness.startTurn(2);+ const [silent, next] = yield* harness.terminals(2);+ assert.equal(silent?.status, "failed");+ assert.include(silent?.failure?.message, "15 minutes");+ assert.equal(next?.status, "completed");+ assert.lengthOf(harness.natives, 2);+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );++ it.effect(+ "holds the inactivity timeout while a tool runs and restarts it when the tool ends",+ () =>+ Effect.gen(function* () {+ const harness = yield* makePromptInactivityHarness({+ environment: (runtimeOrdinal) =>+ runtimeOrdinal === 1 ? { T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG: "execute" } : {},+ });+ yield* harness.startTurn(1);+ yield* harness.runtime.events.pipe(+ Stream.filter(+ (event) =>+ event.type === "turn_item.updated" &&+ event.turnItem.nativeItemRef?.nativeId === "tracked-tool-call",+ ),+ Stream.runHead,+ );+ yield* TestClock.adjust("1 hour");+ assert.isTrue(yield* harness.nextTurnRejected(2));++ yield* harness.emitUpdate({+ sessionId: "mock-session-1",+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "tracked-tool-call",+ status: "completed",+ },+ });+ yield* TestClock.adjust(Duration.millis(15 * 60_000 - 1));+ assert.isTrue(yield* harness.nextTurnRejected(2));+ yield* TestClock.adjust("1 millis");+ yield* harness.startTurn(2);+ const [silent, next] = yield* harness.terminals(2);+ assert.equal(silent?.status, "failed");+ assert.equal(next?.status, "completed");+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );++ it.effect("holds the inactivity timeout while the agent waits on an approval", () =>+ Effect.gen(function* () {+ const harness = yield* makePromptInactivityHarness({+ environment: () => ({ T3_ACP_EMIT_TOOL_CALLS: "1" }),+ runtimeMode: "approval-required",+ });+ yield* harness.startTurn(1);+ const pending = Option.getOrThrow(+ yield* harness.runtime.events.pipe(+ Stream.filter(+ (event) =>+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",+ ),+ Stream.runHead,+ ),+ );+ if (pending.type !== "runtime_request.updated") {+ return yield* Effect.die("Expected a pending approval");+ }+ // Only the request is left open, so it alone holds the deadline.+ yield* harness.emitUpdate({+ sessionId: "mock-session-1",+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "tool-call-1",+ status: "completed",+ },+ });+ yield* TestClock.adjust("1 hour");+ assert.isTrue(yield* harness.nextTurnRejected(2));++ yield* harness.runtime.respondToRuntimeRequest({+ requestId: pending.runtimeRequest.id,+ decision: "accept",+ });+ const [approved] = yield* harness.terminals(1);+ assert.equal(approved?.status, "completed");+ assert.lengthOf(harness.natives, 1);+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );++ it.effect("fails a running prompt once when its agent process exits", () =>+ Effect.gen(function* () {+ const harness = yield* makePromptInactivityHarness({+ environment: (runtimeOrdinal) =>+ runtimeOrdinal === 1+ ? { T3_ACP_EMIT_TOOL_CALLS: "1" }+ : runtimeOrdinal === 2+ ? { T3_ACP_HANG_PROMPT_FOREVER: "1" }+ : {},+ runtimeMode: "approval-required",+ });+ yield* harness.startTurn(1);+ // The dying agent leaves an approval unanswered.+ yield* harness.runtime.events.pipe(+ Stream.filter(+ (event) =>+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",+ ),+ Stream.runHead,+ );+ yield* harness.natives[0]!.notify("_test/exit", {});+ const [exited] = yield* harness.terminals(1);+ assert.equal(exited?.status, "failed");++ // The replacement's silent prompt still times out.+ yield* harness.startTurn(2);+ yield* TestClock.adjust("15 minutes");+ yield* harness.startTurn(3);+ const [silent, next] = yield* harness.terminals(2);+ assert.equal(silent?.status, "failed");+ assert.notEqual(silent?.providerTurnId, exited?.providerTurnId);+ assert.equal(next?.status, "completed");+ assert.lengthOf(harness.natives, 3);+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );+it.live("does not poll the process ledger while a cgroup lease owns teardown", () =>Effect.gen(function* () {if ((yield* HostProcess.Platform) !== "linux") return;diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.tsindex 4d2f7bac175..1490140c1e6 100644--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts@@ -273,6 +273,8 @@ export function makeAntigravityAcpAdapterFlavor(// ACP 1.3.0 treats /compact as ordinary model input.supportsCompaction: false,requiresSignIn: isAntigravitySignInRequiredError,+ // Antigravity can leave a prompt open without updates; long tools and approvals pause this.+ promptInactivityTimeout: "15 minutes",// 1.4.5 returns the root trajectory's Gemini usageMetadata delta; 1.4.1 returns none.reportsPerTurnPromptUsage: true,geminiPromptUsage: true,diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex d08ecd8ce87..678cd7edf22 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -149,6 +149,24 @@ const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis";*/const ACP_TEXT_FLUSH_INTERVAL: Duration.Input = "50 millis";+// Output of the running prompt. Session metadata and unknown updates do not reset its timeout.+const ACP_PROMPT_ACTIVITY_UPDATES: ReadonlySet<string> = new Set([+ "agent_message",+ "agent_message_chunk",+ "agent_thought",+ "agent_thought_chunk",+ "tool_call",+ "tool_call_update",+ "tool_call_content_chunk",+ "terminal_output_chunk",+ "terminal_update",+ "plan",+ "plan_update",+ "plan_removed",+ "compaction_update",+ "compaction_summary_chunk",+]);+export interface AcpAdapterV2RuntimeInput {readonly cwd: string;readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;@@ -167,6 +185,7 @@ export interface AcpAdapterV2RuntimeInput {readonly onTermination: NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]>;readonly onOutgoingResponseFailure?: AcpSessionRuntime.AcpSessionRuntimeOptions["onOutgoingResponseFailure"];readonly onOutgoingResponse?: AcpSessionRuntime.AcpSessionRuntimeOptions["onOutgoingResponse"];+ readonly onIncomingRequest?: AcpSessionRuntime.AcpSessionRuntimeOptions["onIncomingRequest"];}export type AcpAdapterV2NativeLogging = Pick<@@ -512,6 +531,11 @@ export interface AcpAdapterV2Flavor {readonly reportsPerTurnPromptUsage?: boolean;/** Gemini-style usage: inputTokens leaves out cachedReadTokens, outputTokens leaves out thoughtTokens. */readonly geminiPromptUsage?: boolean;+ /**+ * Fails a dispatched prompt after this long with no update for its session while no+ * agent request, tool or subagent is open, and replaces the agent before the next turn.+ */+ readonly promptInactivityTimeout?: Duration.Input;/** Grok can retain task_already_running until process exit. */readonly restartRuntimeAfterInterrupt?: boolean;/** Prompt failures after which the agent process keeps failing until replaced. */@@ -1395,6 +1419,9 @@ interface ActiveAcpTurn {backgroundFinalizeGeneration: 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`. */+ lastProgressAt: number;+ inactivityWatchdog: Fiber.Fiber<void> | undefined;}type AcpRuntimeTeardownState =@@ -2259,6 +2286,40 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (Effect.void;const nativeLogging = options.nativeLogging?.(input.threadId);+ const promptInactivityTimeoutMillis =+ flavor.promptInactivityTimeout === undefined+ ? undefined+ : Duration.toMillis(flavor.promptInactivityTimeout);+ // Each runtime owns its unanswered agent requests, so a dead process's leftovers+ // and late callbacks never reach its replacement.+ let openAgentRequests = new Set<string>();+ const notePromptProgress =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) {+ if (promptInactivityTimeoutMillis === undefined) return;+ if (+ notification !== undefined &&+ !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate)+ ) {+ return;+ }+ const context = yield* Ref.get(activeTurn);+ if (+ context === null ||+ (notification !== undefined &&+ notification.sessionId !== context.nativeThreadId &&+ !context.subagentsBySessionId.has(notification.sessionId))+ ) {+ return;+ }+ context.lastProgressAt = yield* Clock.currentTimeMillis;+ });+ const closeAgentRequest = (agentRequests: Set<string>, requestId: string) =>+ Effect.suspend(() =>+ agentRequests.delete(requestId) && agentRequests === openAgentRequests+ ? notePromptProgress()+ : Effect.void,+ );const handleRuntimeTerminationAtGeneration = (runtimeGeneration: number) =>runRuntimeCallbackAtGeneration(runtimeGeneration,@@ -2295,6 +2356,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ().pipe(Effect.asVoid);const makeRuntimeInput = (runtimeGeneration: number,+ agentRequests: Set<string>,mcpContext: AcpMcpContext,resumeSessionId?: string,onTermination: AcpAdapterV2RuntimeInput["onTermination"] = () =>@@ -2321,7 +2383,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (...(flavor.clientCapabilitiesMeta ? { _meta: flavor.clientCapabilitiesMeta } : {}),},clientInfo: { name: "t3-code", version: "0.0.0" },- onTermination,+ onTermination: (error) =>+ Effect.sync(() => agentRequests.clear()).pipe(Effect.andThen(onTermination(error))),+ ...(promptInactivityTimeoutMillis === undefined+ ? {}+ : {+ onIncomingRequest: (requestId: string) =>+ Effect.sync(() => {+ agentRequests.add(requestId);+ }),+ }),onOutgoingResponseFailure: (requestId, error) =>Ref.modify(nativeResponseAcknowledgements, (current) => {const entry = current.get(requestId);@@ -2350,7 +2421,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (),updated,] as const;- }).pipe(Effect.flatten),+ }).pipe(Effect.flatten, Effect.andThen(closeAgentRequest(agentRequests, requestId))),onOutgoingResponse: (requestId) =>Ref.modify(nativeResponseAcknowledgements, (current) => {const entry = current.get(requestId);@@ -2379,7 +2450,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (),updated,] as const;- }).pipe(Effect.flatten),+ }).pipe(Effect.flatten, Effect.andThen(closeAgentRequest(agentRequests, requestId))),...(nativeLogging?.requestLogger === undefined? {}: { requestLogger: nativeLogging.requestLogger }),@@ -6170,6 +6241,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (Effect.fnUntraced(function* (rawNotification: EffectAcpSchema.SessionNotification) {if (flavor.ignoreSessionUpdate?.(rawNotification) === true) return;+ yield* notePromptProgress(rawNotification);const nativePromptId = flavor.forkFromTurn?.nativeTurnId(rawNotification);if (nativePromptId !== undefined) {const context = yield* Ref.get(activeTurn);@@ -6780,8 +6852,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (const mcpContext = yield* readMcpContext(threadId);runtimeMcpBridge = yield* makeRuntimeMcpBridge(mcpContext, runtimeScope);const runtimeGeneration = yield* Ref.get(runtimeCallbackGeneration);+ openAgentRequests = new Set();runtime = yield* flavor- .makeRuntime(makeRuntimeInput(runtimeGeneration, mcpContext, resumeSessionId))+ .makeRuntime(+ makeRuntimeInput(runtimeGeneration, openAgentRequests, mcpContext, resumeSessionId),+ ).pipe(Effect.provideService(Scope.Scope, runtimeScope),Effect.provideService(SecureRandom.SecureRandom, random),@@ -6821,6 +6896,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (// Keep live callbacks active until replacement startup succeeds.const replacementGeneration = yield* allocateRuntimeCallbackGeneration;const replacementScope = yield* Scope.make();+ const replacementAgentRequests = new Set<string>();type CandidateLifecycle =| { readonly _tag: "Starting" }| { readonly _tag: "Terminated"; readonly error: EffectAcpErrors.AcpError }@@ -6856,6 +6932,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (.makeRuntime(makeRuntimeInput(replacementGeneration,+ replacementAgentRequests,mcpContext,undefined,handleCandidateTermination,@@ -6919,6 +6996,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (runtime = replacementExit.value.replacementRuntime;runtimeScope = replacementScope;runtimeMcpBridge = replacementMcpBridge;+ openAgentRequests = replacementAgentRequests;yield* Ref.set(runtimeCallbackGeneration, replacementGeneration);prepareTerminalEnvironment(yield* readMcpContext(threadId),@@ -7499,6 +7577,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (const settledStatus = context.interrupted ? "interrupted" : status;context.finalizedStatus = settledStatus;context.finalized = true;+ const watchdog = context.inactivityWatchdog;+ context.inactivityWatchdog = undefined;+ if (watchdog !== undefined) {+ yield* Fiber.interrupt(watchdog).pipe(Effect.forkDetach, Effect.asVoid);+ }const directStopQuarantine = yield* Ref.get(stoppedRunQuarantine);if (flavor.subagentsIdleOnTurnCompletion === true) {for (const subagent of context.subagents.values()) {@@ -7694,6 +7777,97 @@ 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;+ }+ for (const subagent of context.subagents.values()) {+ if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) return true;+ }+ return false;+ });++ /**+ * Holds the transition permit from the deadline check through process teardown,+ * so Stop and the next turn see either a running prompt or a replaced runtime.+ */+ const retireInactivePrompt = Effect.fn("AcpAdapterV2.retireInactivePrompt")(function* (+ context: ActiveAcpTurn,+ generation: number,+ timeoutMillis: number,+ ) {+ const retired = yield* runRuntimeCallbackAtGeneration(+ generation,+ Effect.gen(function* () {+ if (context.finalized || context.interrupted) return "done" as const;+ if ((yield* Ref.get(activeTurn)) !== context) return "done" as const;+ if (yield* Deferred.isDone(context.promptWireSettled)) return "done" as const;+ const now = yield* Clock.currentTimeMillis;+ if (context.lastProgressAt + timeoutMillis > now) return "rearm" as const;+ if (yield* promptInactivityPaused(context)) {+ context.lastProgressAt = now;+ return "rearm" as const;+ }+ context.inactivityWatchdog = undefined;+ openAgentRequests.clear();+ yield* quarantineNativeTransportAtGeneration(generation);+ yield* advanceRuntimeCallbackGeneration;+ yield* Ref.set(runtimeRestartRequired, true);+ yield* cancelPendingRuntimeRequests();+ yield* terminalizeOpenForegroundTools(context, "failed");+ const minutes = Math.max(1, Math.round(timeoutMillis / 60_000));+ yield* finalizeTurn(+ context,+ "failed",+ makeProviderFailure({+ class: "provider_error",+ message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`,+ }),+ );+ return "retired" as const;+ }),+ );+ if (Option.isNone(retired) || retired.value !== "retired") {+ return Option.getOrElse(retired, () => "done" as const);+ }+ yield* Effect.logWarning("orchestration-v2.acp-prompt-inactive", {+ driver,+ providerSessionId: input.providerSessionId,+ providerTurnId: context.providerTurnId,+ timeoutMillis,+ });+ if (runtimeScope !== undefined) {+ yield* Scope.close(runtimeScope, Exit.void).pipe(Effect.ignore);+ }+ return "retired" as const;+ });++ const watchPromptInactivity = Effect.fn("AcpAdapterV2.watchPromptInactivity")(function* (+ context: ActiveAcpTurn,+ generation: number,+ timeoutMillis: number,+ ) {+ yield* Deferred.await(context.promptDispatched);+ context.lastProgressAt = yield* Clock.currentTimeMillis;+ while (true) {+ const remaining =+ context.lastProgressAt + timeoutMillis - (yield* Clock.currentTimeMillis);+ if (remaining > 0) {+ yield* Effect.sleep(Duration.millis(remaining));+ continue;+ }+ const outcome = yield* runtimeTransitionPermit.withPermit(+ retireInactivePrompt(context, generation, timeoutMillis),+ );+ if (outcome !== "rearm") return;+ }+ });+const resolvePromptParts = Effect.fnUntraced(function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,sessionId: string,@@ -8004,6 +8178,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (promptUsage: undefined,backgroundFinalizeGeneration: 0,nativePromptId: undefined,+ lastProgressAt: 0,+ inactivityWatchdog: undefined,};const carryover = yield* Ref.getAndSet(carryoverSubagents, null);let rehydratedCarryoverSubagents: ReadonlyArray<ActiveAcpSubagent> = [];@@ -8145,6 +8321,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (const promptGeneration = yield* Ref.get(runtimeCallbackGeneration);const promptOptions = { dispatched: context.promptDispatched };context.promptSentAt = yield* Clock.currentTimeMillis;+ if (promptInactivityTimeoutMillis !== undefined) {+ context.inactivityWatchdog = yield* watchPromptInactivity(+ context,+ promptGeneration,+ promptInactivityTimeoutMillis,+ ).pipe(Effect.forkIn(sessionScope));+ }const compactSession = isCompactionMessage(turnInput.message)? flavor.compactSession: undefined;