diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 1f777fd134e47..3404ca16ff665 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -14126,6 +14126,502 @@ describe("AcpAdapterV2", () => { assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); }).pipe(Effect.provide(layerTest)), ); + + it.effect( + "recycles a runtime before a new turn once maxRuntimeAgeBeforeTurn elapses and reports output presence to watchPromptOutcome", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-max-runtime-age"); + const threadId = ThreadId.make("thread-acp-max-runtime-age"); + const promptRuntimes: Array = []; + const resumeIds: Array = []; + const receivedOutputs: Array = []; + let emitReplyOnNextPrompt = false; + let pendingReply = false; + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => { + let onUpdate: Parameters[0] | undefined; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + onUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (emitReplyOnNextPrompt && onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "ok" }, + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + }; + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + hasPendingReply: () => Effect.sync(() => pendingReply), + watchPromptOutcome: () => + Effect.succeed((_result, options) => + Effect.sync(() => { + receivedOutputs.push(options?.receivedOutput); + return undefined; + }), + ), + makeRuntime: (runtimeInput) => + Effect.sync(() => { + resumeIds.push(runtimeInput.resumeSessionId); + }).pipe(Effect.andThen(baseMakeRuntime(runtimeInput))), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-max-runtime-age"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number, emitReply: boolean) => + Effect.gen(function* () { + emitReplyOnNextPrompt = emitReply; + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + // Turn 1: silent prompt on runtime 1. + yield* runTurn(1, false); + // Turn 2 at +30m (< 45m): reuses runtime 1 and emits assistant output. + yield* TestClock.adjust("30 minutes"); + yield* runTurn(2, true); + // Turn 3 at +50m (>= 45m), but a queued reply defers recycling on runtime 1. + yield* TestClock.adjust("20 minutes"); + pendingReply = true; + yield* runTurn(3, true); + // Turn 4 once the pending reply clears: proactively recycles to runtime 2 with resumeSessionId. + pendingReply = false; + yield* runTurn(4, true); + // Restarting via loadSession keeps the replayed snapshot history intact. + const snapshotAfterRecycle = yield* session.readThreadSnapshot({ providerThread }); + assert.isTrue( + snapshotAfterRecycle.messages.some((message) => message.text.includes("replay")), + "expected replayed snapshot message to survive runtime recycle", + ); + // Turn 5 at +10m after recycle (< 45m on runtime 2): stays on runtime 2. + yield* TestClock.adjust("10 minutes"); + yield* runTurn(5, false); + + assert.deepEqual(promptRuntimes, [1, 1, 1, 2, 2]); + assert.deepEqual(resumeIds, [undefined, providerThread.nativeThreadRef?.nativeId]); + assert.deepEqual(receivedOutputs, [false, true, true, true, false]); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect( + "gates maxRuntimeAgeBeforeTurn recycling on nonterminal detached tools, not ended history", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-detached-recycle"); + const threadId = ThreadId.make("thread-acp-detached-recycle"); + const promptRuntimes: Array = []; + const promptSettledWithBackgroundWork = yield* Queue.unbounded(); + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => { + let onUpdate: Parameters[0] | undefined; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + onUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (promptRuntimes.length === 1 && onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "detached-tool-1", + title: "Background tool", + kind: "execute", + status: "in_progress", + }, + }); + } else if (promptRuntimes.length === 2 && onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "detached-tool-1", + status: "completed", + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + }; + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + deferFinalizeForBackgroundWork: true, + toolOutlivesPrompt: () => true, + makeRuntime: baseMakeRuntime, + }, + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Queue.offer(promptSettledWithBackgroundWork, undefined), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-detached-recycle"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const until = (done: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) => + Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (done(event)) return seen; + } + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const startTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + }); + const awaitTerminal = () => + Effect.gen(function* () { + const seen = yield* until((event) => event.type === "turn.terminal"); + const terminal = seen.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + // Turn 1 leaves a running outliving tool detached via awaitBackgroundTasks(awaited=false). + yield* startTurn(1); + yield* Queue.take(promptSettledWithBackgroundWork); + const released = yield* session.awaitBackgroundTasks!({ + providerThread, + taskIds: ["mock-session-1/task-1"], + awaited: false, + }); + assert.deepEqual(released.matched, ["mock-session-1/task-1"]); + yield* TestClock.adjust("5 seconds"); + yield* awaitTerminal(); + + // At +50m, the still-running detached tool blocks proactive recycling on turn 2. + // Turn 2's prompt then emits its completion, leaving the ended entry in + // detachedUnawaitedTools for late corrections. + yield* TestClock.adjust("50 minutes"); + yield* startTurn(2); + yield* awaitTerminal(); + assert.deepEqual(promptRuntimes, [1, 1]); + + // On turn 3, the ended detached history must no longer block recycling. + yield* startTurn(3); + yield* awaitTerminal(); + assert.deepEqual(promptRuntimes, [1, 1, 2]); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect( + "preserves cached snapshot history across a same-session resume that emits no replay", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-resume-no-replay-snapshot"); + const threadId = ThreadId.make("thread-acp-resume-no-replay-snapshot"); + const promptRuntimes: Array = []; + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => { + let onUpdate: Parameters[0] | undefined; + return { + ...runtime, + // Simulate a same-session session/resume that sends no replay updates even + // though the agent advertises both loadSession and sessionCapabilities.resume. + handleSessionUpdate: (handler) => + Effect.sync(() => { + onUpdate = handler; + }).pipe( + Effect.andThen( + runtime.handleSessionUpdate((notification) => + runtimeOrdinal > 1 ? Effect.void : handler(notification), + ), + ), + ), + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: `reply-runtime-${runtimeOrdinal}` }, + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + }; + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: baseMakeRuntime, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-resume-no-replay"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + yield* runTurn(1); + yield* TestClock.adjust("50 minutes"); + yield* runTurn(2); + assert.deepEqual(promptRuntimes, [1, 2]); + + const snapshotAfterRecycle = yield* session.readThreadSnapshot({ providerThread }); + assert.isTrue( + snapshotAfterRecycle.messages.some((message) => message.text.includes("reply-runtime-1")), + "expected prior turn reply to remain cached when resume emits no replay", + ); + assert.isTrue( + snapshotAfterRecycle.messages.some((message) => message.text.includes("reply-runtime-2")), + "expected post-recycle reply to appear in snapshot", + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect( + "preserves runtimeRestartRequired when a replacement runtime terminates during restart drain", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-restart-drain-termination"); + const threadId = ThreadId.make("thread-acp-restart-drain-termination"); + const promptRuntimes: Array = []; + const onTerminations = new Map(); + let nextRuntime = 0; + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => ({ + ...runtime, + drainEvents: + runtimeOrdinal === 2 + ? runtime.drainEvents.pipe( + Effect.andThen( + onTerminations.get(2)?.( + new EffectAcpErrors.AcpTransportError({ + detail: "replacement runtime exited during drain", + cause: new Error("exited"), + }), + ) ?? Effect.void, + ), + ) + : runtime.drainEvents, + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + return { stopReason: "end_turn" as const }; + }), + }), + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: (runtimeInput) => + Effect.sync(() => { + nextRuntime += 1; + onTerminations.set(nextRuntime, runtimeInput.onTermination); + }).pipe(Effect.andThen(baseMakeRuntime(runtimeInput))), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-drain-termination"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + yield* runTurn(1); + yield* TestClock.adjust("50 minutes"); + // Runtime 2 terminates during drainEvents; Turn 3 must not reuse it. + yield* runTurn(2); + yield* runTurn(3); + assert.deepEqual(promptRuntimes, [1, 2, 3]); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index f7261e013111e..f680e79ce8843 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -6345,3 +6345,191 @@ describe("AntigravityAdapterV2 command exits", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 silent ADC drop recovery", () => { + it.effect("fails a silent USER_INPUT-only turn and restarts the runtime on the next send", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + 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), + ); + const profileDirectory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-adc-drop-", + }); + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversations, { recursive: true }); + const appendStep = (type: number, status: number, payload: string) => { + const database = new NodeSqlite.DatabaseSync(path.join(conversations, "mock-session-1.db")); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, step_payload BLOB)", + ); + database + .prepare("INSERT INTO steps (step_type, status, step_payload) VALUES (?, ?, ?)") + .run(type, status, Buffer.from(payload)); + } finally { + database.close(); + } + }; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let runtimeOrdinal = 0; + const promptRuntimes: Array = []; + const resumeIds: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-adc-drop-test"); + const threadId = ThreadId.make("thread-antigravity-adc-drop"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + profileDirectory, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: (input) => { + const currentRuntime = ++runtimeOrdinal; + resumeIds.push(input.resumeSessionId); + let sessionUpdate: Parameters[0] | undefined; + return makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.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))), + prompt: () => + Effect.gen(function* () { + promptRuntimes.push(currentRuntime); + appendStep(14, 3, `Prompt on runtime ${currentRuntime}`); + // Simulate agy's 60m ADC OAuth failure on runtime 1: only USER_INPUT is + // recorded and session/prompt resolves cleanly with no output or usage. + if (currentRuntime === 1) { + return { stopReason: "end_turn" as const }; + } + yield* sessionUpdate!( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: `Reply from runtime ${currentRuntime}` }, + }, + }), + ); + appendStep(15, 3, `Reply from runtime ${currentRuntime}`); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 }, + }; + }), + })), + ); + }, + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + 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-adc-drop"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-adc-drop"), + title: "Antigravity ADC drop", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: runtimePolicy.runtimeMode, + interactionMode: runtimePolicy.interactionMode, + branch: null, + worktreePath: null, + 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, + }, + threadId, + runId: RunId.make(`run-antigravity-adc-drop-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-adc-drop-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-adc-drop-${ordinal}`), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`msg-antigravity-adc-drop-${ordinal}`), + text: `Hello ${ordinal}`, + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + return events.at(-1); + }); + + // Turn 1 hits the silent drop on runtime 1 and fails with a retryable provider error. + const firstTerminal = yield* runTurn(1); + assert.equal(firstTerminal?.type, "turn.terminal"); + assert.equal(firstTerminal?.type === "turn.terminal" ? firstTerminal.status : null, "failed"); + assert.equal( + firstTerminal?.type === "turn.terminal" && firstTerminal.status === "failed" + ? firstTerminal.failure.retryable + : null, + true, + ); + + // Turn 2 automatically restarts onto runtime 2 (resuming mock-session-1) and succeeds. + const secondTerminal = yield* runTurn(2); + assert.equal( + secondTerminal?.type === "turn.terminal" ? secondTerminal.status : null, + "completed", + ); + + assert.deepEqual(promptRuntimes, [1, 2]); + assert.deepEqual(resumeIds, [undefined, "mock-session-1"]); + }).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 10d9ffe891122..e13da479cb506 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -9,6 +9,7 @@ import type { SelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; +import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -118,6 +119,8 @@ export interface AntigravityAdapterV2Options { readonly continuationRequests?: Parameters[0]["continuationRequests"]; /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */ readonly profileDirectory?: string; + /** Recycles long-lived ACP runtimes before a new turn (used for ADC's 60m token cliff). */ + readonly maxRuntimeAgeBeforeTurn?: Duration.Input; } /** @@ -358,6 +361,9 @@ export function makeAntigravityAcpAdapterFlavor( checksVersionAtHandshake: true, // Antigravity can leave a prompt open without updates; long tools and approvals pause this. promptInactivityTimeout: "15 minutes", + ...(options.maxRuntimeAgeBeforeTurn === undefined + ? {} + : { maxRuntimeAgeBeforeTurn: options.maxRuntimeAgeBeforeTurn }), reportsPerTurnPromptUsage: true, geminiPromptUsage: true, ...(profileDirectory === undefined diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 86f019c0090ce..be66518faacc6 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -49,7 +49,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter" import { knownProviderFailureMessage } from "@t3tools/provider-core/server/failure"; import { resolveProviderCompatibility } from "../providerCompatibility.ts"; import { writeProviderStatusCache } from "../providerStatusCache.ts"; -import { AntigravityDriver } from "./AntigravityDriver.ts"; +import { AntigravityDriver, antigravityMaxRuntimeAgeBeforeTurn } from "./AntigravityDriver.ts"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as ProviderHostLive from "../ProviderHostLive.ts"; import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; @@ -1129,4 +1129,16 @@ it.layer(layerTest)("AntigravityDriver", (it) => { yield* h.assertClosed; }), ); + + it("enables 45-minute runtime recycling only for Agent Platform ADC auth", () => { + expect(antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "" })).toBe( + "45 minutes", + ); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "AIza-test" }), + ).toBeUndefined(); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "oauth-personal", apiKey: "" }), + ).toBeUndefined(); + }); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 8527678f0d99c..db346698a445f 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -98,6 +98,17 @@ import { readProviderStatusCache, resolveProviderStatusCachePath } from "../prov import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts"; const DRIVER = ProviderDriverKind.make("antigravity"); +// agy acp in Agent Platform ADC mode fails OAuth refresh with context canceled at 60 minutes; +// recycling between turns at 45 minutes keeps sessions on a fresh token without hitting the cliff. +const ANTIGRAVITY_ADC_MAX_RUNTIME_AGE = "45 minutes" as const; + +export function antigravityMaxRuntimeAgeBeforeTurn( + auth: Pick, +): typeof ANTIGRAVITY_ADC_MAX_RUNTIME_AGE | undefined { + return auth.authMethod === "agent-platform" && !auth.apiKey.trim() + ? ANTIGRAVITY_ADC_MAX_RUNTIME_AGE + : undefined; +} const decodeSettings = Schema.decodeSync(AntigravitySettings); const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); @@ -820,6 +831,7 @@ export const AntigravityDriver: ProviderDriver< ), ); const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel)); + const maxRuntimeAgeBeforeTurn = antigravityMaxRuntimeAgeBeforeTurn(auth); const orchestrationAdapter = yield* makeAntigravityAdapterV2({ instanceId, selfInvocation, @@ -832,6 +844,7 @@ export const AntigravityDriver: ProviderDriver< ), ), profileDirectory, + ...(maxRuntimeAgeBeforeTurn === undefined ? {} : { maxRuntimeAgeBeforeTurn }), onSessionStarted: (started, cwd, session) => provider .onSessionStarted(started, cwd, session) diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 35a5107987c78..4622c2380f3ef 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -150,7 +150,7 @@ describe("watchAntigravityPromptOutcome", () => { const turn = ( steps: ReadonlyArray, result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" }, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) => Effect.gen(function* () { const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId); @@ -451,6 +451,53 @@ describe("watchAntigravityPromptOutcome", () => { retryable: true, }), ); + // After 60 minutes in Agent Platform ADC mode, agy's OAuth refresh fails with + // context canceled and resolves session/prompt with only USER_INPUT and no output. + assert.deepEqual( + yield* turn([[USER_INPUT, input]], { stopReason: "end_turn" }, { receivedOutput: false }), + reusable({ + class: "provider_error", + message: + "Antigravity ended the turn without contacting the model. T3 Code will restart the agent; send your message again to continue.", + code: null, + retryable: true, + }), + ); + // Local replies, reported usage, inactivity-retired prompts, and steers after a + // model reply must not trip the silent-drop check. + assert.isUndefined( + yield* turn([[USER_INPUT, input]], { stopReason: "end_turn" }, { receivedOutput: true }), + ); + assert.isUndefined( + yield* turn( + [[USER_INPUT, input]], + { + stopReason: "end_turn", + usage: { inputTokens: 10, outputTokens: 2, totalTokens: 12 }, + }, + { receivedOutput: false }, + ), + ); + assert.isUndefined( + yield* turn( + [[USER_INPUT, input]], + { stopReason: "end_turn" }, + { retired: true, receivedOutput: false }, + ), + ); + assert.isUndefined( + yield* steered( + [ + [USER_INPUT, input], + [PLANNER_RESPONSE, reply], + ], + [[USER_INPUT, input]], + ), + ); + assert.equal( + (yield* steered([[USER_INPUT, input]], [[USER_INPUT, input]]))?.failure.retryable, + true, + ); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 9a89fae12648b..fef991187b7c8 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -13,6 +13,8 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; +// CORTEX_STEP_TYPE_USER_INPUT: the prompt was recorded before model execution. +const USER_INPUT_STEP_TYPE = 14; // CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory. const ERROR_STEP_TYPE = 17; // CORTEX_STEP_TYPE_PLANNER_RESPONSE: the model answered within this turn. @@ -209,9 +211,10 @@ function verificationErrorInfo(text: string) { } function turnFailure( - stopReason: EffectAcpSchema.StopReason, + result: EffectAcpSchema.PromptResponse, step: LastStep | undefined, now: DateTime.Utc | undefined, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ): | { readonly failure: OrchestrationV2ProviderFailure; @@ -219,16 +222,37 @@ function turnFailure( readonly resumeWith?: string; } | undefined { + const { stopReason } = result; const errorText = step?.type === ERROR_STEP_TYPE ? new TextDecoder().decode(step.payload ?? new Uint8Array()) : undefined; + const reusable = (failure: OrchestrationV2ProviderFailure) => + ({ failure, threadDisposition: "reusable" }) as const; + // After ~60m in Agent Platform ADC mode, agy's OAuth refresh fails with context canceled + // and session/prompt resolves cleanly with only USER_INPUT recorded and no model output. + if ( + errorText === undefined && + options?.retired !== true && + options?.receivedOutput !== true && + stopReason === "end_turn" && + result.usage == null && + step?.type === USER_INPUT_STEP_TYPE && + !step.reachedModel + ) { + return reusable( + makeProviderFailure({ + class: "provider_error", + message: + "Antigravity ended the turn without contacting the model. T3 Code will restart the agent; send your message again to continue.", + retryable: true, + }), + ); + } // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`. if (errorText === undefined && stopReason !== "refusal") return undefined; const text = errorText ?? ""; const apiError = API_ERROR.exec(text) ?? statusError(text); - const reusable = (failure: OrchestrationV2ProviderFailure) => - ({ failure, threadDisposition: "reusable" }) as const; if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) { return reusable( makeProviderFailure({ @@ -292,7 +316,7 @@ const conversationSegments = ["antigravity-acp", "conversations"]; type PromptOutcomeCheck = ( result: EffectAcpSchema.PromptResponse, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) => Effect.Effect | "completed">; interface PromptBaseline { @@ -316,8 +340,8 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w sessionId: string, turnStart?: PromptOutcomeCheck, ) { - const typedOnly: PromptOutcomeCheck = (result) => - DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now))); + const typedOnly: PromptOutcomeCheck = (result, options) => + DateTime.now.pipe(Effect.map((now) => turnFailure(result, undefined, now, options))); if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly; const segments = [...conversationSegments, `${sessionId}.db`]; const before = yield* Effect.tryPromise({ @@ -369,7 +393,7 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w : startIndex; const check: PromptOutcomeCheck = Effect.fn("AntigravityTurnOutcome.check")(function* ( result: EffectAcpSchema.PromptResponse, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) { // The same file as before the prompt, or one this prompt created, still unlinked. const after = yield* Effect.tryPromise({ @@ -391,7 +415,7 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w // A retired prompt's check runs long after the error, so a relative delay has no anchor. const retired = options?.retired === true; const now = retired ? undefined : yield* DateTime.now; - const failure = turnFailure(result.stopReason, step, now); + const failure = turnFailure(result, step, now, options); // The reply finished but session/prompt never answered. const finished = retired && diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index be375b5f782df..fd0567a8f0f9d 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -451,7 +451,7 @@ interface AcpPromptOutcomeFailure { type AcpPromptOutcomeCheck = ( result: EffectAcpSchema.PromptResponse, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) => Effect.Effect; export interface AcpAdapterV2Flavor { @@ -816,6 +816,11 @@ export interface AcpAdapterV2Flavor { * agent request, tool or subagent is open, and replaces the agent before the next turn. */ readonly promptInactivityTimeout?: Duration.Input; + /** + * Recycles the live ACP runtime before starting a new turn once its uptime reaches this age, + * provided the agent can resume sessions and no background work or wake traffic is pending. + */ + readonly maxRuntimeAgeBeforeTurn?: 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. */ @@ -2122,6 +2127,8 @@ interface ActiveAcpTurn { promptSequence: number; /** The turn already resent a prompt after a resumable outcome failure. */ outcomeResumed: boolean; + /** Whether the current prompt received any model/tool/plan output update. */ + promptReceivedOutput: boolean; /** Clock millis just before `session/prompt` was handed to the runtime. */ promptSentAt: number | null; /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */ @@ -3090,6 +3097,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.compactSession !== undefined || flavor.compactViaAdvertisedCommand === true; const runtimeRestartRequired = yield* Ref.make(false); + const runtimeStartedAt = yield* Ref.make(null); const runtimeTeardownState = yield* Ref.make({ _tag: "Idle" }); const runtimeCallbackGeneration = yield* Ref.make(0); const runtimeCallbackGenerationCounter = yield* Ref.make(0); @@ -3563,6 +3571,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.promptInactivityTimeout === undefined ? undefined : Duration.toMillis(flavor.promptInactivityTimeout); + const maxRuntimeAgeBeforeTurnMillis = + flavor.maxRuntimeAgeBeforeTurn === undefined + ? undefined + : Duration.toMillis(flavor.maxRuntimeAgeBeforeTurn); // Each runtime owns its unanswered agent requests, so a dead process's leftovers // and late callbacks never reach its replacement. let openAgentRequests = new Set(); @@ -7854,14 +7866,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return; } - if ( - update.sessionUpdate !== "tool_call_update" && - update.sessionUpdate !== "plan" && - update.sessionUpdate !== "plan_update" && - update.sessionUpdate !== "plan_removed" && - acpRootSessionUpdateIngestsOutput(notification) - ) { - yield* emitProviderRetry(context, "completed"); + if (acpRootSessionUpdateIngestsOutput(notification)) { + context.promptReceivedOutput = true; + if ( + update.sessionUpdate !== "tool_call_update" && + update.sessionUpdate !== "plan" && + update.sessionUpdate !== "plan_update" && + update.sessionUpdate !== "plan_removed" + ) { + yield* emitProviderRetry(context, "completed"); + } } yield* applySteerBoundaryUpdate(context, notification); if ( @@ -9578,6 +9592,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.provideService(AgentScope, agentScope), Effect.provideService(AgentScopeThreadId, threadId ?? undefined), ); + yield* Ref.set(runtimeStartedAt, yield* Clock.currentTimeMillis); }); const startAcpRuntime = Effect.fnUntraced(function* ( @@ -9714,6 +9729,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeScope = replacementScope; runtimeMcpBridge = replacementMcpBridge; openAgentRequests = replacementAgentRequests; + yield* Ref.set(runtimeStartedAt, yield* Clock.currentTimeMillis); yield* Ref.set(runtimeCallbackGeneration, replacementGeneration); prepareTerminalEnvironment( yield* readMcpContext(threadId), @@ -11055,14 +11071,101 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartRuntimeAfterTeardownIfRequired = Effect.fnUntraced(function* ( threadId: ThreadId | null, + resumeSessionId?: string, ) { const restartRequired = yield* Ref.get(runtimeRestartRequired); - if (!restartRequired) return false; + if (!restartRequired) return undefined; + if (resumeSessionId !== undefined && canResumeSession) { + const initialFailure = yield* Ref.modify(initialSessionActivationFailure, (failure) => + failure?.sessionId === resumeSessionId ? [failure.error, null] : [undefined, failure], + ); + if (initialFailure !== undefined) { + return yield* initialFailure; + } + const mcpContext = yield* readMcpContext(threadId); + prepareTerminalEnvironment(mcpContext, resumeSessionId); + const previousSnapshot = + (yield* Ref.get(activeSessionId)) === resumeSessionId + ? yield* Ref.get(snapshot) + : undefined; + // Clear before start so a load-capable resume starts from a clean replay slate; + // if a same-session resume sends no replay (e.g. resumeMethod: "resume"), restore + // the cached snapshot afterward. + yield* Ref.set(snapshot, emptySnapshotState()); + yield* reportStartupPhase("launch"); + yield* reportStartupPhase("resume"); + const activated = yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + // Fence off the old runtime and clear the marker before spawning so a + // termination of the new runtime during startup or drain stays recorded. + yield* runtimeCallbackPermit.withPermit( + Effect.andThen( + advanceRuntimeCallbackGeneration, + Ref.set(runtimeRestartRequired, false), + ), + ); + return yield* restore( + startAcpRuntime(threadId, resumeSessionId).pipe( + Effect.tap(() => runtime.drainEvents), + ), + ).pipe( + Effect.onExit((exit) => + Exit.isSuccess(exit) + ? Effect.void + : Effect.gen(function* () { + yield* Ref.set(runtimeRestartRequired, true); + if (previousSnapshot !== undefined) { + yield* Ref.set(snapshot, previousSnapshot); + } + yield* reportStartupPhase(undefined); + }), + ), + ); + }), + ); + if ( + previousSnapshot !== undefined && + activated.sessionId === resumeSessionId && + (yield* Ref.get(snapshot)).order.length === 0 + ) { + yield* Ref.set(snapshot, previousSnapshot); + } + yield* reportStartupPhase(undefined); + yield* Ref.set(activeSessionId, activated.sessionId); + yield* Ref.set(loadingSessionId, null); + yield* setActiveSessionSetup(activated); + rememberTerminalEnvironment(activated.sessionId, yield* readMcpContext(threadId)); + yield* resetPublishedCatalogKey; + yield* Ref.set(activeSelection, null); + yield* Ref.set(activeInteractionMode, null); + // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again. + yield* Ref.set(promptInstructionStates, new Map()); + yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); + yield* Ref.set(compactionMarkers, new Map()); + yield* Ref.set(completedCompactionIds, new Set()); + return { restarted: true as const, activated }; + } yield* reportStartupPhase("launch"); - yield* restartAcpRuntime(threadId).pipe( - Effect.onError(() => reportStartupPhase(undefined)), + yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + yield* runtimeCallbackPermit.withPermit( + Effect.andThen( + advanceRuntimeCallbackGeneration, + Ref.set(runtimeRestartRequired, false), + ), + ); + yield* restore(restartAcpRuntime(threadId)).pipe( + Effect.onExit((exit) => + Exit.isSuccess(exit) + ? Effect.void + : Ref.set(runtimeRestartRequired, true).pipe( + Effect.andThen(reportStartupPhase(undefined)), + ), + ), + ); + }), ); - yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); yield* Ref.set(activeSessionSetup, null); yield* resetPublishedCatalogKey; @@ -11075,7 +11178,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); - return true; + return { restarted: true as const, activated: undefined }; }); const commitAcpAppContext = Effect.fnUntraced(function* (input: { @@ -11221,7 +11324,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( result.stopReason === "error" || result.stopReason === "cancelled" ? undefined - : yield* settle.checkPromptOutcome(result); + : yield* settle.checkPromptOutcome(result, { + receivedOutput: context.promptReceivedOutput, + }); const hiddenFailure = outcome === "completed" ? undefined : outcome; const resumeWith = hiddenFailure?.resumeWith; if ( @@ -11418,12 +11523,99 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // load/resume can invoke client methods; install the incoming policy before activation. latestRuntimePolicy = turnInput.runtimePolicy; const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); - const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( + if ( + maxRuntimeAgeBeforeTurnMillis !== undefined && + (canLoadSession || canResumeSession) && + !(yield* Ref.get(runtimeRestartRequired)) && + !acpIsProviderContinuationMessage(turnInput.message) + ) { + yield* runtimeCallbackPermit.withPermit( + continuationPermit.withPermit( + Effect.gen(function* () { + const startedAtMillis = yield* Ref.get(runtimeStartedAt); + if ( + startedAtMillis === null || + (yield* Clock.currentTimeMillis) - startedAtMillis < + maxRuntimeAgeBeforeTurnMillis + ) { + return; + } + const hasIdleOutlivingSubagents = [...idleOutlivingSubagents.values()].some( + (entries) => entries.size > 0, + ); + const hasActiveDetachedBackgroundCommands = [ + ...(yield* Ref.get(detachedBackgroundCommands)), + ].some(([taskId, turn]) => { + const toolCallId = turn.toolCallIdsByBackgroundTaskId.get(taskId); + const tool = + toolCallId === undefined ? undefined : turn.tools.get(toolCallId); + const status = tool === undefined ? "completed" : toolStatus(tool.status); + return status === "pending" || status === "running"; + }); + const hasActiveDetachedUnawaitedTools = [ + ...(yield* Ref.get(detachedUnawaitedTools)), + ].some(([toolCallId, turn]) => { + const tool = turn.tools.get(toolCallId); + const status = tool === undefined ? "completed" : toolStatus(tool.status); + return status === "pending" || status === "running"; + }); + const carryover = yield* Ref.get(carryoverSubagents); + const hasActiveCarryoverSubagents = + carryover !== null && + carryover.subagents.some( + (subagent) => + !acpSubagentStatusIsTerminal(subagent.task.status) || + !subagent.terminalStatusProjected, + ); + const isIdleInMemory = + !(yield* Ref.get(continuationRequested)) && + (yield* Ref.get(wakeBuffer)).length === 0 && + (yield* Ref.get(runningBackgroundTaskIds)).size === 0 && + agentRequests.size === 0 && + !hasActiveDetachedBackgroundCommands && + !hasActiveDetachedUnawaitedTools && + !hasActiveCarryoverSubagents && + !hasIdleOutlivingSubagents; + if (!isIdleInMemory) { + return; + } + const currentSessionId = yield* Ref.get(activeSessionId); + if ( + currentSessionId !== null && + flavor.hasPendingReply !== undefined && + (yield* flavor.hasPendingReply(currentSessionId)) + ) { + return; + } + // Fence off callbacks from the retiring runtime before leaving the permit + // so no late root wake can be buffered ahead of teardown. + yield* Effect.uninterruptible( + Effect.andThen( + advanceRuntimeCallbackGeneration, + Ref.set(runtimeRestartRequired, true), + ), + ); + }), + ), + ); + } + const restartResult = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, + requestedSessionId, ); + const restarted = restartResult !== undefined; const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; - if (needsSessionActivation) { + restartResult?.activated === undefined && + ((yield* Ref.get(activeSessionId)) !== requestedSessionId || restarted); + if (restartResult?.activated !== undefined) { + yield* configureSession( + restartResult.activated, + turnInput.modelSelection, + turnInput.runtimePolicy, + ); + yield* Ref.set(activeSelection, turnInput.modelSelection); + yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); + } else if (needsSessionActivation) { const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(loadingSessionId, null); @@ -11603,6 +11795,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( foregroundIdle: yield* Deferred.make(), promptSequence: 0, outcomeResumed: false, + promptReceivedOutput: false, promptSentAt: null, promptStarted, promptUsage: undefined, @@ -11949,6 +12142,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const wasPromptSettled = context.promptSettled; context.promptSettled = false; context.promptSettledStatus = null; + context.promptReceivedOutput = false; context.backgroundFinalizeGeneration += 1; context.promptSentAt = yield* Clock.currentTimeMillis; const previousPromptSettled = yield* Deferred.isDone(context.promptWireSettled); @@ -12395,9 +12589,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restorePreviousItemIdentity = Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; }); - const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( - threadInput.providerThread.appThreadId, - ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); + const restartAfterInterrupt = + (yield* restartRuntimeAfterTeardownIfRequired( + threadInput.providerThread.appThreadId, + ).pipe(Effect.tapError(() => restorePreviousItemIdentity))) !== undefined; if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { yield* Ref.set(snapshot, emptySnapshotState()); const activated = yield* activateSession(