@devries-cameron20 / t3code-1 / commits / 12be92d034
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): Antigravity threads keep going after a background command finishes (#38864)

agy ends its prompt while a backgrounded command still runs. When the command finishes, agy starts a reply by itself with no prompt open. T3 Code dropped that output and failed its permission request, so the thread looked stopped. The built-in Antigravity adapter and the registry agy path now continue in a new run, and wait for the reply's closing usage_update instead of the 3 s debounce. T3 tool titles with the "Run mcp_t3-code_<tool>" form are recognized again, so html_render pages show. Takes over #36138, #37485, #30083 and part of #35073. Co-authored-by: Denis Bolba <denisbolba@gmail.com> Co-authored-by: drstrangerujn <343873859@qq.com> Co-authored-by: Vedanta-krit das (Alex Vedmedenko) <vedmalex@gmail.com> Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Theo Browne committed Nov 18, 2026 at 19:04 UTC 12be92d034f3889cfecac077c6bb655632d9074c
7 files changed +524 -21
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+186 -1
@@ -212,6 +212,7 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
212 continuationEnabled = true,
213 agentId: string | Record<string, unknown> = "claude-acp",
214 replacementEntries?: ReadonlyArray<unknown>,
215 + runtimeMode: "approval-required" | "full-access" = "approval-required",
216 ) {
217 const fileSystem = yield* FileSystem.FileSystem;
218 const path = yield* Path.Path;
@@ -292,7 +293,6 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
293 );
294 const threadId = ThreadId.make("thread-claude-lifecycle");
295 const modelSelection = { instanceId, model: "default" } as const;
295 - const runtimeMode = "approval-required";
296 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
297 runtimeMode,
298 interactionMode: "default",
@@ -452,6 +452,191 @@ const claudeUnrelatedChildren = [
452 ];
453
454 describe("AcpRegistryAdapterV2", () => {
455 + it.effect.each([
456 + { commandPath: "/root/.local/bin/agy", offers: 1 },
457 + { commandPath: "C:\\tools\\agy.exe", offers: 1 },
458 + { commandPath: "/opt/bin/other-agent", offers: 0 },
459 + ])("continues late output only for agy ($commandPath)", ({ commandPath, offers }) =>
460 + Effect.gen(function* () {
461 + const gate = makeProviderReplayGate(["wake"]);
462 + const update = (sessionUpdate: Record<string, unknown>) =>
463 + claudeFrames.update(CLAUDE_ROOT_SESSION, sessionUpdate);
464 + const session = yield* openClaudeReplaySession(
465 + [
466 + {
467 + type: "expect_outbound",
468 + frame: { kind: "request", method: "initialize", params: "<any>" },
469 + },
470 + {
471 + type: "emit_inbound",
472 + frame: {
473 + kind: "response",
474 + method: "initialize",
475 + result: {
476 + protocolVersion: 1,
477 + agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" },
478 + agentCapabilities: { loadSession: true },
479 + authMethods: [],
480 + },
481 + },
482 + },
483 + claudeFrames.open[2],
484 + claudeFrames.open[3],
485 + claudeFrames.prompt(1)[0],
486 + {
487 + type: "emit_inbound",
488 + frame: {
489 + kind: "response",
490 + method: "session/prompt",
491 + result: { stopReason: "end_turn" },
492 + },
493 + },
494 + {
495 + ...update({
496 + sessionUpdate: "agent_message_chunk",
497 + content: { type: "text", text: "Background work finished." },
498 + }),
499 + label: "wake",
500 + },
501 + // agy ends each reply with usage_update; this one ends before the continuation run starts.
502 + update({ sessionUpdate: "usage_update", used: 100, size: 1000 }),
503 + claudeMarker("late output received"),
504 + ],
505 + gate,
506 + true,
507 + { source: "local", commandPath, commandArgs: ["acp"] },
508 + );
509 + yield* session.runtime.startTurn(session.turnInput(1));
510 + assert.equal((yield* session.terminal).status, "completed");
511 + gate.release("wake");
512 + yield* session.throughMarker("late output received");
513 + assert.lengthOf(session.offers, offers, "late output must only wake agy");
514 + if (offers === 0) return;
515 + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
516 + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
517 + yield* TestClock.adjust("3 seconds");
518 + const continued = yield* session.until((event) => event.type === "turn.terminal");
519 + assert.include(JSON.stringify(continued), "Background work finished.");
520 + const terminal = continued.at(-1)!;
521 + if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
522 + assert.equal(terminal.status, "completed");
523 + }).pipe(Effect.provide(layerTest)),
524 + );
525 +
526 + it.effect.each(["approval-required", "full-access"] as const)(
527 + "continues an agy permission request after the prompt settles (%s)",
528 + (runtimeMode) =>
529 + Effect.gen(function* () {
530 + const gate = makeProviderReplayGate(["wake", "reply"]);
531 + const session = yield* openClaudeReplaySession(
532 + [
533 + {
534 + type: "expect_outbound",
535 + frame: { kind: "request", method: "initialize", params: "<any>" },
536 + },
537 + {
538 + type: "emit_inbound",
539 + frame: {
540 + kind: "response",
541 + method: "initialize",
542 + result: {
543 + protocolVersion: 1,
544 + agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" },
545 + agentCapabilities: { loadSession: true },
546 + authMethods: [],
547 + },
548 + },
549 + },
550 + claudeFrames.open[2],
551 + claudeFrames.open[3],
552 + claudeFrames.prompt(1)[0],
553 + {
554 + type: "emit_inbound",
555 + frame: {
556 + kind: "response",
557 + method: "session/prompt",
558 + result: { stopReason: "end_turn" },
559 + },
560 + },
561 + {
562 + type: "emit_inbound",
563 + label: "wake",
564 + frame: {
565 + kind: "request",
566 + method: "session/request_permission",
567 + params: {
568 + sessionId: CLAUDE_ROOT_SESSION,
569 + toolCall: {
570 + toolCallId: "late-command",
571 + title: "Run command",
572 + kind: "execute",
573 + status: "pending",
574 + },
575 + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
576 + },
577 + },
578 + },
579 + claudeMarker("late permission received"),
580 + {
581 + type: "expect_outbound",
582 + frame: {
583 + kind: "response",
584 + method: "session/request_permission",
585 + result: { outcome: { outcome: "selected", optionId: "allow" } },
586 + },
587 + },
588 + {
589 + ...claudeFrames.update(CLAUDE_ROOT_SESSION, {
590 + sessionUpdate: "agent_message_chunk",
591 + content: { type: "text", text: "Command approved." },
592 + }),
593 + label: "reply",
594 + },
595 + claudeFrames.update(CLAUDE_ROOT_SESSION, {
596 + sessionUpdate: "usage_update",
597 + used: 100,
598 + size: 1000,
599 + }),
600 + ],
601 + gate,
602 + true,
603 + { source: "local", commandPath: "/root/.local/bin/agy", commandArgs: ["acp"] },
604 + undefined,
605 + runtimeMode,
606 + );
607 + yield* session.runtime.startTurn(session.turnInput(1));
608 + assert.equal((yield* session.terminal).status, "completed");
609 + gate.release("wake");
610 + yield* session.throughMarker("late permission received");
611 + assert.lengthOf(session.offers, 1, "a permission request must offer a continuation");
612 + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
613 + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
614 + if (runtimeMode === "approval-required") {
615 + const events = yield* session.until(
616 + (event) =>
617 + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
618 + );
619 + const request = events.at(-1)!;
620 + if (request.type !== "runtime_request.updated") throw new Error("Missing approval");
621 + yield* TestClock.adjust("5 seconds");
622 + yield* session.runtime.respondToRuntimeRequest({
623 + requestId: request.runtimeRequest.id,
624 + decision: "accept",
625 + });
626 + }
627 + // The model can be silent longer than the finalize debounce before it goes on.
628 + yield* TestClock.adjust("10 seconds");
629 + gate.release("reply");
630 + const output = yield* session.until(
631 + (event) => event.type === "message.updated" && event.message.text === "Command approved.",
632 + );
633 + assert.isTrue(output.some((event) => event.type === "message.updated"));
634 + assert.isFalse(output.some((event) => event.type === "turn.terminal"));
635 + yield* TestClock.adjust("3 seconds");
636 + assert.equal((yield* session.terminal).status, "completed");
637 + }).pipe(Effect.provide(layerTest)),
638 + );
639 +
640 it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => {
641 const limit = new EffectAcpErrors.AcpRequestError({
642 code: -31001,
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+241 -1
@@ -23,9 +23,11 @@ import * as FileSystem from "effect/FileSystem";
23 import * as Fiber from "effect/Fiber";
24 import * as Layer from "effect/Layer";
25 import * as Path from "effect/Path";
26 +import * as Queue from "effect/Queue";
27 import * as Ref from "effect/Ref";
28 import * as Stream from "effect/Stream";
29 import { ChildProcessSpawner } from "effect/process";
30 +import * as TestClock from "effect/testing/TestClock";
31 import type * as EffectAcpSchema from "effect-acp/compat";
32 import * as EffectAcpErrors from "effect-acp/errors";
33
@@ -38,6 +40,7 @@ import { normalizeAntigravitySessionUpdate } from "../../provider/acp/Antigravit
40 import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts";
41 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
42 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
43 +import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
44 import {
45 makeAntigravityAcpAdapterFlavor,
46 makeAntigravityAdapterV2,
@@ -614,6 +617,11 @@ describe("AntigravityAdapterV2 html_render pages", () => {
617 const report = { html: `<table>${rows.join("")}</table>`, title: "Revenue", height: 240 };
618 const failed = { ...report, html: "<p>Revenue</p>" };
619 const errored = { ...report, html: "<p>Revenue error</p>" };
620 + const telemetry = {
621 + html: `<ul>${rows.join("").replaceAll("tr", "li")}</ul>`,
622 + title: "Telemetry",
623 + height: 411,
624 + };
625 const adapter = yield* makeAntigravityAdapterV2({
626 instanceId,
627 selfInvocation: yield* resolveSelfInvocation(),
@@ -730,6 +738,21 @@ describe("AntigravityAdapterV2 html_render pages", () => {
738 status: "completed",
739 rawOutput: "Summary of published",
740 });
741 + // agy 1.5.8 titles the call with its MCP name and completes without any output.
742 + yield* send({
743 + sessionUpdate: "tool_call",
744 + toolCallId: "agy-1.5.8",
745 + title: "Run mcp_t3-code_html_render",
746 + kind: "other",
747 + status: "in_progress",
748 + rawInput: { ...telemetry, toolSummary: "Render telemetry" },
749 + });
750 + yield* mcpSessions.recordHtmlRender(threadId, telemetry, page("agy-1.5.8"));
751 + yield* send({
752 + sessionUpdate: "tool_call_update",
753 + toolCallId: "agy-1.5.8",
754 + status: "completed",
755 + });
756 return { stopReason: "end_turn" as const };
757 }),
758 })),
@@ -855,7 +878,7 @@ describe("AntigravityAdapterV2 html_render pages", () => {
878 ),
879 [page("report"), page("report"), page("replacement"), page("replacement")],
880 );
858 - for (const name of ["failed-retry", "error-retry"]) {
881 + for (const name of ["failed-retry", "error-retry", "agy-1.5.8"]) {
882 assert.deepEqual(tool(name), {
883 status: "completed",
884 toolName: "t3-code.html_render",
@@ -866,6 +889,223 @@ describe("AntigravityAdapterV2 html_render pages", () => {
889 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined);
890 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined);
891 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined);
892 + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined);
893 + }).pipe(Effect.provide(layerSession)),
894 + );
895 +});
896 +
897 +describe("AntigravityAdapterV2 work after the prompt ends", () => {
898 + // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns
899 + // end_turn, the command finishes later, and the agent replies with no prompt open.
900 + it.effect("continues in one run when a finished background command wakes the agent", () =>
901 + Effect.gen(function* () {
902 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
903 + const path = yield* Path.Path;
904 + const crypto = yield* SecureRandom.SecureRandom;
905 + const mockAgentPath = yield* path.fromFileUrl(
906 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
907 + );
908 + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
909 + let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
910 + let requestPermission: Parameters<RuntimeService["handleRequestPermission"]>[0] | undefined;
911 + const send = (update: EffectAcpSchema.SessionUpdate) =>
912 + sessionUpdate === undefined
913 + ? Effect.die("the adapter must handle session updates")
914 + : sessionUpdate(
915 + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }),
916 + );
917 + const command = {
918 + toolCallId: "call_fetch",
919 + kind: "execute",
920 + title: "node fetch_throughput.mjs",
921 + rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 },
922 + } as const;
923 + const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const;
924 + const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
925 + const instanceId = ProviderInstanceId.make("antigravity-wake-test");
926 + const threadId = ThreadId.make("thread-antigravity-wake");
927 + const adapter = yield* makeAntigravityAdapterV2({
928 + instanceId,
929 + selfInvocation: yield* resolveSelfInvocation(),
930 + continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) },
931 + makeRuntime: (input) =>
932 + makeAntigravityAcpRuntime({
933 + ...input,
934 + childProcessSpawner,
935 + spawn: {
936 + command: process.execPath,
937 + args: [mockAgentPath],
938 + cwd: input.cwd,
939 + env: { T3_ACP_ANTIGRAVITY: "1" },
940 + },
941 + }).pipe(
942 + Effect.provideService(SecureRandom.SecureRandom, crypto),
943 + Effect.map((runtime): RuntimeService => ({
944 + ...runtime,
945 + handleSessionUpdate: (handler) =>
946 + Effect.sync(() => {
947 + sessionUpdate = handler;
948 + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
949 + handleRequestPermission: (handler) =>
950 + Effect.sync(() => {
951 + requestPermission = handler;
952 + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))),
953 + prompt: () =>
954 + Effect.gen(function* () {
955 + yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" });
956 + yield* send({
957 + sessionUpdate: "agent_message_chunk",
958 + content: { type: "text", text: "I'll render once the fetch finishes." },
959 + });
960 + yield* send(usage);
961 + return { stopReason: "end_turn" as const };
962 + }),
963 + })),
964 + ),
965 + withProcess: (_stop, task) => task,
966 + defaultModel: Effect.undefined,
967 + });
968 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
969 + runtimeMode: "full-access",
970 + interactionMode: "default",
971 + cwd: process.cwd(),
972 + });
973 + const modelSelection = { instanceId, model: "gemini-test-low" } as const;
974 + const session = yield* adapter.openSession({
975 + threadId,
976 + providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"),
977 + modelSelection,
978 + runtimePolicy,
979 + });
980 + const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
981 + yield* session.events.pipe(
982 + Stream.runForEach((event) => Queue.offer(events, event)),
983 + Effect.forkScoped,
984 + );
985 + const throughTerminal = Effect.gen(function* () {
986 + const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
987 + while (true) {
988 + const event = yield* Queue.take(events);
989 + seen.push(event);
990 + if (event.type === "turn.terminal") return seen;
991 + }
992 + });
993 + const providerThread = yield* session.ensureThread({
994 + threadId,
995 + modelSelection,
996 + runtimePolicy,
997 + });
998 + const now = yield* DateTime.now;
999 + const startTurn = (ordinal: number, continuation: boolean) =>
1000 + session.startTurn({
1001 + appThread: {
1002 + createdBy: "user",
1003 + creationSource: "web",
1004 + id: threadId,
1005 + projectId: ProjectId.make("project-antigravity-wake"),
1006 + title: "Antigravity wake",
1007 + providerInstanceId: instanceId,
1008 + modelSelection,
1009 + runtimeMode: "full-access",
1010 + interactionMode: "default",
1011 + branch: null,
1012 + worktreePath: process.cwd(),
1013 + activeProviderThreadId: providerThread.id,
1014 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1015 + forkedFrom: null,
1016 + createdAt: now,
1017 + updatedAt: now,
1018 + archivedAt: null,
1019 + settledOverride: null,
1020 + settledAt: null,
1021 + lastVisitedAt: null,
1022 + deletedAt: null,
1023 + },
1024 + threadId,
1025 + runId: RunId.make(`run-antigravity-wake-${ordinal}`),
1026 + runOrdinal: ordinal,
1027 + providerTurnOrdinal: ordinal,
1028 + attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`),
1029 + rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`),
1030 + providerThread,
1031 + message: {
1032 + ...(continuation
1033 + ? { createdBy: "agent" as const, creationSource: "provider" as const }
1034 + : { createdBy: "user" as const, creationSource: "web" as const }),
1035 + messageId: MessageId.make(`message-antigravity-wake-${ordinal}`),
1036 + text: "chart the throughput",
1037 + attachments: [],
1038 + },
1039 + modelSelection,
1040 + runtimePolicy,
1041 + });
1042 +
1043 + yield* startTurn(1, false);
1044 + const promptTerminal = (yield* throughTerminal).at(-1);
1045 + assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed");
1046 +
1047 + yield* send({
1048 + sessionUpdate: "tool_call_update",
1049 + ...command,
1050 + status: "completed",
1051 + rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1052 + });
1053 + assert.lengthOf(offers, 1, "the finished command must wake the thread");
1054 + // The agent can ask before the app has started the continuation run.
1055 + const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" };
1056 + const permission = yield* Effect.suspend(() =>
1057 + requestPermission === undefined
1058 + ? Effect.die("the adapter must handle permission requests")
1059 + : requestPermission(
1060 + {
1061 + sessionId: "mock-session-1",
1062 + toolCall: { ...followUp, status: "pending" },
1063 + options: [
1064 + { optionId: "allow", name: "Allow", kind: "allow_once" },
1065 + { optionId: "deny", name: "Deny", kind: "reject_once" },
1066 + ],
1067 + },
1068 + { requestId: "permission-1", method: "session/request_permission" },
1069 + ),
1070 + ).pipe(Effect.forkScoped({ startImmediately: true }));
1071 + yield* offers[0]!.dispatchIfCurrent!(Effect.void);
1072 + yield* startTurn(2, true);
1073 + assert.deepEqual(yield* Fiber.join(permission), {
1074 + outcome: { outcome: "selected", optionId: "allow" },
1075 + });
1076 +
1077 + // The model took 6.7 s to answer the finished command; the run must outlast that silence.
1078 + yield* TestClock.adjust("10 seconds");
1079 + yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" });
1080 + yield* send({
1081 + sessionUpdate: "agent_message_chunk",
1082 + content: { type: "text", text: "Here is the chart." },
1083 + });
1084 + yield* TestClock.adjust("10 seconds");
1085 + yield* send(usage);
1086 + yield* TestClock.adjust("3 seconds");
1087 + const continued = yield* throughTerminal;
1088 + const continuedTerminal = continued.at(-1);
1089 + assert.equal(
1090 + continuedTerminal?.type === "turn.terminal" && continuedTerminal.status,
1091 + "completed",
1092 + );
1093 + assert.isTrue(
1094 + continued.some(
1095 + (event) =>
1096 + event.type === "turn_item.updated" &&
1097 + event.turnItem.type === "assistant_message" &&
1098 + event.turnItem.runId === RunId.make("run-antigravity-wake-2"),
1099 + ),
1100 + "the reply belongs to the continuation run",
1101 + );
1102 + const finished = continued.findLast(
1103 + (event) =>
1104 + event.type === "turn_item.updated" &&
1105 + event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1106 + );
1107 + assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed");
1108 + assert.lengthOf(offers, 1, "one wake is one run");
1109 }).pipe(Effect.provide(layerSession)),
1110 );
1111 });
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+6
@@ -242,6 +242,12 @@ export function makeAntigravityAcpAdapterFlavor(
242 ),
243 // Loading history replays tool calls; resume avoids replay.
244 subagentsIdleOnTurnCompletion: true,
245 + // A finished background command or timer wakes the agent with no prompt open: it streams a
246 + // reply and asks for permissions, and no prompt response ever ends that reply.
247 + enablePostSettleContinuation: true,
248 + deferFinalizeForBackgroundWork: true,
249 + wakeOnDetachedRequest: true,
250 + replyEndsWithUsageUpdate: true,
251 ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }),
252 applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({
253 runtime,
packages/provider-acp-registry/src/server/adapter.ts
+9 -3
@@ -197,6 +197,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
197 const startupKey =
198 options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId;
199 const isDevin = registryAgentId === "devin";
200 + const isAntigravityCli =
201 + options.settings.source === "local" &&
202 + /^agy(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
203 const isOmp =
204 options.settings.source === "local" &&
205 /^omp(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
@@ -252,6 +255,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
255 : AcpProviderCapabilitiesV2,
256 customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
257 compactViaAdvertisedCommand: true,
258 + ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}),
259 promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
260 ...(registryAgentId === "factory-droid"
261 ? { extractElicitationForm: extractDroidElicitationForm }
@@ -290,9 +294,11 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
294 // Hermes replies on the root session when a background process it started exits; no
295 // prompt response follows, so the continuation ends on the deferred-finalize debounce.
296 // Hermes is not in the public registry and may run through a wrapper, so only its
293 - // initialize reply identifies it.
294 - enablePostSettleContinuation: isHermes,
295 - deferFinalizeForBackgroundWork: isHermes,
297 + // initialize reply identifies it. agy does the same and is known by its command.
298 + enablePostSettleContinuation: (initializeResult) =>
299 + isAntigravityCli || isHermes(initializeResult),
300 + deferFinalizeForBackgroundWork: (initializeResult) =>
301 + isAntigravityCli || isHermes(initializeResult),
302 ...(isDevin
303 ? {
304 clientCapabilitiesMeta: {
packages/provider-acp/src/server/adapter.ts
+61 -8
@@ -143,6 +143,8 @@ export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const;
143
144 // Grok summaries can trail hydrated tools by over two seconds; shorter waits split the wake.
145 const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis";
146 +// A model can stay silent this long before the first token of a reply the agent started itself.
147 +const ACP_OPEN_REPLY_QUIET_LIMIT: Duration.Input = "2 minutes";
148 const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second";
149
150 // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject
@@ -586,6 +588,11 @@ export interface AcpAdapterV2Flavor {
588 notification: EffectAcpSchema.SessionNotification,
589 ) => boolean;
590 readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag;
591 + /**
592 + * Every model reply ends with `usage_update`, also the ones the agent starts with no prompt
593 + * open. A turn that ends on the deferred finalize waits for it instead of the short debounce.
594 + */
595 + readonly replyEndsWithUsageUpdate?: boolean;
596 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
597 /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */
598 readonly interruptPromptOnCancel?: boolean;
@@ -618,6 +625,8 @@ export interface AcpAdapterV2Flavor {
625 readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
626 readonly preserveRuntimeOnSettledInterrupt?: boolean;
627 readonly enablePostSettleContinuation?: AcpNegotiatedFlag;
628 + /** A native request after prompt settlement starts a continuation before it is handled. */
629 + readonly wakeOnDetachedRequest?: boolean;
630 /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
631 readonly followAgentWorkState?: boolean;
632 /**
@@ -1554,6 +1563,8 @@ interface ActiveAcpTurn {
1563 readonly promptStarted: Deferred.Deferred<void, never>;
1564 promptUsage: EffectAcpSchema.Usage | undefined;
1565 backgroundFinalizeGeneration: number;
1566 + /** `replyEndsWithUsageUpdate`: output arrived and its closing `usage_update` has not. */
1567 + replyOpen: boolean;
1568 /** The agent's own id for this turn's prompt, from `forkFromTurn.nativeTurnId`. */
1569 nativePromptId: string | undefined;
1570 /** Clock millis of the prompt's last progress, for `promptInactivityTimeout`. */
@@ -4041,6 +4052,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4052 /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text);
4053
4054 const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => {
4055 + if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true;
4056 if (context.awaitingBackgroundHydration.size > 0) return true;
4057 if (context.pendingInjectedReport.size > 0) return true;
4058 for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {
@@ -4052,6 +4064,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4064 const status = toolStatus(tool.status);
4065 if (status === "pending" || status === "running") return true;
4066 }
4067 + // finalizeTurn idles these subagents, so waiting on them would never settle.
4068 + if (flavor.subagentsIdleOnTurnCompletion === true) return false;
4069 for (const subagent of context.subagents.values()) {
4070 if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) {
4071 return true;
@@ -5318,7 +5332,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5332 });
5333
5334 const awaitRequestTurn = Effect.fnUntraced(function* (generation: number) {
5321 - if (!followsAgentWorkState) return true;
5335 + if (
5336 + !followsAgentWorkState &&
5337 + !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest)
5338 + )
5339 + return true;
5340 while (true) {
5341 const waiting = yield* runRuntimeCallbackAtGeneration(
5342 generation,
@@ -5341,7 +5359,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5359 (generation: number) =>
5360 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
5361 Effect.suspend(() =>
5344 - !followsAgentWorkState
5362 + !followsAgentWorkState &&
5363 + !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest)
5364 ? effect
5365 : Effect.acquireUseRelease(
5366 runRuntimeCallbackAtGeneration(
@@ -5360,6 +5379,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5379 if (Option.isSome(token)) agentRequests.delete(token.value);
5380 const context = yield* Ref.get(activeTurn);
5381 if (context !== null) yield* settleIdleWork(context);
5382 + if (context !== null && flavor.wakeOnDetachedRequest) {
5383 + // The agent goes on with its reply once the request is answered.
5384 + if (flavor.replyEndsWithUsageUpdate === true) context.replyOpen = true;
5385 + yield* rearmDeferredFinalize(context);
5386 + }
5387 }),
5388 ).pipe(Effect.asVoid),
5389 ),
@@ -5379,6 +5403,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5403 return;
5404 if (yield* projectAgentTerminalUpdate(notification, context)) return;
5405 if (yield* projectDetachedBackgroundCommand(notification, context)) return;
5406 + if (flavor.replyEndsWithUsageUpdate === true) {
5407 + if (context === null) {
5408 + // A reply can end before its continuation run starts; replay its end with its output.
5409 + if (
5410 + update.sessionUpdate === "usage_update" &&
5411 + (yield* Ref.get(wakeBuffer)).length > 0
5412 + ) {
5413 + yield* Ref.update(wakeBuffer, (current) => [...current, notification]);
5414 + }
5415 + } else if (context.nativeThreadId === notification.sessionId) {
5416 + if (update.sessionUpdate === "usage_update") {
5417 + context.replyOpen = false;
5418 + yield* rearmDeferredFinalize(context);
5419 + } else if (acpRootSessionUpdateIngestsOutput(notification)) {
5420 + context.replyOpen = true;
5421 + }
5422 + }
5423 + }
5424 if (
5425 update.sessionUpdate === "usage_update" ||
5426 update.sessionUpdate === "session_info_update"
@@ -6924,6 +6966,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6966 }
6967 yield* targetRuntime.handleRequestPermission((nativeParams, requestContext) =>
6968 Effect.gen(function* () {
6969 + if (
6970 + postSettleContinuationEnabled &&
6971 + flavor.wakeOnDetachedRequest &&
6972 + nativeParams.sessionId !== (yield* Ref.get(activeSessionId))
6973 + ) {
6974 + return { outcome: { outcome: "cancelled" } } as const;
6975 + }
6976 const trackedTurn = yield* Ref.get(activeTurn);
6977 const params =
6978 trackedTurn !== null && nativeParams.sessionId === (yield* Ref.get(activeSessionId))
@@ -6961,7 +7010,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7010 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
7011 request: EffectAcpSchema.RequestPermissionRequest = params,
7012 ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request);
6964 - if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") {
7013 + if (
7014 + (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") ||
7015 + (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest)
7016 + ) {
7017 if (!(yield* awaitRequestTurn(handlerGeneration)))
7018 return { outcome: { outcome: "cancelled" } } as const;
7019 }
@@ -8315,8 +8367,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8367 if (hasDeferredBackgroundWork(context)) return;
8368 context.backgroundFinalizeGeneration += 1;
8369 const generation = context.backgroundFinalizeGeneration;
8370 + const debounce = context.replyOpen
8371 + ? ACP_OPEN_REPLY_QUIET_LIMIT
8372 + : ACP_DEFERRED_FINALIZE_DEBOUNCE;
8373 yield* Effect.gen(function* () {
8319 - yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE);
8374 + yield* Effect.sleep(debounce);
8375 if (
8376 context.finalized ||
8377 context.interrupted ||
@@ -8328,10 +8383,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8383 const status = context.promptSettledStatus ?? "completed";
8384 yield* finalizeTurn(context, status);
8385 }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);
8331 - yield* (
8332 - options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ??
8333 - Effect.void
8334 - );
8386 + yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void;
8387 });
8388
8389 const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* (
@@ -8769,6 +8821,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8821 promptStarted,
8822 promptUsage: undefined,
8823 backgroundFinalizeGeneration: 0,
8824 + replyOpen: false,
8825 nativePromptId: undefined,
8826 lastProgressAt: 0,
8827 inactivityWatchdog: undefined,
packages/provider-acp/src/server/runtimeModel.test.ts
+10 -1
@@ -1395,6 +1395,10 @@ describe("extractMcpToolCallIdentity", () => {
1395 // Kimi retitles with partial JSON and middle-truncates args over 50 characters.
1396 'delegate_task: {"mode":"async","task":"Ru',
1397 'delegate_task: {"mode":"async","task":"Ru...cho child-result-42\'"}',
1398 + // Antigravity: "Running <tool>" before agy 1.5.8, "Run mcp_<server>_<tool>" since, "?" on prompts.
1399 + "Running delegate_task",
1400 + "Run mcp_t3-code_delegate_task",
1401 + "Run mcp_t3-code_delegate_task?",
1402 ]) {
1403 const toolCall = toolCallFromUpdate({
1404 sessionUpdate: "tool_call",
@@ -1612,7 +1616,12 @@ describe("extractMcpToolCallIdentity", () => {
1616 });
1617
1618 it("does not brand path-like or unknown-tool titles", () => {
1615 - for (const title of ["t3-code/README.md", "t3-code_not_a_real_tool"]) {
1619 + for (const title of [
1620 + "t3-code/README.md",
1621 + "t3-code_not_a_real_tool",
1622 + "Run mcp_t3-code_not_a_real_tool",
1623 + "Run manage_task",
1624 + ]) {
1625 const toolCall = toolCallFromUpdate({
1626 sessionUpdate: "tool_call",
1627 toolCallId: "path-1",
packages/provider-acp/src/server/runtimeModel.ts
+11 -7
@@ -1088,11 +1088,14 @@ const T3_MCP_TITLE_SUFFIX_CALL =
1088 /^(?<tool>[A-Za-z0-9][A-Za-z0-9_.-]*?)(?: \(t3[-_ ]?code MCP Server\)(?::|$)|[-_.]t3[-_ ]?code$)/i;
1089
1090 /**
1091 - * glm and Kimi use bare names; Antigravity uses "Running <tool>". Kimi appends
1092 - * streamed JSON arguments. Require a name or JSON opening brace so built-ins
1093 - * titled "<tool>: <description>" cannot impersonate an inventory entry.
1091 + * glm and Kimi use bare names. Kimi appends streamed JSON arguments. Require a
1092 + * name or JSON opening brace so built-ins titled "<tool>: <description>" cannot
1093 + * impersonate an inventory entry.
1094 */
1095 -const T3_MCP_BARE_TITLE_CALL = /^(?:Running )?(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
1095 +const T3_MCP_BARE_TITLE_CALL = /^(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
1096 +
1097 +// Antigravity titles calls "Running <tool>" or, from agy 1.5.8, "Run mcp_<server>_<tool>"; prompts end in "?".
1098 +const ANTIGRAVITY_TOOL_TITLE = /^Run(?:ning)? (?<name>[^\s?]+)\??$/;
1099
1100 /** ACP lacks typed MCP calls; recognize provider metadata and terminal fallback commands. */
1101 export function extractMcpToolCallIdentity(
@@ -1185,10 +1188,11 @@ export function extractMcpToolCallIdentity(
1188 }
1189 if (qualified?.[1] && qualified[2] && !/^t3[-_ ]?code$/i.test(qualified[1]))
1190 return { server: qualified[1], tool: qualified[2] };
1191 + const name = ANTIGRAVITY_TOOL_TITLE.exec(trimmed)?.groups?.name ?? trimmed;
1192 const match =
1189 - T3_MCP_TITLE_CALL.exec(trimmed) ??
1190 - T3_MCP_TITLE_SUFFIX_CALL.exec(trimmed) ??
1191 - T3_MCP_BARE_TITLE_CALL.exec(trimmed);
1193 + T3_MCP_TITLE_CALL.exec(name) ??
1194 + T3_MCP_TITLE_SUFFIX_CALL.exec(name) ??
1195 + T3_MCP_BARE_TITLE_CALL.exec(name);
1196 const candidateTool = match?.groups?.tool;
1197 if (candidateTool !== undefined && T3_MCP_TOOL_NAMES.has(candidateTool)) {
1198 return { server: "t3-code", tool: candidateTool };