diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 1c84345c729fa..a532f2ced7704 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -212,6 +212,7 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( continuationEnabled = true, agentId: string | Record = "claude-acp", replacementEntries?: ReadonlyArray, + runtimeMode: "approval-required" | "full-access" = "approval-required", ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -292,7 +293,6 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( ); const threadId = ThreadId.make("thread-claude-lifecycle"); const modelSelection = { instanceId, model: "default" } as const; - const runtimeMode = "approval-required"; const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode, interactionMode: "default", @@ -452,6 +452,191 @@ const claudeUnrelatedChildren = [ ]; describe("AcpRegistryAdapterV2", () => { + it.effect.each([ + { commandPath: "/root/.local/bin/agy", offers: 1 }, + { commandPath: "C:\\tools\\agy.exe", offers: 1 }, + { commandPath: "/opt/bin/other-agent", offers: 0 }, + ])("continues late output only for agy ($commandPath)", ({ commandPath, offers }) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["wake"]); + const update = (sessionUpdate: Record) => + claudeFrames.update(CLAUDE_ROOT_SESSION, sessionUpdate); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }, + }, + }, + claudeFrames.open[2], + claudeFrames.open[3], + claudeFrames.prompt(1)[0], + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + { + ...update({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Background work finished." }, + }), + label: "wake", + }, + // agy ends each reply with usage_update; this one ends before the continuation run starts. + update({ sessionUpdate: "usage_update", used: 100, size: 1000 }), + claudeMarker("late output received"), + ], + gate, + true, + { source: "local", commandPath, commandArgs: ["acp"] }, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("wake"); + yield* session.throughMarker("late output received"); + assert.lengthOf(session.offers, offers, "late output must only wake agy"); + if (offers === 0) return; + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + yield* TestClock.adjust("3 seconds"); + const continued = yield* session.until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(continued), "Background work finished."); + const terminal = continued.at(-1)!; + if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal"); + assert.equal(terminal.status, "completed"); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each(["approval-required", "full-access"] as const)( + "continues an agy permission request after the prompt settles (%s)", + (runtimeMode) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["wake", "reply"]); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }, + }, + }, + claudeFrames.open[2], + claudeFrames.open[3], + claudeFrames.prompt(1)[0], + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + { + type: "emit_inbound", + label: "wake", + frame: { + kind: "request", + method: "session/request_permission", + params: { + sessionId: CLAUDE_ROOT_SESSION, + toolCall: { + toolCallId: "late-command", + title: "Run command", + kind: "execute", + status: "pending", + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }, + }, + }, + claudeMarker("late permission received"), + { + type: "expect_outbound", + frame: { + kind: "response", + method: "session/request_permission", + result: { outcome: { outcome: "selected", optionId: "allow" } }, + }, + }, + { + ...claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Command approved." }, + }), + label: "reply", + }, + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "usage_update", + used: 100, + size: 1000, + }), + ], + gate, + true, + { source: "local", commandPath: "/root/.local/bin/agy", commandArgs: ["acp"] }, + undefined, + runtimeMode, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("wake"); + yield* session.throughMarker("late permission received"); + assert.lengthOf(session.offers, 1, "a permission request must offer a continuation"); + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + if (runtimeMode === "approval-required") { + const events = yield* session.until( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + ); + const request = events.at(-1)!; + if (request.type !== "runtime_request.updated") throw new Error("Missing approval"); + yield* TestClock.adjust("5 seconds"); + yield* session.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + decision: "accept", + }); + } + // The model can be silent longer than the finalize debounce before it goes on. + yield* TestClock.adjust("10 seconds"); + gate.release("reply"); + const output = yield* session.until( + (event) => event.type === "message.updated" && event.message.text === "Command approved.", + ); + assert.isTrue(output.some((event) => event.type === "message.updated")); + assert.isFalse(output.some((event) => event.type === "turn.terminal")); + yield* TestClock.adjust("3 seconds"); + assert.equal((yield* session.terminal).status, "completed"); + }).pipe(Effect.provide(layerTest)), + ); + it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => { const limit = new EffectAcpErrors.AcpRequestError({ code: -31001, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b281ecc16ab84..5e3a971dba1c9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -23,9 +23,11 @@ import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; +import * as TestClock from "effect/testing/TestClock"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as EffectAcpErrors from "effect-acp/errors"; @@ -38,6 +40,7 @@ import { normalizeAntigravitySessionUpdate } from "../../provider/acp/Antigravit import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { makeAntigravityAcpAdapterFlavor, makeAntigravityAdapterV2, @@ -614,6 +617,11 @@ describe("AntigravityAdapterV2 html_render pages", () => { const report = { html: `${rows.join("")}
`, title: "Revenue", height: 240 }; const failed = { ...report, html: "

Revenue

" }; const errored = { ...report, html: "

Revenue error

" }; + const telemetry = { + html: `
    ${rows.join("").replaceAll("tr", "li")}
`, + title: "Telemetry", + height: 411, + }; const adapter = yield* makeAntigravityAdapterV2({ instanceId, selfInvocation: yield* resolveSelfInvocation(), @@ -730,6 +738,21 @@ describe("AntigravityAdapterV2 html_render pages", () => { status: "completed", rawOutput: "Summary of published", }); + // agy 1.5.8 titles the call with its MCP name and completes without any output. + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "agy-1.5.8", + title: "Run mcp_t3-code_html_render", + kind: "other", + status: "in_progress", + rawInput: { ...telemetry, toolSummary: "Render telemetry" }, + }); + yield* mcpSessions.recordHtmlRender(threadId, telemetry, page("agy-1.5.8")); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "agy-1.5.8", + status: "completed", + }); return { stopReason: "end_turn" as const }; }), })), @@ -855,7 +878,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { ), [page("report"), page("report"), page("replacement"), page("replacement")], ); - for (const name of ["failed-retry", "error-retry"]) { + for (const name of ["failed-retry", "error-retry", "agy-1.5.8"]) { assert.deepEqual(tool(name), { status: "completed", toolName: "t3-code.html_render", @@ -866,6 +889,223 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined); + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); + }).pipe(Effect.provide(layerSession)), + ); +}); + +describe("AntigravityAdapterV2 work after the prompt ends", () => { + // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns + // end_turn, the command finishes later, and the agent replies with no prompt open. + it.effect("continues in one run when a finished background command wakes the agent", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let requestPermission: Parameters[0] | undefined; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + const command = { + toolCallId: "call_fetch", + kind: "execute", + title: "node fetch_throughput.mjs", + rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 }, + } as const; + const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; + const offers: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-wake-test"); + const threadId = ThreadId.make("thread-antigravity-wake"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, + makeRuntime: (input) => + 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))), + handleRequestPermission: (handler) => + Effect.sync(() => { + requestPermission = handler; + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), + prompt: () => + Effect.gen(function* () { + yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "I'll render once the fetch finishes." }, + }); + yield* send(usage); + return { stopReason: "end_turn" as const }; + }), + })), + ), + 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-wake"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const throughTerminal = Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (event.type === "turn.terminal") return seen; + } + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const startTurn = (ordinal: number, continuation: boolean) => + session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-wake"), + title: "Antigravity wake", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-antigravity-wake-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`), + providerThread, + message: { + ...(continuation + ? { createdBy: "agent" as const, creationSource: "provider" as const } + : { createdBy: "user" as const, creationSource: "web" as const }), + messageId: MessageId.make(`message-antigravity-wake-${ordinal}`), + text: "chart the throughput", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + yield* startTurn(1, false); + const promptTerminal = (yield* throughTerminal).at(-1); + assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed"); + + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + assert.lengthOf(offers, 1, "the finished command must wake the thread"); + // The agent can ask before the app has started the continuation run. + const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" }; + const permission = yield* Effect.suspend(() => + requestPermission === undefined + ? Effect.die("the adapter must handle permission requests") + : requestPermission( + { + sessionId: "mock-session-1", + toolCall: { ...followUp, status: "pending" }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-1", method: "session/request_permission" }, + ), + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* offers[0]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(2, true); + assert.deepEqual(yield* Fiber.join(permission), { + outcome: { outcome: "selected", optionId: "allow" }, + }); + + // The model took 6.7 s to answer the finished command; the run must outlast that silence. + yield* TestClock.adjust("10 seconds"); + yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* TestClock.adjust("10 seconds"); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const continued = yield* throughTerminal; + const continuedTerminal = continued.at(-1); + assert.equal( + continuedTerminal?.type === "turn.terminal" && continuedTerminal.status, + "completed", + ); + assert.isTrue( + continued.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.runId === RunId.make("run-antigravity-wake-2"), + ), + "the reply belongs to the continuation run", + ); + const finished = continued.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed"); + assert.lengthOf(offers, 1, "one wake is one run"); }).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 8566cbb83f9e9..b91f1a452679d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -242,6 +242,12 @@ export function makeAntigravityAcpAdapterFlavor( ), // Loading history replays tool calls; resume avoids replay. subagentsIdleOnTurnCompletion: true, + // A finished background command or timer wakes the agent with no prompt open: it streams a + // reply and asks for permissions, and no prompt response ever ends that reply. + enablePostSettleContinuation: true, + deferFinalizeForBackgroundWork: true, + wakeOnDetachedRequest: true, + replyEndsWithUsageUpdate: true, ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({ runtime, diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8f133f619cea3..ce5a2b94531c4 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -197,6 +197,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu const startupKey = options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId; const isDevin = registryAgentId === "devin"; + const isAntigravityCli = + options.settings.source === "local" && + /^agy(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); const isOmp = options.settings.source === "local" && /^omp(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); @@ -252,6 +255,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : AcpProviderCapabilitiesV2, customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug), compactViaAdvertisedCommand: true, + ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}), promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause), ...(registryAgentId === "factory-droid" ? { extractElicitationForm: extractDroidElicitationForm } @@ -290,9 +294,11 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu // Hermes replies on the root session when a background process it started exits; no // prompt response follows, so the continuation ends on the deferred-finalize debounce. // Hermes is not in the public registry and may run through a wrapper, so only its - // initialize reply identifies it. - enablePostSettleContinuation: isHermes, - deferFinalizeForBackgroundWork: isHermes, + // initialize reply identifies it. agy does the same and is known by its command. + enablePostSettleContinuation: (initializeResult) => + isAntigravityCli || isHermes(initializeResult), + deferFinalizeForBackgroundWork: (initializeResult) => + isAntigravityCli || isHermes(initializeResult), ...(isDevin ? { clientCapabilitiesMeta: { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 23883850a8765..7402b5ec9b0eb 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -143,6 +143,8 @@ export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const; // Grok summaries can trail hydrated tools by over two seconds; shorter waits split the wake. const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis"; +// A model can stay silent this long before the first token of a reply the agent started itself. +const ACP_OPEN_REPLY_QUIET_LIMIT: Duration.Input = "2 minutes"; const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -586,6 +588,11 @@ export interface AcpAdapterV2Flavor { notification: EffectAcpSchema.SessionNotification, ) => boolean; readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag; + /** + * Every model reply ends with `usage_update`, also the ones the agent starts with no prompt + * open. A turn that ends on the deferred finalize waits for it instead of the short debounce. + */ + readonly replyEndsWithUsageUpdate?: boolean; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -618,6 +625,8 @@ export interface AcpAdapterV2Flavor { readonly terminateRuntimeProcessGroupOnInterrupt?: boolean; readonly preserveRuntimeOnSettledInterrupt?: boolean; readonly enablePostSettleContinuation?: AcpNegotiatedFlag; + /** A native request after prompt settlement starts a continuation before it is handled. */ + readonly wakeOnDetachedRequest?: boolean; /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */ readonly followAgentWorkState?: boolean; /** @@ -1554,6 +1563,8 @@ interface ActiveAcpTurn { readonly promptStarted: Deferred.Deferred; promptUsage: EffectAcpSchema.Usage | undefined; backgroundFinalizeGeneration: number; + /** `replyEndsWithUsageUpdate`: output arrived and its closing `usage_update` has not. */ + replyOpen: boolean; /** 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`. */ @@ -4041,6 +4052,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (context.awaitingBackgroundHydration.size > 0) return true; if (context.pendingInjectedReport.size > 0) return true; for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) { @@ -4052,6 +4064,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const status = toolStatus(tool.status); if (status === "pending" || status === "running") return true; } + // finalizeTurn idles these subagents, so waiting on them would never settle. + if (flavor.subagentsIdleOnTurnCompletion === true) return false; for (const subagent of context.subagents.values()) { if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) { return true; @@ -5318,7 +5332,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const awaitRequestTurn = Effect.fnUntraced(function* (generation: number) { - if (!followsAgentWorkState) return true; + if ( + !followsAgentWorkState && + !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) + ) + return true; while (true) { const waiting = yield* runRuntimeCallbackAtGeneration( generation, @@ -5341,7 +5359,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (generation: number) => (effect: Effect.Effect) => Effect.suspend(() => - !followsAgentWorkState + !followsAgentWorkState && + !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) ? effect : Effect.acquireUseRelease( runRuntimeCallbackAtGeneration( @@ -5360,6 +5379,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (Option.isSome(token)) agentRequests.delete(token.value); const context = yield* Ref.get(activeTurn); if (context !== null) yield* settleIdleWork(context); + if (context !== null && flavor.wakeOnDetachedRequest) { + // The agent goes on with its reply once the request is answered. + if (flavor.replyEndsWithUsageUpdate === true) context.replyOpen = true; + yield* rearmDeferredFinalize(context); + } }), ).pipe(Effect.asVoid), ), @@ -5379,6 +5403,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; if (yield* projectAgentTerminalUpdate(notification, context)) return; if (yield* projectDetachedBackgroundCommand(notification, context)) return; + if (flavor.replyEndsWithUsageUpdate === true) { + if (context === null) { + // A reply can end before its continuation run starts; replay its end with its output. + if ( + update.sessionUpdate === "usage_update" && + (yield* Ref.get(wakeBuffer)).length > 0 + ) { + yield* Ref.update(wakeBuffer, (current) => [...current, notification]); + } + } else if (context.nativeThreadId === notification.sessionId) { + if (update.sessionUpdate === "usage_update") { + context.replyOpen = false; + yield* rearmDeferredFinalize(context); + } else if (acpRootSessionUpdateIngestsOutput(notification)) { + context.replyOpen = true; + } + } + } if ( update.sessionUpdate === "usage_update" || update.sessionUpdate === "session_info_update" @@ -6924,6 +6966,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* targetRuntime.handleRequestPermission((nativeParams, requestContext) => Effect.gen(function* () { + if ( + postSettleContinuationEnabled && + flavor.wakeOnDetachedRequest && + nativeParams.sessionId !== (yield* Ref.get(activeSessionId)) + ) { + return { outcome: { outcome: "cancelled" } } as const; + } const trackedTurn = yield* Ref.get(activeTurn); const params = trackedTurn !== null && nativeParams.sessionId === (yield* Ref.get(activeSessionId)) @@ -6961,7 +7010,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest = params, ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); - if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") { + if ( + (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") || + (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) + ) { if (!(yield* awaitRequestTurn(handlerGeneration))) return { outcome: { outcome: "cancelled" } } as const; } @@ -8315,8 +8367,11 @@ 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; yield* Effect.gen(function* () { - yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE); + yield* Effect.sleep(debounce); if ( context.finalized || context.interrupted || @@ -8328,10 +8383,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const status = context.promptSettledStatus ?? "completed"; yield* finalizeTurn(context, status); }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); - yield* ( - options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ?? - Effect.void - ); + yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( @@ -8769,6 +8821,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( promptStarted, promptUsage: undefined, backgroundFinalizeGeneration: 0, + replyOpen: false, nativePromptId: undefined, lastProgressAt: 0, inactivityWatchdog: undefined, diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index b41c95f6466b6..4fb77c4c3cc6c 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1395,6 +1395,10 @@ describe("extractMcpToolCallIdentity", () => { // Kimi retitles with partial JSON and middle-truncates args over 50 characters. 'delegate_task: {"mode":"async","task":"Ru', 'delegate_task: {"mode":"async","task":"Ru...cho child-result-42\'"}', + // Antigravity: "Running " before agy 1.5.8, "Run mcp__" since, "?" on prompts. + "Running delegate_task", + "Run mcp_t3-code_delegate_task", + "Run mcp_t3-code_delegate_task?", ]) { const toolCall = toolCallFromUpdate({ sessionUpdate: "tool_call", @@ -1612,7 +1616,12 @@ describe("extractMcpToolCallIdentity", () => { }); it("does not brand path-like or unknown-tool titles", () => { - for (const title of ["t3-code/README.md", "t3-code_not_a_real_tool"]) { + for (const title of [ + "t3-code/README.md", + "t3-code_not_a_real_tool", + "Run mcp_t3-code_not_a_real_tool", + "Run manage_task", + ]) { const toolCall = toolCallFromUpdate({ sessionUpdate: "tool_call", toolCallId: "path-1", diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 3b936a30b766f..eaf352695e5c0 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1088,11 +1088,14 @@ const T3_MCP_TITLE_SUFFIX_CALL = /^(?[A-Za-z0-9][A-Za-z0-9_.-]*?)(?: \(t3[-_ ]?code MCP Server\)(?::|$)|[-_.]t3[-_ ]?code$)/i; /** - * glm and Kimi use bare names; Antigravity uses "Running ". Kimi appends - * streamed JSON arguments. Require a name or JSON opening brace so built-ins - * titled ": " cannot impersonate an inventory entry. + * glm and Kimi use bare names. Kimi appends streamed JSON arguments. Require a + * name or JSON opening brace so built-ins titled ": " cannot + * impersonate an inventory entry. */ -const T3_MCP_BARE_TITLE_CALL = /^(?:Running )?(?[A-Za-z0-9_]+)(?::\s*\{|$)/; +const T3_MCP_BARE_TITLE_CALL = /^(?[A-Za-z0-9_]+)(?::\s*\{|$)/; + +// Antigravity titles calls "Running " or, from agy 1.5.8, "Run mcp__"; prompts end in "?". +const ANTIGRAVITY_TOOL_TITLE = /^Run(?:ning)? (?[^\s?]+)\??$/; /** ACP lacks typed MCP calls; recognize provider metadata and terminal fallback commands. */ export function extractMcpToolCallIdentity( @@ -1185,10 +1188,11 @@ export function extractMcpToolCallIdentity( } if (qualified?.[1] && qualified[2] && !/^t3[-_ ]?code$/i.test(qualified[1])) return { server: qualified[1], tool: qualified[2] }; + const name = ANTIGRAVITY_TOOL_TITLE.exec(trimmed)?.groups?.name ?? trimmed; const match = - T3_MCP_TITLE_CALL.exec(trimmed) ?? - T3_MCP_TITLE_SUFFIX_CALL.exec(trimmed) ?? - T3_MCP_BARE_TITLE_CALL.exec(trimmed); + T3_MCP_TITLE_CALL.exec(name) ?? + T3_MCP_TITLE_SUFFIX_CALL.exec(name) ?? + T3_MCP_BARE_TITLE_CALL.exec(name); const candidateTool = match?.groups?.tool; if (candidateTool !== undefined && T3_MCP_TOOL_NAMES.has(candidateTool)) { return { server: "t3-code", tool: candidateTool };