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";
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");
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);
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", () => {