diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index e87b96f99046..fca472c6c433 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -17,6 +17,7 @@ import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; +import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; @@ -35,6 +36,7 @@ import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { makeAcpAdapterV2 } from "@t3tools/provider-acp/server/adapter"; import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; @@ -43,6 +45,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter" import { makeTurnInput } from "./AcpAdapterV2.testkit.ts"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { + type AntigravityAdapterV2Options, type AntigravityAdapterV2RuntimeInput, makeAntigravityAcpAdapterFlavor, makeAntigravityAdapterV2, @@ -998,6 +1001,10 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") detachedChildProfile?: string, /** agy 1.5.11 answers a steered prompt once the next one arrives, which runs to `releaseSteer`. */ steering?: { readonly agentVersion: string; readonly holdsFirstPrompt: boolean }, + options?: { + readonly profileDirectory?: string; + readonly initialToolCalls?: ReadonlyArray; + }, ) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -1028,11 +1035,14 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") let terminate: AntigravityAdapterV2RuntimeInput["onTermination"]; const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; const offers: Array = []; + const scheduledFinalizes = yield* Queue.unbounded(); const instanceId = ProviderInstanceId.make("antigravity-wake-test"); const threadId = ThreadId.make("thread-antigravity-wake"); - const adapter = yield* makeAntigravityAdapterV2({ + const selfInvocation = yield* resolveSelfInvocation(); + const profileDirectory = options?.profileDirectory ?? detachedChildProfile; + const adapterOptions: AntigravityAdapterV2Options = { instanceId, - selfInvocation: yield* resolveSelfInvocation(), + selfInvocation, continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, makeRuntime: (input) => { terminate = input.onTermination; @@ -1074,18 +1084,24 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") yield* Deferred.await(releaseSteer); return { stopReason: "end_turn" as const }; } - yield* send( - detachedChildProfile === undefined - ? { sessionUpdate: "tool_call", ...command, status: "in_progress" } - : { - sessionUpdate: "tool_call", - toolCallId: "call_research", - kind: "other", - title: "Run invoke_subagent", - status: "completed", - rawInput: { TypeName: "research", Role: "Researcher", Prompt: "Read it" }, - }, - ); + if (options?.initialToolCalls !== undefined) { + for (const toolUpdate of options.initialToolCalls) { + yield* send(toolUpdate); + } + } else { + yield* send( + detachedChildProfile === undefined + ? { sessionUpdate: "tool_call", ...command, status: "in_progress" } + : { + sessionUpdate: "tool_call", + toolCallId: "call_research", + kind: "other", + title: "Run invoke_subagent", + status: "completed", + rawInput: { TypeName: "research", Role: "Researcher", Prompt: "Read it" }, + }, + ); + } yield* send({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "I'll render once the fetch finishes." }, @@ -1099,8 +1115,28 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }, withProcess: (_stop, task) => task, defaultModel: Effect.undefined, - ...(detachedChildProfile === undefined ? {} : { profileDirectory: detachedChildProfile }), - }); + ...(profileDirectory === undefined ? {} : { profileDirectory }), + }; + const adapter = + options === undefined + ? yield* makeAntigravityAdapterV2(adapterOptions) + : yield* makeAcpAdapterV2({ + instanceId, + flavor: makeAntigravityAcpAdapterFlavor({ + ...adapterOptions, + random: crypto, + fileSystem: yield* FileSystem.FileSystem, + path, + host: yield* ProviderHost.ProviderHost, + }), + selfInvocation, + ...(adapterOptions.continuationRequests === undefined + ? {} + : { continuationRequests: adapterOptions.continuationRequests }), + testHooks: { + onDeferredFinalizeScheduled: (debounce) => Queue.offer(scheduledFinalizes, debounce), + }, + }); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -1183,6 +1219,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") command, usage, offers, + scheduledFinalizes, send, startTurn, until, @@ -1312,6 +1349,310 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // Command 2 finishes during reply 1; agy dequeues command 2 after reply 1's usage_update and + // needs >3 s before streaming reply 2. Wait for reply 2 (bounded by the 2-minute quiet limit), + // but still finalize at 3 s when both commands were batched into reply 1. + it.effect.each([ + { case: "separate second wake", batched: false, stalls: false }, + { case: "batched into one wake reply", batched: true, stalls: false }, + { case: "stalled second wake hits quiet limit", batched: false, stalls: true }, + ])( + "handles two parallel background commands finishing 500 ms apart ($case)", + ({ batched, stalls }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-race-" }); + const generated = (kind: string) => + path.join( + profile, + "antigravity-acp", + "brain", + "mock-session-1", + ".system_generated", + kind, + ); + const writeFile = (directory: string, name: string, body: string) => + fileSystem + .makeDirectory(directory, { recursive: true }) + .pipe(Effect.andThen(fileSystem.writeFileString(path.join(directory, name), body))); + const cmd1 = { + toolCallId: "call_gates", + kind: "execute", + title: "bin/gates back", + rawInput: { CommandLine: "bin/gates back", WaitMsBeforeAsync: 10000 }, + } as const; + const cmd2 = { + toolCallId: "call_tests", + kind: "execute", + title: "bin/session test", + rawInput: { CommandLine: "bin/session test", WaitMsBeforeAsync: 10000 }, + } as const; + const { usage, offers, scheduledFinalizes, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + profileDirectory: profile, + initialToolCalls: [ + { sessionUpdate: "tool_call", ...cmd1, status: "in_progress" }, + { sessionUpdate: "tool_call", ...cmd2, status: "in_progress" }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + + // Command 1 finishes and wakes the model. + yield* writeFile( + generated("messages"), + "msg-1.json", + JSON.stringify({ + id: "msg-1", + priority: "MESSAGE_PRIORITY_HIGH", + sender: "mock-session-1/task-1", + }), + ); + yield* writeFile(generated("messages"), "read.json", JSON.stringify({ "msg-1": true })); + yield* writeFile( + generated("logs"), + "transcript.jsonl", + `${JSON.stringify({ step_index: 1, type: "SYSTEM_MESSAGE", status: "DONE", content: "priority=MESSAGE_PRIORITY_HIGH task-1" })}\n`, + ); + yield* send({ + sessionUpdate: "tool_call_update", + ...cmd1, + status: "completed", + rawOutput: { output: "ok larastan", exit_code: 0 }, + }); + + // 500 ms later, command 2 also finishes while reply 1 is still in flight. + yield* TestClock.adjust("500 millis"); + yield* writeFile( + generated("messages"), + "msg-2.json", + JSON.stringify({ + id: "msg-2", + priority: "MESSAGE_PRIORITY_HIGH", + sender: "mock-session-1/task-2", + }), + ); + yield* send({ + sessionUpdate: "tool_call_update", + ...cmd2, + status: "completed", + rawOutput: { output: "34 passed", exit_code: 0 }, + }); + assert.equal((yield* Queue.takeAll(scheduledFinalizes)).at(-1), "2 minutes"); + + // Reply 1 streams and ends with usage_update #1. + yield* TestClock.adjust("8 seconds"); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { + type: "text", + text: batched ? "gates and tests both passed." : "gates passed; waiting for tests.", + }, + }); + assert.equal((yield* Queue.takeAll(scheduledFinalizes)).at(-1), "2 minutes"); + yield* writeFile( + generated("messages"), + "read.json", + JSON.stringify({ "msg-1": true, "msg-2": true }), + ); + yield* writeFile( + generated("logs"), + "transcript.jsonl", + (batched + ? [ + JSON.stringify({ + step_index: 1, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_HIGH task-1 + task-2", + }), + JSON.stringify({ + step_index: 2, + type: "PLANNER_RESPONSE", + status: "DONE", + content: "gates and tests both passed.", + }), + ] + : [ + JSON.stringify({ + step_index: 1, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_HIGH task-1", + }), + JSON.stringify({ + step_index: 2, + type: "PLANNER_RESPONSE", + status: "DONE", + content: "gates passed; waiting for tests.", + }), + JSON.stringify({ + step_index: 3, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_HIGH task-2", + }), + ] + ).join("\n") + "\n", + ); + yield* send(usage); + assert.equal(yield* Queue.take(scheduledFinalizes), "3000 millis"); + + // Advance past the 3-second debounce. + yield* TestClock.adjust("3 seconds"); + if (batched) { + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.include(JSON.stringify(run), "gates and tests both passed."); + assert.lengthOf(offers, 0); + return; + } + + // Pending wake for command 2 must extend into the 2-minute quiet window before finalizing. + assert.equal(yield* Queue.take(scheduledFinalizes), "2 minutes"); + if (stalls) { + yield* TestClock.adjust("2 minutes"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.lengthOf(offers, 0); + return; + } + + // Reply 2 arrives 6 seconds later (9 seconds after usage_update #1). + yield* TestClock.adjust("6 seconds"); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "All 34 tests passed." }, + }); + assert.equal((yield* Queue.takeAll(scheduledFinalizes)).at(-1), "2 minutes"); + yield* writeFile( + generated("logs"), + "transcript.jsonl", + [ + JSON.stringify({ + step_index: 1, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_HIGH task-1", + }), + JSON.stringify({ + step_index: 2, + type: "PLANNER_RESPONSE", + status: "DONE", + content: "gates passed; waiting for tests.", + }), + JSON.stringify({ + step_index: 3, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_HIGH task-2", + }), + JSON.stringify({ + step_index: 4, + type: "PLANNER_RESPONSE", + status: "DONE", + content: "All 34 tests passed.", + }), + ].join("\n") + "\n", + ); + yield* send(usage); + assert.equal(yield* Queue.take(scheduledFinalizes), "3000 millis"); + yield* TestClock.adjust("3 seconds"); + + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.include( + JSON.stringify(run), + "All 34 tests passed.", + "reply 2 must stay in the same run", + ); + assert.lengthOf(offers, 0, "the open run needs no continuation"); + }).pipe(Effect.provide(layerSession)), + ); + + // A background command can finish while the initial prompt's final reply is still in flight, + // so the tool is already `completed` when session/prompt returns end_turn while its wake sits + // unread in the inbox. + it.effect( + "keeps the run open when a background command finishes before end_turn with an unread wake", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-pre-settle-" }); + const generated = (kind: string) => + path.join( + profile, + "antigravity-acp", + "brain", + "mock-session-1", + ".system_generated", + kind, + ); + const writeFile = (directory: string, name: string, body: string) => + fileSystem + .makeDirectory(directory, { recursive: true }) + .pipe(Effect.andThen(fileSystem.writeFileString(path.join(directory, name), body))); + const cmd = { + toolCallId: "call_mix", + kind: "execute", + title: "python3 voice.py mix", + rawInput: { CommandLine: "python3 voice.py mix", WaitMsBeforeAsync: 10000 }, + } as const; + yield* writeFile( + generated("messages"), + "msg-1.json", + JSON.stringify({ + id: "msg-1", + priority: "MESSAGE_PRIORITY_HIGH", + sender: "mock-session-1/task-1", + }), + ); + const { usage, offers, scheduledFinalizes, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + profileDirectory: profile, + initialToolCalls: [ + { sessionUpdate: "tool_call", ...cmd, status: "in_progress" }, + { + sessionUpdate: "tool_call_update", + ...cmd, + status: "completed", + rawOutput: { output: "mixed.mp4", exit_code: 0 }, + }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + assert.equal(yield* Queue.take(scheduledFinalizes), "2 minutes"); + + yield* TestClock.adjust("9 seconds"); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Mix finished." }, + }); + assert.equal(yield* Queue.take(scheduledFinalizes), "2 minutes"); + yield* writeFile(generated("messages"), "read.json", JSON.stringify({ "msg-1": true })); + yield* writeFile( + generated("logs"), + "transcript.jsonl", + `${JSON.stringify({ step_index: 2, type: "PLANNER_RESPONSE", status: "DONE", content: "Mix finished." })}\n`, + ); + yield* send(usage); + assert.equal(yield* Queue.take(scheduledFinalizes), "3000 millis"); + yield* TestClock.adjust("3 seconds"); + + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.include(JSON.stringify(run), "Mix finished."); + assert.lengthOf(offers, 0); + }).pipe(Effect.provide(layerSession)), + ); + // agy names its background commands `/task-`; the agent passes that to // t3_background_wait, which must not fail since the adapter already holds the run open. it.effect("accepts t3_background_wait for a command it already tracks", () => diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 77ab7136e678..3f629c813b61 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -34,6 +34,7 @@ import { antigravitySubagentLaunches, describeAntigravitySubagentLaunches, readAntigravityChildrenAtWork, + readAntigravityPendingReply, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; @@ -304,6 +305,11 @@ export function makeAntigravityAcpAdapterFlavor( rootSessionId: sessionId, toolCallIds: nativeTaskIds, }), + hasPendingReply: (sessionId: string) => + readAntigravityPendingReply({ + profileDirectory, + sessionId, + }), }), }; } diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index 21783cbae1d3..e0336da84ac6 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -13,6 +13,7 @@ import { describeAntigravitySubagentLaunches, readAntigravityChildrenAtWork, readAntigravityChildWork, + readAntigravityPendingReply, } from "./AntigravityChildWork.ts"; import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts"; import { @@ -570,4 +571,115 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { expect(JSON.stringify(children).length).toBeLessThan(600 * 1024); }), ); + + it.effect( + "detects unread high-priority inbox wakes and trailing waking SYSTEM_MESSAGE steps", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-pending-reply-" }); + const write = (segments: ReadonlyArray, body: string) => { + const file = path.join( + profile, + "antigravity-acp", + "brain", + ROOT, + ".system_generated", + ...segments, + ); + return fs + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe(Effect.andThen(fs.writeFileString(file, body))); + }; + const pending = () => + readAntigravityPendingReply({ profileDirectory: profile, sessionId: ROOT }); + + // Empty profile or invalid session id fails closed. + expect(yield* pending()).toBe(false); + expect( + yield* readAntigravityPendingReply({ profileDirectory: profile, sessionId: "../escape" }), + ).toBe(false); + + // Low-priority unread notices (e.g. cancelled task / server restart) do not wake the agent. + yield* write( + ["messages", "low-1.json"], + JSON.stringify({ id: "low-1", priority: "MESSAGE_PRIORITY_LOW", sender: "system" }), + ); + expect(yield* pending()).toBe(false); + + // An unread high-priority message indicates a queued wake. + yield* write( + ["messages", "high-1.json"], + JSON.stringify({ + id: "high-1", + priority: "MESSAGE_PRIORITY_HIGH", + sender: `${ROOT}/task-1`, + }), + ); + expect(yield* pending()).toBe(true); + + // Once marked read in read.json and followed by a completed PLANNER_RESPONSE, nothing is pending. + yield* write(["messages", "read.json"], JSON.stringify({ "high-1": true })); + yield* write( + ["logs", "transcript.jsonl"], + `${JSON.stringify({ step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", content: "Done." })}\n`, + ); + expect(yield* pending()).toBe(false); + + // A trailing waking SYSTEM_MESSAGE (even past a >64 KiB prefix) means the reply is in flight. + const filler = JSON.stringify({ + step_index: 0, + type: "GENERIC", + status: "DONE", + content: "x".repeat(8_000), + }); + yield* write( + ["logs", "transcript.jsonl"], + `${Array.from({ length: 12 }, () => filler).join("\n")}\n${JSON.stringify({ + step_index: 2, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_HIGH task-2 finished", + })}\n`, + ); + expect(yield* pending()).toBe(true); + + // A low-priority-only trailing SYSTEM_MESSAGE does not hold the turn open. + yield* write( + ["logs", "transcript.jsonl"], + `${JSON.stringify({ + step_index: 3, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: "priority=MESSAGE_PRIORITY_LOW server restart notice", + })}\n`, + ); + expect(yield* pending()).toBe(false); + + // Corrupt read.json fails closed rather than treating messages as unread. + yield* write(["messages", "read.json"], "{not json"); + expect(yield* pending()).toBe(false); + + // Symlinked transcript fails closed. + const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-pending-outside-" }); + const external = path.join(outside, "transcript.jsonl"); + yield* fs.writeFileString( + external, + `${JSON.stringify({ step_index: 4, type: "SYSTEM_MESSAGE", status: "DONE", content: "priority=MESSAGE_PRIORITY_HIGH" })}\n`, + ); + const transcriptPath = path.join( + profile, + "antigravity-acp", + "brain", + ROOT, + ".system_generated", + "logs", + "transcript.jsonl", + ); + yield* fs.remove(transcriptPath); + yield* fs.symlink(external, transcriptPath); + expect(yield* pending()).toBe(false); + }), + ); }); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index 625062b5368b..aa0932cf0f41 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -651,6 +651,131 @@ async function findDetachedInvokeRecord( return matches.length === 1 ? match : undefined; } +const PENDING_REPLY_TAIL_BYTES = 64 * 1024; +const HIGH_PRIORITY_MESSAGE = "MESSAGE_PRIORITY_HIGH"; +const LOW_PRIORITY_MESSAGE = "MESSAGE_PRIORITY_LOW"; + +const decodeReadReceipts = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Boolean)), +); + +const decodeInboxPriorityMessage = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + id: Schema.optional(Schema.String), + priority: Schema.optional(Schema.String), + }), + ), +); + +async function hasUnreadWakingInboxMessage( + profileRoot: string, + sessionId: string, +): Promise { + const directory = ["antigravity-acp", "brain", sessionId, ".system_generated", "messages"]; + const inbox = await antigravityManagedPath(profileRoot, directory, "directory"); + if (inbox === undefined) return false; + const entries = await NodeFSP.readdir(inbox.path).catch(() => undefined); + if (entries === undefined) return false; + const messageNames = entries.filter((name) => name.endsWith(".json") && name !== "read.json"); + if (messageNames.length === 0 || messageNames.length > MAX_MESSAGE_FILES) return false; + let readReceipts: Readonly> = {}; + if (entries.includes("read.json")) { + const receiptFile = await antigravityManagedPath( + profileRoot, + [...directory, "read.json"], + "file", + ); + if (receiptFile === undefined || receiptFile.info.size > MAX_STEP_BYTES) return false; + const rawReceipts = await NodeFSP.readFile(receiptFile.path, "utf8").catch(() => undefined); + if (rawReceipts === undefined) return false; + const decodedReceipts = decodeReadReceipts(rawReceipts); + if (Option.isNone(decodedReceipts)) return false; + readReceipts = decodedReceipts.value; + } + for (const name of messageNames) { + const fileId = name.slice(0, -5); + if (readReceipts[fileId] === true) continue; + const file = await antigravityManagedPath(profileRoot, [...directory, name], "file"); + if (file === undefined || file.info.size > MAX_STEP_BYTES) continue; + const raw = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined); + if (raw === undefined) continue; + const decoded = decodeInboxPriorityMessage(raw); + if (Option.isNone(decoded)) continue; + if (decoded.value.id !== undefined && readReceipts[decoded.value.id] === true) continue; + if (decoded.value.priority === HIGH_PRIORITY_MESSAGE) return true; + } + return false; +} + +async function readLastTranscriptLine( + profileRoot: string, + sessionId: string, +): Promise | undefined> { + const transcript = await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "brain", sessionId, ".system_generated", "logs", "transcript.jsonl"], + "file", + ); + if (transcript === undefined) return undefined; + const handle = await NodeFSP.open( + transcript.path, + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), + ); + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size === 0) return undefined; + for (const byteCap of [PENDING_REPLY_TAIL_BYTES, TRANSCRIPT_BYTE_CAP]) { + const start = Math.max(0, stat.size - byteCap); + const buffer = Buffer.alloc(stat.size - start); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, start); + let end = bytesRead; + while (end > 0 && (buffer[end - 1] === 0x0a || buffer[end - 1] === 0x0d)) { + end -= 1; + } + if (end === 0) { + if (start === 0) return undefined; + continue; + } + const trimmed = buffer.subarray(0, end); + const lastNewline = trimmed.lastIndexOf(0x0a); + if (lastNewline === -1 && start > 0) continue; + const line = trimmed.toString("utf8", lastNewline + 1); + return Option.getOrUndefined(decodeTranscriptLine(line)); + } + return undefined; + } finally { + await handle.close(); + } +} + +/** + * True when `agy` has a high-priority wake queued in the session's inbox or already dequeued as + * the trailing `SYSTEM_MESSAGE` step in `transcript.jsonl` with no `PLANNER_RESPONSE` yet. + * Fails closed when records are missing, linked, or unreadable. + */ +export const readAntigravityPendingReply = Effect.fn("readAntigravityPendingReply")( + function* (input: { readonly profileDirectory: string; readonly sessionId: string }) { + if (!NATIVE_ID.test(input.sessionId)) return false; + const read = async (): Promise => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + if (profileRoot === undefined) return false; + if (await hasUnreadWakingInboxMessage(profileRoot, input.sessionId)) return true; + const lastStep = await readLastTranscriptLine(profileRoot, input.sessionId); + if (lastStep === undefined || lastStep.type !== "SYSTEM_MESSAGE") return false; + return ( + lastStep.content === undefined || + lastStep.content.includes(`priority=${HIGH_PRIORITY_MESSAGE}`) || + !lastStep.content.includes(`priority=${LOW_PRIORITY_MESSAGE}`) + ); + }; + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }).pipe(Effect.orElseSucceed(() => false)); + }, +); + /** * agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them: * a child is done, or waits for guidance, once its message is in the parent's inbox or its record diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index bebb81bfa8e4..9c8e473f2bf8 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -641,6 +641,13 @@ export interface AcpAdapterV2Flavor { * open. A turn that ends on the deferred finalize waits for it instead of the short debounce. */ readonly replyEndsWithUsageUpdate?: boolean; + /** + * True when the agent has a queued wake or in-flight reply that has not streamed yet (for + * example, a second background task finished while the first wake's reply was running). + * Checked before finalizing a settled prompt or its deferred debounce, so the turn waits + * through `ACP_OPEN_REPLY_QUIET_LIMIT` instead of closing early. + */ + readonly hasPendingReply?: (sessionId: string) => Effect.Effect; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -8677,19 +8684,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (hasDeferredBackgroundWork(context)) return; context.backgroundFinalizeGeneration += 1; const generation = context.backgroundFinalizeGeneration; - const debounce = context.replyOpen - ? ACP_OPEN_REPLY_QUIET_LIMIT - : ACP_DEFERRED_FINALIZE_DEBOUNCE; + const replyOpen = context.replyOpen; + const debounce = replyOpen ? ACP_OPEN_REPLY_QUIET_LIMIT : ACP_DEFERRED_FINALIZE_DEBOUNCE; yield* Effect.gen(function* () { yield* Effect.sleep(debounce); - if ( - context.finalized || - context.interrupted || - context.backgroundFinalizeGeneration !== generation - ) { + const stillCurrent = () => + !context.finalized && + !context.interrupted && + context.backgroundFinalizeGeneration === generation && + !hasDeferredBackgroundWork(context); + if (!stillCurrent()) return; + const pendingReply = + !replyOpen && flavor.hasPendingReply !== undefined + ? yield* flavor.hasPendingReply(context.nativeThreadId) + : false; + if (!stillCurrent()) return; + if (pendingReply) { + context.replyOpen = true; + yield* scheduleDeferredFinalize(context); return; } - if (hasDeferredBackgroundWork(context)) return; const status = context.promptSettledStatus ?? "completed"; yield* finalizeTurn(context, status); }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); @@ -9073,12 +9087,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* idleReportedSubagents(context); if (context.finalized) return; - if ( + const deferredBackgroundWork = defersFinalizeForBackgroundWork && !context.interrupted && - hasDeferredBackgroundWork(context) - ) { + hasDeferredBackgroundWork(context); + const pendingReply = + !deferredBackgroundWork && + defersFinalizeForBackgroundWork && + status === "completed" && + !context.interrupted && + flavor.hasPendingReply !== undefined + ? yield* flavor.hasPendingReply(context.nativeThreadId) + : false; + if (context.finalized) return; + if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + if (pendingReply) { + context.replyOpen = true; + yield* scheduleDeferredFinalize(context); + } yield* ( options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void );