@devries-cameron20 / t3code-1 / commits / f9b9bc742d
Fork 0

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

fix(server): Antigravity threads stay working while a background command runs, and Stop ends it (#38916)

agy ends its prompt while a command it backgrounded still runs, and replies by itself when the command finishes. T3 Code ended the run at the prompt, so the thread looked idle and Stop was not offered. The run now stays open until the command ends. A daemon does not hold it. Stop sends session/cancel, which ends the command in agy 1.5.11. A message sent while the command runs does not, so the command keeps running. A held run fails when the agent process exits. The Servers panel no longer lists an agent CLI's own ports. Takes over #35073 and #36585. Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: saphid <4596216+saphid@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Theo Browne committed Nov 18, 2026 at 20:21 UTC f9b9bc742d99cec7c658b75954fdf3c872106b16
6 files changed +382 -191
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+259 -157
@@ -42,6 +42,7 @@ 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 + type AntigravityAdapterV2RuntimeInput,
46 makeAntigravityAcpAdapterFlavor,
47 makeAntigravityAdapterV2,
48 } from "./AntigravityAdapterV2.ts";
@@ -894,152 +895,198 @@ describe("AntigravityAdapterV2 html_render pages", () => {
895 );
896 });
897
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),
898 +/**
899 + * A session whose prompt reports one running command and returns end_turn, as agy 1.5.11 does
900 + * for `run_command` once `WaitMsBeforeAsync` passes. The test sends every later frame.
901 + */
902 +const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")(function* (
903 + commandInput: Record<string, unknown>,
904 +) {
905 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
906 + const path = yield* Path.Path;
907 + const crypto = yield* SecureRandom.SecureRandom;
908 + const mockAgentPath = yield* path.fromFileUrl(
909 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
910 + );
911 + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
912 + let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
913 + let requestPermission: Parameters<RuntimeService["handleRequestPermission"]>[0] | undefined;
914 + const send = (update: EffectAcpSchema.SessionUpdate) =>
915 + sessionUpdate === undefined
916 + ? Effect.die("the adapter must handle session updates")
917 + : sessionUpdate(normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }));
918 + const command = {
919 + toolCallId: "call_fetch",
920 + kind: "execute",
921 + title: "node fetch_throughput.mjs",
922 + rawInput: { CommandLine: "node fetch_throughput.mjs", ...commandInput },
923 + } as const;
924 + let cancels = 0;
925 + let terminate: AntigravityAdapterV2RuntimeInput["onTermination"];
926 + const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const;
927 + const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
928 + const instanceId = ProviderInstanceId.make("antigravity-wake-test");
929 + const threadId = ThreadId.make("thread-antigravity-wake");
930 + const adapter = yield* makeAntigravityAdapterV2({
931 + instanceId,
932 + selfInvocation: yield* resolveSelfInvocation(),
933 + continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) },
934 + makeRuntime: (input) => {
935 + terminate = input.onTermination;
936 + return makeAntigravityAcpRuntime({
937 + ...input,
938 + childProcessSpawner,
939 + spawn: {
940 + command: process.execPath,
941 + args: [mockAgentPath],
942 + cwd: input.cwd,
943 + env: { T3_ACP_ANTIGRAVITY: "1" },
944 + },
945 + }).pipe(
946 + Effect.provideService(SecureRandom.SecureRandom, crypto),
947 + Effect.map((runtime): RuntimeService => ({
948 + ...runtime,
949 + cancel: Effect.sync(() => {
950 + cancels += 1;
951 + }),
952 + handleSessionUpdate: (handler) =>
953 + Effect.sync(() => {
954 + sessionUpdate = handler;
955 + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
956 + handleRequestPermission: (handler) =>
957 + Effect.sync(() => {
958 + requestPermission = handler;
959 + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))),
960 + prompt: () =>
961 + Effect.gen(function* () {
962 + yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" });
963 + yield* send({
964 + sessionUpdate: "agent_message_chunk",
965 + content: { type: "text", text: "I'll render once the fetch finishes." },
966 + });
967 + yield* send(usage);
968 + return { stopReason: "end_turn" as const };
969 + }),
970 + })),
971 );
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({
972 + },
973 + withProcess: (_stop, task) => task,
974 + defaultModel: Effect.undefined,
975 + });
976 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
977 + runtimeMode: "full-access",
978 + interactionMode: "default",
979 + cwd: process.cwd(),
980 + });
981 + const modelSelection = { instanceId, model: "gemini-test-low" } as const;
982 + const session = yield* adapter.openSession({
983 + threadId,
984 + providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"),
985 + modelSelection,
986 + runtimePolicy,
987 + });
988 + const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
989 + yield* session.events.pipe(
990 + Stream.runForEach((event) => Queue.offer(events, event)),
991 + Effect.forkScoped,
992 + );
993 + const until = (done: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) =>
994 + Effect.gen(function* () {
995 + const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
996 + while (true) {
997 + const event = yield* Queue.take(events);
998 + seen.push(event);
999 + if (done(event)) return seen;
1000 + }
1001 + });
1002 + const providerThread = yield* session.ensureThread({
1003 + threadId,
1004 + modelSelection,
1005 + runtimePolicy,
1006 + });
1007 + const now = yield* DateTime.now;
1008 + const startTurn = (ordinal: number, continuation: boolean) =>
1009 + session.startTurn({
1010 + appThread: {
1011 + createdBy: "user",
1012 + creationSource: "web",
1013 + id: threadId,
1014 + projectId: ProjectId.make("project-antigravity-wake"),
1015 + title: "Antigravity wake",
1016 + providerInstanceId: instanceId,
1017 + modelSelection,
1018 runtimeMode: "full-access",
1019 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 - });
1020 + branch: null,
1021 + worktreePath: process.cwd(),
1022 + activeProviderThreadId: providerThread.id,
1023 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1024 + forkedFrom: null,
1025 + createdAt: now,
1026 + updatedAt: now,
1027 + archivedAt: null,
1028 + settledOverride: null,
1029 + settledAt: null,
1030 + lastVisitedAt: null,
1031 + deletedAt: null,
1032 + },
1033 + threadId,
1034 + runId: RunId.make(`run-antigravity-wake-${ordinal}`),
1035 + runOrdinal: ordinal,
1036 + providerTurnOrdinal: ordinal,
1037 + attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`),
1038 + rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`),
1039 + providerThread,
1040 + message: {
1041 + ...(continuation
1042 + ? { createdBy: "agent" as const, creationSource: "provider" as const }
1043 + : { createdBy: "user" as const, creationSource: "web" as const }),
1044 + messageId: MessageId.make(`message-antigravity-wake-${ordinal}`),
1045 + text: "chart the throughput",
1046 + attachments: [],
1047 + },
1048 + modelSelection,
1049 + runtimePolicy,
1050 + });
1051
1052 + return {
1053 + session,
1054 + providerThread,
1055 + command,
1056 + usage,
1057 + offers,
1058 + send,
1059 + startTurn,
1060 + until,
1061 + throughTerminal: until((event) => event.type === "turn.terminal"),
1062 + // The reply before end_turn closes when the prompt settles, held open or not.
1063 + throughPromptSettled: until(
1064 + (event) =>
1065 + event.type === "turn_item.updated" &&
1066 + event.turnItem.type === "assistant_message" &&
1067 + event.turnItem.status === "completed",
1068 + ),
1069 + requestPermission: (...args: Parameters<NonNullable<typeof requestPermission>>) =>
1070 + requestPermission === undefined
1071 + ? Effect.die("the adapter must handle permission requests")
1072 + : requestPermission(...args),
1073 + cancels: () => cancels,
1074 + runtimeDies: Effect.suspend(
1075 + () =>
1076 + terminate?.(
1077 + new EffectAcpErrors.AcpTransportError({ detail: "agent exited", cause: "exit" }),
1078 + ) ?? Effect.die("the adapter must watch its runtime"),
1079 + ),
1080 + };
1081 +});
1082 +
1083 +describe("AntigravityAdapterV2 work after the prompt ends", () => {
1084 + // agy sets `IsDaemon` on a command it does not wait for. When it exits, the agent replies
1085 + // with no prompt open.
1086 + it.effect("continues in one run when a finished daemon wakes the agent", () =>
1087 + Effect.gen(function* () {
1088 + const { command, usage, offers, send, startTurn, throughTerminal, requestPermission } =
1089 + yield* openSessionWithRunningCommand({ IsDaemon: true, WaitMsBeforeAsync: 500 });
1090 yield* startTurn(1, false);
1091 const promptTerminal = (yield* throughTerminal).at(-1);
1092 assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed");
@@ -1050,23 +1097,19 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => {
1097 status: "completed",
1098 rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1099 });
1053 - assert.lengthOf(offers, 1, "the finished command must wake the thread");
1100 + assert.lengthOf(offers, 1, "the finished daemon must wake the thread");
1101 // The agent can ask before the app has started the continuation run.
1102 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 - ),
1103 + const permission = yield* requestPermission(
1104 + {
1105 + sessionId: "mock-session-1",
1106 + toolCall: { ...followUp, status: "pending" },
1107 + options: [
1108 + { optionId: "allow", name: "Allow", kind: "allow_once" },
1109 + { optionId: "deny", name: "Deny", kind: "reject_once" },
1110 + ],
1111 + },
1112 + { requestId: "permission-1", method: "session/request_permission" },
1113 ).pipe(Effect.forkScoped({ startImmediately: true }));
1114 yield* offers[0]!.dispatchIfCurrent!(Effect.void);
1115 yield* startTurn(2, true);
@@ -1108,6 +1151,65 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => {
1151 assert.lengthOf(offers, 1, "one wake is one run");
1152 }).pipe(Effect.provide(layerSession)),
1153 );
1154 +
1155 + // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns
1156 + // end_turn while the command runs, and the agent replies when the command finishes.
1157 + it.effect("keeps the run open while a command the agent waits for still runs", () =>
1158 + Effect.gen(function* () {
1159 + const { command, usage, offers, send, startTurn, until, throughPromptSettled } =
1160 + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 });
1161 + yield* startTurn(1, false);
1162 + yield* throughPromptSettled;
1163 + yield* TestClock.adjust("10 minutes");
1164 + yield* send({
1165 + sessionUpdate: "tool_call_update",
1166 + ...command,
1167 + status: "completed",
1168 + rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1169 + });
1170 + yield* TestClock.adjust("10 seconds");
1171 + yield* send({
1172 + sessionUpdate: "agent_message_chunk",
1173 + content: { type: "text", text: "Here is the chart." },
1174 + });
1175 + yield* send(usage);
1176 + yield* TestClock.adjust("3 seconds");
1177 + const run = yield* until((event) => event.type === "turn.terminal");
1178 + const terminal = run.at(-1);
1179 + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1180 + assert.include(JSON.stringify(run), "Here is the chart.", "the reply is part of the run");
1181 + assert.lengthOf(offers, 0, "the open run needs no continuation");
1182 + }).pipe(Effect.provide(layerSession)),
1183 + );
1184 +
1185 + it.effect.each([
1186 + // session/cancel ends the agent's commands, so only Stop may send it.
1187 + { ending: "Stop", cancels: 1, status: "interrupted" },
1188 + { ending: "a new message", cancels: 0, status: "interrupted" },
1189 + { ending: "the agent exiting", cancels: 0, status: "failed" },
1190 + ] as const)(
1191 + "ends a run held open by a running command on $ending",
1192 + ({ ending, cancels, status }) =>
1193 + Effect.gen(function* () {
1194 + const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 });
1195 + yield* opened.startTurn(1, false);
1196 + const started = yield* opened.throughPromptSettled;
1197 + const turn = started.find((event) => event.type === "provider_turn.updated");
1198 + if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start");
1199 + if (ending === "the agent exiting") {
1200 + yield* opened.runtimeDies;
1201 + } else {
1202 + yield* opened.session.interruptTurn({
1203 + providerThread: opened.providerThread,
1204 + providerTurnId: turn.providerTurn.id,
1205 + ...(ending === "Stop" ? { requestRuntimeRestart: true } : {}),
1206 + });
1207 + }
1208 + const terminal = (yield* opened.throughTerminal).at(-1);
1209 + assert.equal(terminal?.type === "turn.terminal" && terminal.status, status);
1210 + assert.equal(opened.cancels(), cancels);
1211 + }).pipe(Effect.provide(layerSession)),
1212 + );
1213 });
1214
1215 describe("AntigravityAdapterV2 subagent reads", () => {
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+5
@@ -36,6 +36,7 @@ import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityCli
36 import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts";
37 import {
38 antigravityApprovalOptions,
39 + antigravityCommandOutlivesPrompt,
40 antigravitySubagentOutput,
41 classifyAntigravitySubagentToolCall,
42 extractAntigravityUserInputQuestion,
@@ -248,6 +249,10 @@ export function makeAntigravityAcpAdapterFlavor(
249 deferFinalizeForBackgroundWork: true,
250 wakeOnDetachedRequest: true,
251 replyEndsWithUsageUpdate: true,
252 + toolOutlivesPrompt: antigravityCommandOutlivesPrompt,
253 + // session/cancel ends the agent's running commands, so only Stop sends it once the prompt
254 + // has ended. A message sent while a command runs leaves the command alone.
255 + preserveRuntimeOnSettledInterrupt: true,
256 ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }),
257 applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({
258 runtime,
apps/server/src/preview/PortScanner.test.ts
+15 -5
@@ -842,7 +842,9 @@ effectIt.effect.each(["linux", "darwin"] as const)(
842 (platform) => {
843 const agentPort = 43_124;
844 const otherPort = 43_125;
845 - const agentListener = `p4242\ncnode\nn127.0.0.1:${agentPort}\n`;
845 + // The agent CLI has the thread in its environment too; its own port is not a server.
846 + const agentListener =
847 + `p4242\ncnode\nn127.0.0.1:${agentPort}\n` + `p4300\ncagy\nn127.0.0.1:43126\n`;
848 const otherListener = `p5000\ncpostgres\nn127.0.0.1:${otherPort}\n`;
849 let lsofStdout = otherListener;
850 let lsofFails = false;
@@ -855,11 +857,18 @@ effectIt.effect.each(["linux", "darwin"] as const)(
857 "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`,
858 "/proc/5000/environ": "PATH=/usr/bin\0",
859 };
860 + const procAgent: Record<string, string> = {
861 + "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0",
862 + "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`,
863 + "/proc/4300/stat": `4300 (agy acp) S ${process.pid} 4300 4300 0`,
864 + };
865 const layer = layerScanner.pipe(
866 Layer.provide(
867 Layer.mergeAll(
868 FileSystem.layerNoop({
869 readFileString: (path) => {
870 + const agent = procAgent[path];
871 + if (agent !== undefined) return Effect.succeed(agent);
872 const content = procEnviron[path];
873 if (content === undefined) return missing.readFileString(path);
874 environmentReads += 1;
@@ -881,9 +890,9 @@ effectIt.effect.each(["linux", "darwin"] as const)(
890 )
891 : Effect.succeed(processOutput(lsofStdout));
892 }
884 - // A direct child of this process, so stop refuses it without signaling anything.
893 + // In its agent CLI's process group, so stop refuses it without signaling anything.
894 if (input.args[0] === "-A") {
886 - return Effect.succeed(processOutput(`4242 ${process.pid} 4242\n`));
895 + return Effect.succeed(processOutput(`4242 4300 4300\n4300 ${process.pid} 4300\n`));
896 }
897 if (environmentFails) {
898 return Effect.fail(
@@ -897,8 +906,9 @@ effectIt.effect.each(["linux", "darwin"] as const)(
906 environmentReads += 1;
907 return Effect.succeed(
908 processOutput(
900 - ` 4242 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` +
901 - " 5000 postgres -D /data PATH=/usr/bin\n",
909 + ` 4242 4300 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` +
910 + ` 4300 ${process.pid} agy acp ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n` +
911 + " 5000 1 postgres -D /data PATH=/usr/bin\n",
912 ),
913 );
914 },
apps/server/src/preview/PortScanner.ts
+57 -28
@@ -384,16 +384,42 @@ const parseProcEnvironThread = (raw: string): ThreadId | null => {
384 };
385
386 /**
387 - * Reads macOS `ps -E -o pid=,command=`, which appends each process's launch environment to its
388 - * argv with spaces, so an argument that spells the assignment out also matches.
387 + * A listener with an agent thread in its environment. An agent CLI is a direct child of this
388 + * server and has that environment too, but its own ports are not servers it started.
389 */
390 -const parsePsEnvironmentThreads = (raw: string): ReadonlyMap<number, ThreadId | null> => {
391 - const threads = new Map<number, ThreadId | null>();
390 +interface AgentListener {
391 + readonly threadId: ThreadId;
392 + readonly isAgentCli: boolean;
393 +}
394 +
395 +/** Reads the parent pid from `/proc/<pid>/stat`, whose command field can hold spaces. */
396 +const parseProcStatParent = (raw: string): number | null => {
397 + const parent = Number(
398 + raw
399 + .slice(raw.lastIndexOf(")") + 1)
400 + .trim()
401 + .split(" ")[1],
402 + );
403 + return Number.isInteger(parent) ? parent : null;
404 +};
405 +
406 +/**
407 + * Reads macOS `ps -E -o pid=,ppid=,command=`, which appends each process's launch environment
408 + * to its argv with spaces, so an argument that spells the assignment out also matches.
409 + */
410 +const parsePsEnvironmentThreads = (
411 + raw: string,
412 + serverPid: number,
413 +): ReadonlyMap<number, AgentListener | null> => {
414 + const threads = new Map<number, AgentListener | null>();
415 for (const line of raw.split("\n")) {
393 - const match = /^\s*(\d+)\s(.*)$/.exec(line);
416 + const match = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
417 if (!match) continue;
395 - const value = AGENT_THREAD_ASSIGNMENT.exec(match[2]!)?.[1];
396 - threads.set(Number(match[1]), value ? ThreadId.make(value) : null);
418 + const value = AGENT_THREAD_ASSIGNMENT.exec(match[3]!)?.[1];
419 + threads.set(
420 + Number(match[1]),
421 + value ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } : null,
422 + );
423 }
424 return threads;
425 };
@@ -528,7 +554,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
554 // Each current listener pid's agent thread, or null without one. A process keeps its launch
555 // environment, so a pid is read once while it listens. Cleared while no client retains the
556 // scanner, since unscanned pids can be reused.
531 - const agentThreadsRef = yield* Ref.make<ReadonlyMap<number, ThreadId | null>>(new Map());
557 + const agentThreadsRef = yield* Ref.make<ReadonlyMap<number, AgentListener | null>>(new Map());
558 const agentCommandStopWatchers = new Set<AgentCommandStopWatcher>();
559 let runningAgents = 0;
560 // An agent that exited, or a cache cleared with a marked listener, owes one listener read: the
@@ -540,40 +566,41 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
566 ) {
567 const cached = yield* Ref.get(agentThreadsRef);
568 const unread = pids.filter((pid) => !cached.has(pid));
543 - const read: ReadonlyMap<number, ThreadId | null> =
569 + const readProcListener = Effect.fnUntraced(function* (pid: number) {
570 + const threadId = yield* fileSystem.readFileString(`/proc/${pid}/environ`).pipe(
571 + Effect.map(parseProcEnvironThread),
572 + Effect.orElseSucceed(() => null),
573 + );
574 + if (threadId === null) return [pid, null] as const;
575 + const parent = yield* fileSystem.readFileString(`/proc/${pid}/stat`).pipe(
576 + Effect.map(parseProcStatParent),
577 + Effect.orElseSucceed(() => null),
578 + );
579 + return [pid, { threadId, isAgentCli: parent === process.pid }] as const;
580 + });
581 + const read: ReadonlyMap<number, AgentListener | null> =
582 unread.length === 0
583 ? new Map()
584 : hostPlatform === "linux"
547 - ? new Map(
548 - yield* Effect.forEach(
549 - unread,
550 - (pid) =>
551 - fileSystem.readFileString(`/proc/${pid}/environ`).pipe(
552 - Effect.map(parseProcEnvironThread),
553 - Effect.orElseSucceed(() => null),
554 - Effect.map((threadId) => [pid, threadId] as const),
555 - ),
556 - { concurrency: 16 },
557 - ),
558 - )
585 + ? new Map(yield* Effect.forEach(unread, readProcListener, { concurrency: 16 }))
586 : yield* processRunner
587 .run({
588 command: "ps",
562 - args: ["-E", "-ww", "-o", "pid=,command=", "-p", unread.join(",")],
589 + args: ["-E", "-ww", "-o", "pid=,ppid=,command=", "-p", unread.join(",")],
590 timeout: Duration.millis(PS_TIMEOUT_MS),
591 maxOutputBytes: PS_MAX_OUTPUT_BYTES,
592 })
593 .pipe(
567 - Effect.map((result) => parsePsEnvironmentThreads(result.stdout)),
594 + Effect.map((result) => parsePsEnvironmentThreads(result.stdout, process.pid)),
595 Effect.orElseSucceed(() => {
596 agentScanPending = true;
597 return new Map();
598 }),
599 );
573 - const next = new Map<number, ThreadId | null>();
600 + const next = new Map<number, AgentListener | null>();
601 for (const pid of pids) {
575 - const threadId = cached.has(pid) ? cached.get(pid) : read.get(pid);
576 - if (threadId !== undefined) next.set(pid, threadId);
602 + const listener = cached.has(pid) ? cached.get(pid) : read.get(pid);
603 + if (listener !== undefined) next.set(pid, listener);
604 }
605 yield* Ref.set(agentThreadsRef, next);
606 return next;
@@ -587,8 +614,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
614 agentScanPending = false;
615 const threads = yield* readAgentThreads(pids.filter((pid) => !terminalOwners.has(pid)));
616 const owners = new Map(terminalOwners);
590 - for (const [pid, threadId] of threads) {
591 - if (threadId !== null) owners.set(pid, { terminal: null, agent: { threadId } });
617 + for (const [pid, listener] of threads) {
618 + if (listener !== null && !listener.isAgentCli) {
619 + owners.set(pid, { terminal: null, agent: { threadId: listener.threadId } });
620 + }
621 }
622 return owners;
623 });
apps/server/src/provider/acp/AntigravityProtocol.ts
+9
@@ -45,6 +45,15 @@ const decodeSingleAnswer = Schema.decodeUnknownOption(
45 );
46 const decodeToolCallContent = Schema.decodeUnknownOption(AcpWireSchema.ToolCallContent);
47
48 +/**
49 + * The agent goes on running a command after its prompt ends, and replies by itself when the
50 + * command finishes. A daemon may never finish.
51 + */
52 +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean {
53 + const input = toolCall.data.rawInput;
54 + return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true);
55 +}
56 +
57 /** Native questions share the permission method, but their choices are not approvals. */
58 export function isAntigravityUserInputRequest(
59 request: EffectAcpSchema.RequestPermissionRequest,
packages/provider-acp/src/server/adapter.ts
+37 -1
@@ -584,6 +584,11 @@ export interface AcpAdapterV2Flavor {
584 readonly appendOutput: string;
585 }>;
586 readonly isPersistentBackgroundTool?: (toolCall: AcpToolCallState) => boolean;
587 + /**
588 + * A tool the agent goes on running after its prompt ends, and reports on by itself when the
589 + * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then.
590 + */
591 + readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean;
592 readonly isProviderWakeNotification?: (
593 notification: EffectAcpSchema.SessionNotification,
594 ) => boolean;
@@ -2575,7 +2580,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2580 runtimeGeneration,
2581 Effect.gen(function* () {
2582 yield* Ref.set(runtimeRestartRequired, true);
2578 - if (!followsAgentWorkState) return;
2583 + if (!followsAgentWorkState) {
2584 + // An open prompt fails with its transport. A turn held open for a running tool
2585 + // has no prompt, so nothing else ends it.
2586 + const held = yield* Ref.get(activeTurn);
2587 + if (
2588 + flavor.toolOutlivesPrompt === undefined ||
2589 + held === null ||
2590 + !held.promptSettled ||
2591 + held.finalized ||
2592 + !hasDeferredBackgroundWork(held)
2593 + )
2594 + return;
2595 + for (const tool of held.tools.values()) {
2596 + const status = toolStatus(tool.status);
2597 + if (status === "pending" || status === "running" || status === "waiting") {
2598 + yield* emitTool(held, tool, "failed");
2599 + }
2600 + }
2601 + yield* finalizeTurn(
2602 + held,
2603 + "failed",
2604 + makeProviderFailure({ class: "transport_error" }),
2605 + );
2606 + return;
2607 + }
2608 agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" };
2609 for (const child of nativeChildren.values()) {
2610 if (child.status !== "running") continue;
@@ -4053,6 +4082,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4082
4083 const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => {
4084 if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true;
4085 + if (flavor.toolOutlivesPrompt !== undefined) {
4086 + // A tool that never started has nothing to report later.
4087 + for (const tool of context.tools.values()) {
4088 + if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool))
4089 + return true;
4090 + }
4091 + }
4092 if (context.awaitingBackgroundHydration.size > 0) return true;
4093 if (context.pendingInjectedReport.size > 0) return true;
4094 for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {