@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 2,166 lines 89.5 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, it } from "@effect/vitest";
4 import {
5 ChatFileAttachment,
6 MessageId,
7 NodeId,
8 ProjectId,
9 ProviderInstanceId,
10 ProviderSessionId,
11 RunAttemptId,
12 RunId,
13 ThreadId,
14 } from "@t3tools/contracts";
15 import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
16 import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
17 import * as SecureRandom from "effect/crypto/SecureRandom";
18 import * as DateTime from "effect/DateTime";
19 import * as Deferred from "effect/Deferred";
20 import * as Effect from "effect/Effect";
21 import * as Exit from "effect/Exit";
22 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
34 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
35 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
36 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
37 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
38 import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
39 import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
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 { makeTurnInput } from "./AcpAdapterV2.testkit.ts";
44 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
45 import {
46 type AntigravityAdapterV2RuntimeInput,
47 makeAntigravityAcpAdapterFlavor,
48 makeAntigravityAdapterV2,
49 } from "./AntigravityAdapterV2.ts";
50
51 const flavor = makeAntigravityAcpAdapterFlavor({
52 instanceId: ProviderInstanceId.make("antigravity-test"),
53 random: undefined as never,
54 fileSystem: undefined as never,
55 path: undefined as never,
56 host: undefined as never,
57 selfInvocation: undefined as never,
58 makeRuntime: () => Effect.die("not spawned in this test"),
59 withProcess: (_stop, task) => task,
60 defaultModel: Effect.undefined,
61 });
62
63 function permissionRequest(
64 toolCallId: string,
65 options: ReadonlyArray<EffectAcpSchema.PermissionOption>,
66 ): EffectAcpSchema.RequestPermissionRequest {
67 return {
68 sessionId: "session-1",
69 options,
70 toolCall: { toolCallId, title: "Which branch?" },
71 };
72 }
73
74 describe("AntigravityAdapterV2 flavor", () => {
75 it("keeps a successful subagent launch running until the parent turn becomes idle", () => {
76 const batch = flavor.extractSubagentUpdate?.({
77 toolCallId: "trajectory:4",
78 title: "Running start_subagent",
79 kind: "other",
80 status: "completed",
81 data: { rawOutput: "Started two agents." },
82 });
83 assert.equal(batch?.status, "running");
84 assert.equal(batch?.prompt, "Started two agents.");
85 assert.isNull(batch?.result);
86 assert.isTrue(flavor.subagentsIdleOnTurnCompletion);
87
88 // Permission prompts carry the launch; later updates for the same call do not.
89 const launch = flavor.extractSubagentUpdate?.({
90 toolCallId: "35bea692fa95447fbdae6333fec5515f",
91 title: "Run invoke_subagent?",
92 kind: "other",
93 status: "pending",
94 data: {
95 rawInput: {
96 Subagents: [{ TypeName: "research", Role: "Readme Reader", Prompt: "Read README.md" }],
97 },
98 },
99 });
100 assert.equal(launch?.title, "Readme Reader");
101 assert.equal(launch?.prompt, "Read README.md");
102
103 // agy 1.5.x auto-approves one subagent per call with a flat input.
104 const single = flavor.extractSubagentUpdate?.({
105 toolCallId: "call_16976942396429577770",
106 title: "Run invoke_subagent",
107 kind: "other",
108 status: "completed",
109 data: {
110 rawInput: { TypeName: "research", Role: "Codebase Researcher", Prompt: "Read README.md" },
111 },
112 });
113 assert.equal(single?.status, "running");
114 assert.equal(single?.title, "Codebase Researcher");
115 assert.equal(single?.prompt, "Read README.md");
116 });
117
118 it("routes interaction_* permission requests to the question card", () => {
119 const question = flavor.extractPermissionQuestion?.(
120 permissionRequest("interaction_1", [
121 { optionId: "main", name: "main", kind: "allow_once" },
122 { optionId: "dev", name: "dev", kind: "allow_once" },
123 ]),
124 );
125 assert.isDefined(question);
126 assert.deepEqual(
127 question?.question.options.map((option) => option.label),
128 ["main", "dev"],
129 );
130 assert.deepEqual(question?.respond({ interaction_1: "dev" }), {
131 outcome: { outcome: "selected", optionId: "dev" },
132 });
133 assert.isUndefined(question?.respond({ interaction_1: "nope" }));
134 assert.isUndefined(
135 flavor.extractPermissionQuestion?.(
136 permissionRequest("tool_1", [{ optionId: "allow", name: "Allow", kind: "allow_once" }]),
137 ),
138 );
139 });
140
141 it("keeps the question card to the agent's own options so a typed answer cannot be sent", () => {
142 const question = flavor.extractPermissionQuestion?.(
143 permissionRequest("interaction_2", [
144 { optionId: "opt-main", name: "main", kind: "allow_once" },
145 { optionId: "opt-dev", name: "dev", kind: "allow_once" },
146 ]),
147 );
148 assert.strictEqual(question?.question.allowCustomAnswer, false);
149 assert.deepEqual(
150 question?.question.options.map((option) => option.value),
151 ["opt-main", "opt-dev"],
152 );
153 assert.deepEqual(question?.respond({ interaction_2: "opt-dev" }), {
154 outcome: { outcome: "selected", optionId: "opt-dev" },
155 });
156 });
157 });
158
159 const layerSession = Layer.mergeAll(
160 NodeServices.layer,
161 NodeCrypto.layer,
162 IdAllocator.layer,
163 McpProviderSessions.layer,
164 TestProviderHost.layer().pipe(
165 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
166 ),
167 );
168
169 describe("AntigravityAdapterV2 compaction", () => {
170 it.live.each([
171 { nativeGoals: false, compact: false },
172 { nativeGoals: true, compact: false },
173 { nativeGoals: false, compact: true },
174 ])(
175 "negotiates native goals ($nativeGoals) and advertised compaction ($compact)",
176 ({ nativeGoals, compact }) =>
177 Effect.gen(function* () {
178 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
179 const fileSystem = yield* FileSystem.FileSystem;
180 const path = yield* Path.Path;
181 const crypto = yield* SecureRandom.SecureRandom;
182 const mockAgentPath = yield* path.fromFileUrl(
183 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
184 );
185 const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-compact-" });
186 const requestLog = path.join(logs, "requests.ndjson");
187 const instanceId = ProviderInstanceId.make("antigravity-compaction-test");
188 const goalSupport = yield* Ref.make(false);
189 const startupMilestone = yield* Deferred.make<void>();
190 const consumeStartupCommands = yield* Deferred.make<void>();
191 const workspaceCommands = yield* Ref.make<{
192 readonly names: ReadonlyArray<string>;
193 readonly cwd: string;
194 } | null>(null);
195 const adapter = yield* makeAntigravityAdapterV2({
196 instanceId,
197 selfInvocation: yield* resolveSelfInvocation(),
198 makeRuntime: (input) =>
199 makeAntigravityAcpRuntime({
200 ...input,
201 childProcessSpawner,
202 spawn: {
203 command: process.execPath,
204 args: [mockAgentPath],
205 cwd: input.cwd,
206 env: {
207 T3_ACP_ANTIGRAVITY: "1",
208 T3_ACP_AVAILABLE_COMMANDS: compact ? "compact" : "",
209 T3_ACP_REQUEST_LOG_PATH: requestLog,
210 },
211 },
212 }).pipe(
213 Effect.provideService(SecureRandom.SecureRandom, crypto),
214 Effect.map((runtime) => ({
215 ...runtime,
216 drainEvents: Deferred.succeed(startupMilestone, undefined).pipe(
217 Effect.andThen(runtime.drainEvents),
218 ),
219 })),
220 ),
221 withProcess: (_stop, task) => task,
222 defaultModel: Effect.undefined,
223 supportsNativeGoals: Ref.get(goalSupport).pipe(
224 Effect.tap(() => Deferred.succeed(startupMilestone, undefined)),
225 ),
226 onSessionEvent: (event, cwd) =>
227 event._tag === "AvailableCommandsUpdated"
228 ? Deferred.await(consumeStartupCommands).pipe(
229 Effect.andThen(Ref.set(goalSupport, nativeGoals)),
230 Effect.andThen(
231 Ref.set(workspaceCommands, {
232 names: event.availableCommands.map((command) => command.name),
233 cwd,
234 }),
235 ),
236 )
237 : Effect.void,
238 });
239 const threadId = ThreadId.make("thread-antigravity-compaction");
240 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
241 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
242 runtimeMode: "full-access",
243 interactionMode: "default",
244 cwd: process.cwd(),
245 });
246 const opening = yield* adapter
247 .openSession({
248 threadId,
249 providerSessionId: ProviderSessionId.make("provider-session-antigravity-compaction"),
250 modelSelection,
251 runtimePolicy,
252 })
253 .pipe(Effect.forkScoped);
254 yield* Deferred.await(startupMilestone);
255 yield* Deferred.succeed(consumeStartupCommands, undefined);
256 const session = yield* Fiber.join(opening);
257 assert.deepEqual(yield* Ref.get(workspaceCommands), {
258 names: compact ? ["compact"] : ["plan", "logout"],
259 cwd: process.cwd(),
260 });
261 const compactThread = session.compactThread;
262 assert.isDefined(compactThread);
263 assert.equal(session.providerSession.capabilities.turns.supportsNativeGoals, nativeGoals);
264 assert.equal((yield* adapter.getCapabilities()).turns.supportsNativeGoals, nativeGoals);
265 const providerThread = yield* session.ensureThread({
266 threadId,
267 modelSelection,
268 runtimePolicy,
269 });
270 const turnInput = makeTurnInput({
271 threadId,
272 providerThread,
273 instanceId,
274 modelSelection,
275 runtimePolicy,
276 now: yield* DateTime.now,
277 messageText: "Compact the conversation.",
278 });
279 if (compact) {
280 yield* compactThread!(turnInput);
281 const events = yield* session.events.pipe(
282 Stream.takeUntil((event) => event.type === "turn.terminal"),
283 Stream.runCollect,
284 );
285 assert.isTrue(
286 events.some(
287 (event) =>
288 event.type === "turn_item.updated" &&
289 event.turnItem.type === "compaction" &&
290 event.turnItem.status === "completed",
291 ),
292 );
293 } else {
294 const error = yield* compactThread!(turnInput).pipe(Effect.flip);
295 assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError);
296 assert.instanceOf(error.cause, ProviderAdapter.ProviderCompactionUnsupportedError);
297 }
298 const prompts = (yield* fileSystem.readFileString(requestLog))
299 .trim()
300 .split("\n")
301 .map((line) => JSON.parse(line) as { method?: string; params?: { prompt?: unknown } })
302 .filter((request) => request.method === "session/prompt")
303 .map((request) => request.params?.prompt);
304 assert.deepEqual(prompts, compact ? [[{ type: "text", text: "/compact" }]] : []);
305 }).pipe(Effect.provide(layerSession)),
306 );
307 });
308
309 describe("AntigravityAdapterV2 session open", () => {
310 it.effect.each([
311 {
312 name: "browser sign-in",
313 cause: new EffectAcpErrors.AcpTransportError({
314 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
315 cause: undefined,
316 }),
317 requiresSignIn: true,
318 },
319 {
320 name: "ACP authentication required",
321 cause: EffectAcpErrors.AcpRequestError.authRequired(),
322 requiresSignIn: true,
323 },
324 {
325 name: "transport failure",
326 cause: new EffectAcpErrors.AcpTransportError({
327 detail: "Connection closed",
328 cause: undefined,
329 }),
330 requiresSignIn: undefined,
331 },
332 ] as const)("classifies $name during session open", ({ cause, requiresSignIn }) =>
333 Effect.gen(function* () {
334 const instanceId = ProviderInstanceId.make("antigravity-sign-in-test");
335 const adapter = yield* makeAntigravityAdapterV2({
336 instanceId,
337 selfInvocation: yield* resolveSelfInvocation(),
338 makeRuntime: () => Effect.fail(cause),
339 withProcess: (_stop, task) => task,
340 defaultModel: Effect.undefined,
341 });
342 const threadId = ThreadId.make("thread-antigravity-sign-in");
343 const error = yield* adapter
344 .openSession({
345 threadId,
346 providerSessionId: ProviderSessionId.make("provider-session-antigravity-sign-in"),
347 modelSelection: { instanceId, model: "gemini-test-low" },
348 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
349 runtimeMode: "full-access",
350 interactionMode: "default",
351 cwd: process.cwd(),
352 }),
353 })
354 .pipe(Effect.flip);
355
356 assert.equal(error._tag, "ProviderAdapterOpenSessionError");
357 assert.equal(
358 error._tag === "ProviderAdapterOpenSessionError" && error.requiresSignIn,
359 requiresSignIn,
360 );
361 }).pipe(Effect.provide(layerSession)),
362 );
363 });
364
365 describe("AntigravityAdapterV2 client file system", () => {
366 it.effect("serves confined reads and leaves edits to the agent's diff tools", () =>
367 Effect.gen(function* () {
368 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
369 const fileSystem = yield* FileSystem.FileSystem;
370 const path = yield* Path.Path;
371 const host = yield* ProviderHost.ProviderHost;
372 const mockAgentPath = yield* path.fromFileUrl(
373 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
374 );
375 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
376 // effect-acp keeps the last handler registered per method; so does this.
377 let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
378 let writeTextFile: Parameters<RuntimeService["handleWriteTextFile"]>[0] | undefined;
379 const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-log-" });
380 const requestLog = path.join(logs, "requests.ndjson");
381 const crypto = yield* SecureRandom.SecureRandom;
382 const instanceId = ProviderInstanceId.make("antigravity-containment-test");
383 const adapter = yield* makeAntigravityAdapterV2({
384 instanceId,
385 selfInvocation: yield* resolveSelfInvocation(),
386 makeRuntime: (input) =>
387 makeAntigravityAcpRuntime({
388 ...input,
389 childProcessSpawner,
390 spawn: {
391 command: process.execPath,
392 args: [mockAgentPath],
393 cwd: input.cwd,
394 env: { T3_ACP_ANTIGRAVITY: "1", T3_ACP_REQUEST_LOG_PATH: requestLog },
395 },
396 }).pipe(
397 Effect.provideService(SecureRandom.SecureRandom, crypto),
398 Effect.map((runtime): RuntimeService => ({
399 ...runtime,
400 handleReadTextFile: (handler) =>
401 Effect.sync(() => {
402 readTextFile = handler;
403 }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))),
404 handleWriteTextFile: (handler) =>
405 Effect.sync(() => {
406 writeTextFile = handler;
407 }).pipe(Effect.andThen(runtime.handleWriteTextFile(handler))),
408 })),
409 ),
410 withProcess: (_stop, task) => task,
411 defaultModel: Effect.undefined,
412 });
413 const workspace = yield* fileSystem.makeTempDirectoryScoped({
414 prefix: "t3-antigravity-workspace-",
415 });
416 const outside = yield* fileSystem.makeTempDirectoryScoped({
417 prefix: "t3-antigravity-outside-",
418 });
419 const outsideFile = path.join(outside, "secret.txt");
420 yield* fileSystem.writeFileString(outsideFile, "secret");
421 const attachment = path.join(host.paths.attachmentsDir, "pasted.txt");
422 yield* fileSystem.writeFileString(attachment, "pasted");
423
424 const threadId = ThreadId.make("thread-antigravity-containment");
425 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
426 runtimeMode: "full-access",
427 interactionMode: "default",
428 cwd: workspace,
429 });
430 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
431 const session = yield* adapter.openSession({
432 threadId,
433 providerSessionId: ProviderSessionId.make("provider-session-antigravity-containment"),
434 modelSelection,
435 runtimePolicy,
436 });
437 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
438 const requests = (yield* fileSystem.readFileString(requestLog))
439 .trim()
440 .split("\n")
441 .map(
442 (line) =>
443 JSON.parse(line) as {
444 method?: string;
445 params?: {
446 clientCapabilities?: { fs?: unknown };
447 clientInfo?: { name?: string };
448 additionalDirectories?: unknown;
449 };
450 },
451 );
452 const initialize = requests.find((request) => request.method === "initialize");
453 // agy runs shell commands from its lexicographically first root, so attachments
454 // must reach it through client reads, never as an extra workspace root.
455 assert.isUndefined(
456 requests.find((request) => request.method === "session/new")?.params?.additionalDirectories,
457 );
458 assert.deepEqual(initialize?.params?.clientCapabilities?.fs, {
459 readTextFile: true,
460 writeTextFile: false,
461 });
462 assert.equal(initialize?.params?.clientInfo?.name, "zed");
463 assert.isUndefined(writeTextFile);
464 if (readTextFile === undefined) {
465 return yield* Effect.die("Antigravity sessions must serve client file reads");
466 }
467 const context = (method: string) => ({ requestId: `test-${method}`, method });
468
469 const insidePath = path.join(workspace, "src", "inside.ts");
470 yield* fileSystem.makeDirectory(path.dirname(insidePath), { recursive: true });
471 yield* fileSystem.writeFileString(insidePath, "inside");
472 const pasted = yield* readTextFile(
473 { sessionId: "mock-session-1", path: attachment },
474 context("fs/read_text_file"),
475 );
476 assert.equal(pasted.content, "pasted");
477 yield* fileSystem.writeFileString(insidePath, "\uFEFFfirst\né中🙂\nlast");
478 const sliced = yield* readTextFile(
479 { sessionId: "mock-session-1", path: insidePath, line: 2, limit: 1 },
480 context("fs/read_text_file"),
481 );
482 assert.equal(sliced.content, "é中🙂");
483 yield* fileSystem.writeFileString(insidePath, "inside");
484 for (const [name, bytes] of [
485 ["image.png", new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])],
486 ["data.bin", new Uint8Array([0x61, 0, 0x62])],
487 ] as const) {
488 const binaryPath = path.join(workspace, name);
489 yield* fileSystem.writeFile(binaryPath, bytes);
490 const binaryRead = yield* readTextFile(
491 { sessionId: "mock-session-1", path: binaryPath },
492 context("fs/read_text_file"),
493 ).pipe(Effect.flip);
494 assert.propertyVal(binaryRead, "code", -32602, `${name} is refused as binary`);
495 }
496
497 const outsideRead = yield* readTextFile(
498 { sessionId: "mock-session-1", path: outsideFile },
499 context("fs/read_text_file"),
500 ).pipe(Effect.exit);
501 assert.isTrue(Exit.isFailure(outsideRead));
502 const linkPath = path.join(workspace, "linked-secret.txt");
503 yield* fileSystem.symlink(outsideFile, linkPath);
504 const linkedRead = yield* readTextFile(
505 { sessionId: "mock-session-1", path: linkPath },
506 context("fs/read_text_file"),
507 ).pipe(Effect.exit);
508 assert.isTrue(Exit.isFailure(linkedRead), "a read through an escaping symlink is denied");
509 const insideLink = path.join(workspace, "inside-link.ts");
510 yield* fileSystem.symlink(insidePath, insideLink);
511 const viaInsideLink = yield* readTextFile(
512 { sessionId: "mock-session-1", path: insideLink },
513 context("fs/read_text_file"),
514 );
515 assert.equal(viaInsideLink.content, "inside");
516 }).pipe(Effect.provide(layerSession)),
517 );
518 });
519
520 describe("AntigravityAdapterV2 workspace changes", () => {
521 it.effect("confines file requests to the workspace of the turn in progress", () =>
522 Effect.gen(function* () {
523 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
524 const fileSystem = yield* FileSystem.FileSystem;
525 const path = yield* Path.Path;
526 const crypto = yield* SecureRandom.SecureRandom;
527 const mockAgentPath = yield* path.fromFileUrl(
528 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
529 );
530 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
531 const promptReceived = yield* Deferred.make<Parameters<RuntimeService["prompt"]>[0]>();
532 const host = yield* ProviderHost.ProviderHost;
533 const document = ChatFileAttachment.make({
534 type: "file",
535 id: "native-pdf",
536 name: "diagram.pdf",
537 mimeType: "application/pdf",
538 sizeBytes: 9,
539 });
540 const documentPath = host.resolveAttachmentPath(document)!;
541 yield* fileSystem.writeFileString(documentPath, "%PDF-1.7");
542 let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
543 const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test");
544 const adapter = yield* makeAntigravityAdapterV2({
545 instanceId,
546 selfInvocation: yield* resolveSelfInvocation(),
547 makeRuntime: (input) =>
548 makeAntigravityAcpRuntime({
549 ...input,
550 childProcessSpawner,
551 spawn: {
552 command: process.execPath,
553 args: [mockAgentPath],
554 cwd: input.cwd,
555 env: { T3_ACP_ANTIGRAVITY: "1", T3_ACP_HANG_PROMPT_FOREVER: "1" },
556 },
557 }).pipe(
558 Effect.provideService(SecureRandom.SecureRandom, crypto),
559 Effect.map((runtime): RuntimeService => ({
560 ...runtime,
561 prompt: (request) =>
562 Deferred.succeed(promptReceived, request).pipe(
563 Effect.andThen(runtime.prompt(request)),
564 ),
565 start: () =>
566 runtime.start().pipe(
567 Effect.map((started) => ({
568 ...started,
569 initializeResult: {
570 ...started.initializeResult,
571 agentCapabilities: {
572 ...started.initializeResult.agentCapabilities,
573 promptCapabilities: { image: true, audio: true, embeddedContext: true },
574 },
575 },
576 })),
577 ),
578 handleReadTextFile: (handler) =>
579 Effect.sync(() => {
580 readTextFile = handler;
581 }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))),
582 })),
583 ),
584 withProcess: (_stop, task) => task,
585 defaultModel: Effect.undefined,
586 });
587 const workspaceA = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-a-" });
588 const workspaceB = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-b-" });
589 yield* fileSystem.writeFileString(path.join(workspaceA, "a.txt"), "from a");
590 yield* fileSystem.writeFileString(path.join(workspaceB, "b.txt"), "from b");
591 const policyFor = (cwd: string) =>
592 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
593 runtimeMode: "full-access",
594 interactionMode: "default",
595 cwd,
596 });
597 const threadId = ThreadId.make("thread-antigravity-workspace-change");
598 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
599 const session = yield* adapter.openSession({
600 threadId,
601 providerSessionId: ProviderSessionId.make("provider-session-antigravity-workspace-change"),
602 modelSelection,
603 runtimePolicy: policyFor(workspaceA),
604 });
605 const providerThread = yield* session.ensureThread({
606 threadId,
607 modelSelection,
608 runtimePolicy: policyFor(workspaceA),
609 });
610 const now = yield* DateTime.now;
611 yield* session
612 .startTurn({
613 appThread: {
614 createdBy: "user",
615 creationSource: "web",
616 id: threadId,
617 projectId: ProjectId.make("project-antigravity-workspace-change"),
618 title: "Antigravity workspace change",
619 providerInstanceId: instanceId,
620 modelSelection,
621 runtimeMode: "full-access",
622 interactionMode: "default",
623 branch: null,
624 worktreePath: workspaceB,
625 activeProviderThreadId: providerThread.id,
626 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
627 forkedFrom: null,
628 createdAt: now,
629 updatedAt: now,
630 archivedAt: null,
631 settledOverride: null,
632 settledAt: null,
633 lastVisitedAt: null,
634 deletedAt: null,
635 },
636 threadId,
637 runId: RunId.make("run-antigravity-workspace-change"),
638 runOrdinal: 1,
639 providerTurnOrdinal: 1,
640 attemptId: RunAttemptId.make("attempt-antigravity-workspace-change"),
641 rootNodeId: NodeId.make("node-antigravity-workspace-change"),
642 providerThread,
643 message: {
644 createdBy: "user",
645 creationSource: "web",
646 messageId: MessageId.make("message-antigravity-workspace-change"),
647 text: "read b.txt",
648 attachments: [document],
649 },
650 modelSelection,
651 runtimePolicy: policyFor(workspaceB),
652 })
653 .pipe(Effect.forkScoped);
654 yield* session.events.pipe(
655 Stream.filter((event) => event.type === "provider_turn.updated"),
656 Stream.runHead,
657 );
658 const sent = yield* Deferred.await(promptReceived);
659 assert.deepEqual(
660 sent.prompt.filter((block) => block.type === "resource_link"),
661 [
662 {
663 type: "resource_link",
664 uri: (yield* path.toFileUrl(documentPath)).href,
665 name: "diagram.pdf",
666 mimeType: "application/pdf",
667 size: 8,
668 },
669 ],
670 );
671 assert.include(JSON.stringify(sent.prompt), JSON.stringify(documentPath).slice(1, -1));
672 if (readTextFile === undefined) {
673 return yield* Effect.die("Antigravity sessions must serve client file requests");
674 }
675 const context = { requestId: "test-read", method: "fs/read_text_file" };
676 const fromB = yield* readTextFile(
677 { sessionId: "mock-session-1", path: path.join(workspaceB, "b.txt") },
678 context,
679 );
680 assert.equal(fromB.content, "from b");
681 const fromA = yield* readTextFile(
682 { sessionId: "mock-session-1", path: path.join(workspaceA, "a.txt") },
683 context,
684 ).pipe(Effect.exit);
685 assert.isTrue(Exit.isFailure(fromA), "the previous workspace is no longer readable");
686 }).pipe(Effect.provide(layerSession)),
687 );
688 });
689
690 describe("AntigravityAdapterV2 html_render pages", () => {
691 it.effect("shows the page html_render published when the agent reports only a summary", () =>
692 Effect.gen(function* () {
693 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
694 const path = yield* Path.Path;
695 const crypto = yield* SecureRandom.SecureRandom;
696 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
697 const mockAgentPath = yield* path.fromFileUrl(
698 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
699 );
700 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
701 let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
702 const instanceId = ProviderInstanceId.make("antigravity-html-render-test");
703 const threadId = ThreadId.make("thread-antigravity-html-render");
704 const page = (name: string) => ({
705 attachmentId: `${threadId}-${name}-html`,
706 title: "Revenue",
707 height: 240,
708 });
709 // Long enough that Antigravity bounds the html the adapter sees.
710 const rows = Array.from({ length: 500 }, (_, row) => `<tr><td>Row ${row}</td></tr>`);
711 const report = { html: `<table>${rows.join("")}</table>`, title: "Revenue", height: 240 };
712 const failed = { ...report, html: "<p>Revenue</p>" };
713 const errored = { ...report, html: "<p>Revenue error</p>" };
714 const telemetry = {
715 html: `<ul>${rows.join("").replaceAll("tr", "li")}</ul>`,
716 title: "Telemetry",
717 height: 411,
718 };
719 const adapter = yield* makeAntigravityAdapterV2({
720 instanceId,
721 selfInvocation: yield* resolveSelfInvocation(),
722 makeRuntime: (input) =>
723 makeAntigravityAcpRuntime({
724 ...input,
725 childProcessSpawner,
726 spawn: {
727 command: process.execPath,
728 args: [mockAgentPath],
729 cwd: input.cwd,
730 env: { T3_ACP_ANTIGRAVITY: "1" },
731 },
732 }).pipe(
733 Effect.provideService(SecureRandom.SecureRandom, crypto),
734 Effect.map((runtime): RuntimeService => ({
735 ...runtime,
736 handleSessionUpdate: (handler) =>
737 Effect.sync(() => {
738 sessionUpdate = handler;
739 }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
740 // agy_acp_server 1.3/1.4 without a permission prompt: the call is
741 // titled "Running <tool>" and completes with the step's summary
742 // in place of the MCP result.
743 prompt: () =>
744 Effect.gen(function* () {
745 const send = (update: EffectAcpSchema.SessionUpdate) =>
746 sessionUpdate === undefined
747 ? Effect.die("the adapter must handle session updates")
748 : sessionUpdate(
749 normalizeAntigravitySessionUpdate({
750 sessionId: "mock-session-1",
751 update,
752 }),
753 );
754 const calls = [
755 ["published", report],
756 ["unpublished", { ...report, html: "<p>Costs</p>" }],
757 ["failed", failed],
758 ["error", errored],
759 ] as const;
760 for (const [toolCallId, rawInput] of calls) {
761 yield* send({
762 sessionUpdate: "tool_call",
763 toolCallId,
764 title: "Running html_render",
765 kind: "other",
766 status: "in_progress",
767 rawInput,
768 });
769 }
770 yield* mcpSessions.recordHtmlRender(threadId, report, page("report"));
771 yield* mcpSessions.recordHtmlRender(threadId, failed, page("failed"));
772 yield* mcpSessions.recordHtmlRender(threadId, errored, page("error"));
773 for (const [toolCallId, status] of [
774 ["unpublished", "completed"],
775 ["failed", "failed"],
776 ["published", "completed"],
777 ["published", "completed"],
778 ] as const) {
779 yield* send({
780 sessionUpdate: "tool_call_update",
781 toolCallId,
782 status,
783 rawOutput: `Summary of ${toolCallId}`,
784 });
785 }
786 yield* send({
787 sessionUpdate: "tool_call_update",
788 toolCallId: "error",
789 status: "completed",
790 rawOutput: { result: { isError: true, content: [] } },
791 });
792 for (const [name, rawInput] of [
793 ["failed", failed],
794 ["error", errored],
795 ] as const) {
796 const toolCallId = `${name}-retry`;
797 yield* send({
798 sessionUpdate: "tool_call",
799 toolCallId,
800 title: "Running html_render",
801 kind: "other",
802 status: "in_progress",
803 rawInput,
804 });
805 yield* mcpSessions.recordHtmlRender(threadId, rawInput, page(toolCallId));
806 yield* send({
807 sessionUpdate: "tool_call_update",
808 toolCallId: name,
809 status: name === "failed" ? "failed" : "completed",
810 rawOutput:
811 name === "failed"
812 ? "Summary of failed"
813 : { result: { isError: true, content: [] } },
814 });
815 yield* send({
816 sessionUpdate: "tool_call_update",
817 toolCallId,
818 status: "completed",
819 rawOutput: `Summary of ${toolCallId}`,
820 });
821 }
822 yield* mcpSessions.recordHtmlRender(threadId, report, page("replacement"));
823 yield* send({
824 sessionUpdate: "tool_call_update",
825 toolCallId: "published",
826 status: "completed",
827 rawOutput: { htmlRender: page("replacement") },
828 });
829 yield* send({
830 sessionUpdate: "tool_call_update",
831 toolCallId: "published",
832 status: "completed",
833 rawOutput: "Summary of published",
834 });
835 // agy 1.5.8 titles the call with its MCP name and completes without any output.
836 yield* send({
837 sessionUpdate: "tool_call",
838 toolCallId: "agy-1.5.8",
839 title: "Run mcp_t3-code_html_render",
840 kind: "other",
841 status: "in_progress",
842 rawInput: { ...telemetry, toolSummary: "Render telemetry" },
843 });
844 yield* mcpSessions.recordHtmlRender(threadId, telemetry, page("agy-1.5.8"));
845 yield* send({
846 sessionUpdate: "tool_call_update",
847 toolCallId: "agy-1.5.8",
848 status: "completed",
849 });
850 return { stopReason: "end_turn" as const };
851 }),
852 })),
853 ),
854 withProcess: (_stop, task) => task,
855 defaultModel: Effect.undefined,
856 });
857 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
858 runtimeMode: "full-access",
859 interactionMode: "default",
860 cwd: process.cwd(),
861 });
862 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
863 const session = yield* adapter.openSession({
864 threadId,
865 providerSessionId: ProviderSessionId.make("provider-session-antigravity-html-render"),
866 modelSelection,
867 runtimePolicy,
868 });
869 const providerThread = yield* session.ensureThread({
870 threadId,
871 modelSelection,
872 runtimePolicy,
873 });
874 const now = yield* DateTime.now;
875 yield* session.startTurn({
876 appThread: {
877 createdBy: "user",
878 creationSource: "web",
879 id: threadId,
880 projectId: ProjectId.make("project-antigravity-html-render"),
881 title: "Antigravity html_render",
882 providerInstanceId: instanceId,
883 modelSelection,
884 runtimeMode: "full-access",
885 interactionMode: "default",
886 branch: null,
887 worktreePath: process.cwd(),
888 activeProviderThreadId: providerThread.id,
889 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
890 forkedFrom: null,
891 createdAt: now,
892 updatedAt: now,
893 archivedAt: null,
894 settledOverride: null,
895 settledAt: null,
896 lastVisitedAt: null,
897 deletedAt: null,
898 },
899 threadId,
900 runId: RunId.make("run-antigravity-html-render"),
901 runOrdinal: 1,
902 providerTurnOrdinal: 1,
903 attemptId: RunAttemptId.make("attempt-antigravity-html-render"),
904 rootNodeId: NodeId.make("node-antigravity-html-render"),
905 providerThread,
906 message: {
907 createdBy: "user",
908 creationSource: "web",
909 messageId: MessageId.make("message-antigravity-html-render"),
910 text: "chart the revenue",
911 attachments: [],
912 },
913 modelSelection,
914 runtimePolicy,
915 });
916 const events = Array.from(
917 yield* session.events.pipe(
918 Stream.takeUntil((event) => event.type === "turn.terminal"),
919 Stream.runCollect,
920 ),
921 );
922 const tool = (nativeId: string) => {
923 const event = events.findLast(
924 (event) =>
925 event.type === "turn_item.updated" &&
926 event.turnItem.nativeItemRef?.nativeId === nativeId,
927 );
928 if (event?.type !== "turn_item.updated" || event.turnItem.type !== "dynamic_tool") {
929 return undefined;
930 }
931 const item = event.turnItem;
932 return {
933 status: item.status,
934 toolName: item.toolName,
935 page: htmlRenderFromToolItem(item),
936 output: item.output,
937 };
938 };
939
940 assert.deepEqual(tool("published"), {
941 status: "completed",
942 toolName: "t3-code.html_render",
943 page: page("replacement"),
944 output: { htmlRender: page("replacement") },
945 });
946 assert.deepEqual(tool("unpublished"), {
947 status: "completed",
948 toolName: "t3-code.html_render",
949 page: undefined,
950 output: "Summary of unpublished",
951 });
952 assert.deepEqual(tool("failed"), {
953 status: "failed",
954 toolName: "t3-code.html_render",
955 page: undefined,
956 output: "Summary of failed",
957 });
958 assert.deepEqual(tool("error"), {
959 status: "completed",
960 toolName: "t3-code.html_render",
961 page: undefined,
962 output: [],
963 });
964 assert.deepEqual(
965 events.flatMap((event) =>
966 event.type === "turn_item.updated" &&
967 event.turnItem.type === "dynamic_tool" &&
968 event.turnItem.nativeItemRef?.nativeId === "published" &&
969 event.turnItem.status === "completed"
970 ? [htmlRenderFromToolItem(event.turnItem)]
971 : [],
972 ),
973 [page("report"), page("report"), page("replacement"), page("replacement")],
974 );
975 for (const name of ["failed-retry", "error-retry", "agy-1.5.8"]) {
976 assert.deepEqual(tool(name), {
977 status: "completed",
978 toolName: "t3-code.html_render",
979 page: page(name),
980 output: { htmlRender: page(name) },
981 });
982 }
983 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined);
984 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined);
985 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined);
986 assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined);
987 }).pipe(Effect.provide(layerSession)),
988 );
989 });
990
991 /**
992 * A session whose prompt reports one running command and returns end_turn, as agy 1.5.11 does
993 * for `run_command` once `WaitMsBeforeAsync` passes. The test sends every later frame.
994 */
995 const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")(function* (
996 commandInput: Record<string, unknown>,
997 /** The prompt launches one agy 1.5 subagent instead; its records live below this profile. */
998 detachedChildProfile?: string,
999 /** agy 1.5.11 answers a steered prompt once the next one arrives, which runs to `releaseSteer`. */
1000 steering?: { readonly agentVersion: string; readonly holdsFirstPrompt: boolean },
1001 ) {
1002 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1003 const path = yield* Path.Path;
1004 const crypto = yield* SecureRandom.SecureRandom;
1005 const mockAgentPath = yield* path.fromFileUrl(
1006 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1007 );
1008 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
1009 let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
1010 let requestPermission: Parameters<RuntimeService["handleRequestPermission"]>[0] | undefined;
1011 const send = (update: EffectAcpSchema.SessionUpdate) =>
1012 sessionUpdate === undefined
1013 ? Effect.die("the adapter must handle session updates")
1014 : sessionUpdate(normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }));
1015 const command = {
1016 toolCallId: "call_fetch",
1017 kind: "execute",
1018 title: "node fetch_throughput.mjs",
1019 rawInput: { CommandLine: "node fetch_throughput.mjs", ...commandInput },
1020 } as const;
1021 let cancels = 0;
1022 const prompts: Array<{
1023 readonly prompt: ReadonlyArray<EffectAcpSchema.ContentBlock>;
1024 readonly released: Deferred.Deferred<void> | undefined;
1025 }> = [];
1026 const steered = yield* Deferred.make<void>();
1027 const releaseSteer = yield* Deferred.make<void>();
1028 let terminate: AntigravityAdapterV2RuntimeInput["onTermination"];
1029 const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const;
1030 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
1031 const instanceId = ProviderInstanceId.make("antigravity-wake-test");
1032 const threadId = ThreadId.make("thread-antigravity-wake");
1033 const adapter = yield* makeAntigravityAdapterV2({
1034 instanceId,
1035 selfInvocation: yield* resolveSelfInvocation(),
1036 continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) },
1037 makeRuntime: (input) => {
1038 terminate = input.onTermination;
1039 return makeAntigravityAcpRuntime({
1040 ...input,
1041 childProcessSpawner,
1042 spawn: {
1043 command: process.execPath,
1044 args: [mockAgentPath],
1045 cwd: input.cwd,
1046 env: {
1047 T3_ACP_ANTIGRAVITY: "1",
1048 ...(steering === undefined ? {} : { T3_ACP_AGENT_VERSION: steering.agentVersion }),
1049 },
1050 },
1051 }).pipe(
1052 Effect.provideService(SecureRandom.SecureRandom, crypto),
1053 Effect.map((runtime): RuntimeService => ({
1054 ...runtime,
1055 cancel: Effect.sync(() => {
1056 cancels += 1;
1057 }),
1058 handleSessionUpdate: (handler) =>
1059 Effect.sync(() => {
1060 sessionUpdate = handler;
1061 }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
1062 handleRequestPermission: (handler) =>
1063 Effect.sync(() => {
1064 requestPermission = handler;
1065 }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))),
1066 prompt: (payload, promptOptions) =>
1067 Effect.gen(function* () {
1068 prompts.push({ prompt: payload.prompt, released: promptOptions?.released });
1069 if (promptOptions?.dispatched !== undefined) {
1070 yield* Deferred.succeed(promptOptions.dispatched, undefined);
1071 }
1072 if (prompts.length > 1) {
1073 yield* Deferred.succeed(steered, undefined);
1074 yield* Deferred.await(releaseSteer);
1075 return { stopReason: "end_turn" as const };
1076 }
1077 yield* send(
1078 detachedChildProfile === undefined
1079 ? { sessionUpdate: "tool_call", ...command, status: "in_progress" }
1080 : {
1081 sessionUpdate: "tool_call",
1082 toolCallId: "call_research",
1083 kind: "other",
1084 title: "Run invoke_subagent",
1085 status: "completed",
1086 rawInput: { TypeName: "research", Role: "Researcher", Prompt: "Read it" },
1087 },
1088 );
1089 yield* send({
1090 sessionUpdate: "agent_message_chunk",
1091 content: { type: "text", text: "I'll render once the fetch finishes." },
1092 });
1093 yield* send(usage);
1094 if (steering?.holdsFirstPrompt === true) yield* Deferred.await(steered);
1095 return { stopReason: "end_turn" as const };
1096 }),
1097 })),
1098 );
1099 },
1100 withProcess: (_stop, task) => task,
1101 defaultModel: Effect.undefined,
1102 ...(detachedChildProfile === undefined ? {} : { profileDirectory: detachedChildProfile }),
1103 });
1104 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1105 runtimeMode: "full-access",
1106 interactionMode: "default",
1107 cwd: process.cwd(),
1108 });
1109 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
1110 const session = yield* adapter.openSession({
1111 threadId,
1112 providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"),
1113 modelSelection,
1114 runtimePolicy,
1115 });
1116 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
1117 yield* session.events.pipe(
1118 Stream.runForEach((event) => Queue.offer(events, event)),
1119 Effect.forkScoped,
1120 );
1121 const until = (done: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) =>
1122 Effect.gen(function* () {
1123 const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
1124 while (true) {
1125 const event = yield* Queue.take(events);
1126 seen.push(event);
1127 if (done(event)) return seen;
1128 }
1129 });
1130 const providerThread = yield* session.ensureThread({
1131 threadId,
1132 modelSelection,
1133 runtimePolicy,
1134 });
1135 const now = yield* DateTime.now;
1136 const startTurn = (ordinal: number, continuation: boolean) =>
1137 session.startTurn({
1138 appThread: {
1139 createdBy: "user",
1140 creationSource: "web",
1141 id: threadId,
1142 projectId: ProjectId.make("project-antigravity-wake"),
1143 title: "Antigravity wake",
1144 providerInstanceId: instanceId,
1145 modelSelection,
1146 runtimeMode: "full-access",
1147 interactionMode: "default",
1148 branch: null,
1149 worktreePath: process.cwd(),
1150 activeProviderThreadId: providerThread.id,
1151 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1152 forkedFrom: null,
1153 createdAt: now,
1154 updatedAt: now,
1155 archivedAt: null,
1156 settledOverride: null,
1157 settledAt: null,
1158 lastVisitedAt: null,
1159 deletedAt: null,
1160 },
1161 threadId,
1162 runId: RunId.make(`run-antigravity-wake-${ordinal}`),
1163 runOrdinal: ordinal,
1164 providerTurnOrdinal: ordinal,
1165 attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`),
1166 rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`),
1167 providerThread,
1168 message: {
1169 ...(continuation
1170 ? { createdBy: "agent" as const, creationSource: "provider" as const }
1171 : { createdBy: "user" as const, creationSource: "web" as const }),
1172 messageId: MessageId.make(`message-antigravity-wake-${ordinal}`),
1173 text: "chart the throughput",
1174 attachments: [],
1175 },
1176 modelSelection,
1177 runtimePolicy,
1178 });
1179
1180 return {
1181 session,
1182 providerThread,
1183 command,
1184 usage,
1185 offers,
1186 send,
1187 startTurn,
1188 until,
1189 throughTerminal: until((event) => event.type === "turn.terminal"),
1190 // The reply before end_turn closes when the prompt settles, held open or not.
1191 throughPromptSettled: until(
1192 (event) =>
1193 event.type === "turn_item.updated" &&
1194 event.turnItem.type === "assistant_message" &&
1195 event.turnItem.status === "completed",
1196 ),
1197 requestPermission: (...args: Parameters<NonNullable<typeof requestPermission>>) =>
1198 requestPermission === undefined
1199 ? Effect.die("the adapter must handle permission requests")
1200 : requestPermission(...args),
1201 cancels: () => cancels,
1202 prompts,
1203 releaseSteer: Deferred.succeed(releaseSteer, undefined),
1204 runtimeDies: Effect.suspend(
1205 () =>
1206 terminate?.(
1207 new EffectAcpErrors.AcpTransportError({ detail: "agent exited", cause: "exit" }),
1208 ) ?? Effect.die("the adapter must watch its runtime"),
1209 ),
1210 };
1211 });
1212
1213 describe("AntigravityAdapterV2 work after the prompt ends", () => {
1214 // agy sets `IsDaemon` on a command it does not wait for. When it exits, the agent replies
1215 // with no prompt open.
1216 it.effect("continues in one run when a finished daemon wakes the agent", () =>
1217 Effect.gen(function* () {
1218 const { command, usage, offers, send, startTurn, throughTerminal, requestPermission } =
1219 yield* openSessionWithRunningCommand({ IsDaemon: true, WaitMsBeforeAsync: 500 });
1220 yield* startTurn(1, false);
1221 const promptTerminal = (yield* throughTerminal).at(-1);
1222 assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed");
1223
1224 yield* send({
1225 sessionUpdate: "tool_call_update",
1226 ...command,
1227 status: "completed",
1228 rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1229 });
1230 assert.lengthOf(offers, 1, "the finished daemon must wake the thread");
1231 // The agent can ask before the app has started the continuation run.
1232 const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" };
1233 const permission = yield* requestPermission(
1234 {
1235 sessionId: "mock-session-1",
1236 toolCall: { ...followUp, status: "pending" },
1237 options: [
1238 { optionId: "allow", name: "Allow", kind: "allow_once" },
1239 { optionId: "deny", name: "Deny", kind: "reject_once" },
1240 ],
1241 },
1242 { requestId: "permission-1", method: "session/request_permission" },
1243 ).pipe(Effect.forkScoped({ startImmediately: true }));
1244 yield* offers[0]!.dispatchIfCurrent!(Effect.void);
1245 yield* startTurn(2, true);
1246 assert.deepEqual(yield* Fiber.join(permission), {
1247 outcome: { outcome: "selected", optionId: "allow" },
1248 });
1249
1250 // The model took 6.7 s to answer the finished command; the run must outlast that silence.
1251 yield* TestClock.adjust("10 seconds");
1252 yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" });
1253 yield* send({
1254 sessionUpdate: "agent_message_chunk",
1255 content: { type: "text", text: "Here is the chart." },
1256 });
1257 yield* TestClock.adjust("10 seconds");
1258 yield* send(usage);
1259 yield* TestClock.adjust("3 seconds");
1260 const continued = yield* throughTerminal;
1261 const continuedTerminal = continued.at(-1);
1262 assert.equal(
1263 continuedTerminal?.type === "turn.terminal" && continuedTerminal.status,
1264 "completed",
1265 );
1266 assert.isTrue(
1267 continued.some(
1268 (event) =>
1269 event.type === "turn_item.updated" &&
1270 event.turnItem.type === "assistant_message" &&
1271 event.turnItem.runId === RunId.make("run-antigravity-wake-2"),
1272 ),
1273 "the reply belongs to the continuation run",
1274 );
1275 const finished = continued.findLast(
1276 (event) =>
1277 event.type === "turn_item.updated" &&
1278 event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1279 );
1280 assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed");
1281 assert.lengthOf(offers, 1, "one wake is one run");
1282 }).pipe(Effect.provide(layerSession)),
1283 );
1284
1285 // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns
1286 // end_turn while the command runs, and the agent replies when the command finishes.
1287 it.effect("keeps the run open while a command the agent waits for still runs", () =>
1288 Effect.gen(function* () {
1289 const { command, usage, offers, send, startTurn, until, throughPromptSettled } =
1290 yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 });
1291 yield* startTurn(1, false);
1292 yield* throughPromptSettled;
1293 yield* TestClock.adjust("10 minutes");
1294 yield* send({
1295 sessionUpdate: "tool_call_update",
1296 ...command,
1297 status: "completed",
1298 rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1299 });
1300 yield* TestClock.adjust("10 seconds");
1301 yield* send({
1302 sessionUpdate: "agent_message_chunk",
1303 content: { type: "text", text: "Here is the chart." },
1304 });
1305 yield* send(usage);
1306 yield* TestClock.adjust("3 seconds");
1307 const run = yield* until((event) => event.type === "turn.terminal");
1308 const terminal = run.at(-1);
1309 assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1310 assert.include(JSON.stringify(run), "Here is the chart.", "the reply is part of the run");
1311 assert.lengthOf(offers, 0, "the open run needs no continuation");
1312 }).pipe(Effect.provide(layerSession)),
1313 );
1314
1315 // agy names its background commands `<session>/task-<n>`; the agent passes that to
1316 // t3_background_wait, which must not fail since the adapter already holds the run open.
1317 it.effect("accepts t3_background_wait for a command it already tracks", () =>
1318 Effect.gen(function* () {
1319 const { session, providerThread, startTurn, throughPromptSettled } =
1320 yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 });
1321 yield* startTurn(1, false);
1322 yield* throughPromptSettled;
1323 const taskIds = ["mock-session-1/task-2"];
1324 assert.isDefined(session.awaitBackgroundTasks, "t3_background_wait must not be unsupported");
1325 const result = yield* session.awaitBackgroundTasks!({
1326 providerThread,
1327 taskIds,
1328 awaited: true,
1329 });
1330 assert.deepEqual(result.matched, taskIds);
1331 }).pipe(Effect.provide(layerSession)),
1332 );
1333
1334 // agy 1.5.11 reads a prompt sent mid-turn as a steer: it answers the running prompt end_turn
1335 // and goes on under the new one. session/cancel would end its running commands and subagents.
1336 it.effect("steers a running prompt with the next one and leaves its work running", () =>
1337 Effect.gen(function* () {
1338 const opened = yield* openSessionWithRunningCommand({}, undefined, {
1339 agentVersion: "1.5.11",
1340 holdsFirstPrompt: true,
1341 });
1342 const { session, providerThread, command, usage, send, startTurn, until } = opened;
1343 assert.isTrue(session.providerSession.capabilities.turns.supportsActiveSteering);
1344 yield* startTurn(1, false);
1345 const started = yield* until(
1346 (event) =>
1347 event.type === "turn_item.updated" &&
1348 event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1349 );
1350 const providerTurnId = started.flatMap((event) =>
1351 event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1352 )[0]!;
1353 yield* send({
1354 sessionUpdate: "tool_call",
1355 toolCallId: "call_artist",
1356 kind: "other",
1357 title: "Run invoke_subagent",
1358 status: "completed",
1359 rawInput: { Role: "Artist", Prompt: "Paint the scooter" },
1360 });
1361
1362 yield* session.steerTurn({
1363 threadId: ThreadId.make("thread-antigravity-wake"),
1364 runId: RunId.make("run-antigravity-wake-1"),
1365 providerThread,
1366 providerTurnId,
1367 message: {
1368 messageId: MessageId.make("message-antigravity-steer"),
1369 text: "Use opus subagents from now on",
1370 attachments: [],
1371 createdBy: "user",
1372 creationSource: "web",
1373 },
1374 });
1375 assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's work");
1376 assert.lengthOf(opened.prompts, 2);
1377 assert.deepEqual(opened.prompts[1]!.prompt, [
1378 { type: "text", text: "Use opus subagents from now on" },
1379 ]);
1380 assert.isTrue(
1381 yield* Deferred.isDone(opened.prompts[0]!.released!),
1382 "the steered prompt frees the runtime for the steer",
1383 );
1384 // The steered prompt has answered end_turn; the turn must outlast the finalize debounce.
1385 yield* TestClock.adjust("10 seconds");
1386
1387 yield* send({
1388 sessionUpdate: "tool_call_update",
1389 ...command,
1390 status: "completed",
1391 rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1392 });
1393 yield* send({
1394 sessionUpdate: "agent_message_chunk",
1395 content: { type: "text", text: "Switching to opus subagents." },
1396 });
1397 yield* send(usage);
1398 yield* opened.releaseSteer;
1399 const run = [...started, ...(yield* until((event) => event.type === "turn.terminal"))];
1400 const terminal = run.at(-1);
1401 assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1402 assert.include(JSON.stringify(run), "Switching to opus subagents.");
1403 const finished = run.findLast(
1404 (event) =>
1405 event.type === "turn_item.updated" &&
1406 event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1407 );
1408 assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed");
1409 const subagentStatuses = run.flatMap((event) =>
1410 event.type === "subagent.updated" ? [event.subagent.status] : [],
1411 );
1412 assert.notInclude(subagentStatuses, "interrupted");
1413 assert.equal(subagentStatuses.at(-1), "idle");
1414 }).pipe(Effect.provide(layerSession)),
1415 );
1416
1417 // A wake run has no prompt of its own, yet agy can keep working in it for minutes.
1418 it.effect("steers a continuation run that keeps working after its wake", () =>
1419 Effect.gen(function* () {
1420 const opened = yield* openSessionWithRunningCommand(
1421 { IsDaemon: true, WaitMsBeforeAsync: 500 },
1422 undefined,
1423 { agentVersion: "1.5.11", holdsFirstPrompt: false },
1424 );
1425 const { session, providerThread, command, offers, send, startTurn, until, throughTerminal } =
1426 opened;
1427 yield* startTurn(1, false);
1428 yield* throughTerminal;
1429 yield* send({
1430 sessionUpdate: "tool_call_update",
1431 ...command,
1432 status: "completed",
1433 rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1434 });
1435 assert.lengthOf(offers, 1, "the finished daemon must wake the thread");
1436 yield* offers[0]!.dispatchIfCurrent!(Effect.void);
1437 yield* startTurn(2, true);
1438 const followUp = { toolCallId: "call_build", kind: "execute", title: "vp run build" };
1439 yield* send({ sessionUpdate: "tool_call", ...followUp, status: "in_progress" });
1440 const continued = yield* until(
1441 (event) =>
1442 event.type === "turn_item.updated" &&
1443 event.turnItem.nativeItemRef?.nativeId === followUp.toolCallId,
1444 );
1445 const providerTurnId = continued.flatMap((event) =>
1446 event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1447 )[0]!;
1448
1449 const steer = yield* session
1450 .steerTurn({
1451 threadId: ThreadId.make("thread-antigravity-wake"),
1452 runId: RunId.make("run-antigravity-wake-2"),
1453 providerThread,
1454 providerTurnId,
1455 message: {
1456 messageId: MessageId.make("message-antigravity-steer"),
1457 text: "Skip the build",
1458 attachments: [],
1459 createdBy: "user",
1460 creationSource: "web",
1461 },
1462 })
1463 .pipe(Effect.exit);
1464 assert.isTrue(
1465 Exit.isSuccess(steer),
1466 `a working wake run must accept a steer: ${String(Exit.isFailure(steer) && steer.cause)}`,
1467 );
1468 assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's work");
1469 assert.lengthOf(opened.prompts, 2);
1470 assert.deepEqual(opened.prompts[1]!.prompt, [{ type: "text", text: "Skip the build" }]);
1471
1472 yield* send({ sessionUpdate: "tool_call_update", ...followUp, status: "completed" });
1473 yield* TestClock.adjust("16 minutes");
1474 const silent = yield* until((event) => event.type === "turn.terminal");
1475 const terminal = silent.at(-1);
1476 assert.equal(
1477 terminal?.type === "turn.terminal" && terminal.status,
1478 "failed",
1479 "a silent steer prompt must still hit the inactivity timeout",
1480 );
1481 }).pipe(Effect.provide(layerSession)),
1482 );
1483
1484 it.effect("steers a run held open by a detached subagent without stopping it", () =>
1485 Effect.gen(function* () {
1486 const fileSystem = yield* FileSystem.FileSystem;
1487 const path = yield* Path.Path;
1488 const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" });
1489 const records = (conversationId: string, kind: string) =>
1490 path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", kind);
1491 const write = (directory: string, name: string, value: unknown) =>
1492 fileSystem
1493 .makeDirectory(directory, { recursive: true })
1494 .pipe(
1495 Effect.andThen(
1496 fileSystem.writeFileString(path.join(directory, name), JSON.stringify(value)),
1497 ),
1498 );
1499 yield* write(records("mock-session-1", "subagents"), "child-1.json", {});
1500 yield* write(records("child-1", "messages"), "launch.json", {
1501 sender: "mock-session-1",
1502 sourceMetadata: { tool: { toolCall: { id: "call_research", name: "invoke_subagent" } } },
1503 });
1504 const opened = yield* openSessionWithRunningCommand({}, profile, {
1505 agentVersion: "1.5.11",
1506 holdsFirstPrompt: false,
1507 });
1508 const { session, providerThread, usage, send, startTurn, until, throughPromptSettled } =
1509 opened;
1510 yield* startTurn(1, false);
1511 const prompt = yield* throughPromptSettled;
1512 const providerTurnId = prompt.flatMap((event) =>
1513 event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1514 )[0]!;
1515 yield* TestClock.adjust("10 minutes");
1516
1517 yield* session.steerTurn({
1518 threadId: ThreadId.make("thread-antigravity-wake"),
1519 runId: RunId.make("run-antigravity-wake-1"),
1520 providerThread,
1521 providerTurnId,
1522 message: {
1523 messageId: MessageId.make("message-antigravity-steer"),
1524 text: "Also check the footnotes",
1525 attachments: [],
1526 createdBy: "user",
1527 creationSource: "web",
1528 },
1529 });
1530 assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's subagents");
1531 assert.lengthOf(opened.prompts, 2);
1532 yield* write(records("mock-session-1", "messages"), "report.json", { sender: "child-1" });
1533 yield* send({
1534 sessionUpdate: "agent_message_chunk",
1535 content: { type: "text", text: "I'll have the footnotes checked too." },
1536 });
1537 yield* send(usage);
1538 yield* opened.releaseSteer;
1539 const run = [...prompt, ...(yield* until((event) => event.type === "turn.terminal"))];
1540 const terminal = run.at(-1);
1541 assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1542 assert.include(JSON.stringify(run), "I'll have the footnotes checked too.");
1543 const subagentStatuses = run.flatMap((event) =>
1544 event.type === "subagent.updated" ? [event.subagent.status] : [],
1545 );
1546 assert.notInclude(subagentStatuses, "interrupted");
1547 assert.equal(subagentStatuses.at(-1), "idle");
1548 }).pipe(Effect.provide(layerSession)),
1549 );
1550
1551 // Files as agy 1.5.12 wrote them: the launch sits in the child's inbox, and the child's report
1552 // lands in the parent's inbox with no session update. Only the agent's own reply follows.
1553 it.effect.each([
1554 { reports: "after the prompt ends", duringPrompt: false },
1555 { reports: "while the prompt runs", duringPrompt: true },
1556 ])("keeps a detached subagent running until it reports $reports", ({ duringPrompt }) =>
1557 Effect.gen(function* () {
1558 const fileSystem = yield* FileSystem.FileSystem;
1559 const path = yield* Path.Path;
1560 const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" });
1561 const records = (conversationId: string, kind: string) =>
1562 path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", kind);
1563 const write = (directory: string, name: string, value: unknown) =>
1564 fileSystem
1565 .makeDirectory(directory, { recursive: true })
1566 .pipe(
1567 Effect.andThen(
1568 fileSystem.writeFileString(path.join(directory, name), JSON.stringify(value)),
1569 ),
1570 );
1571 yield* write(records("mock-session-1", "subagents"), "child-1.json", {});
1572 yield* write(records("child-1", "messages"), "launch.json", {
1573 sender: "mock-session-1",
1574 sourceMetadata: { tool: { toolCall: { id: "call_research", name: "invoke_subagent" } } },
1575 });
1576 const report = write(records("mock-session-1", "messages"), "report.json", {
1577 sender: "child-1",
1578 });
1579 if (duringPrompt) yield* report;
1580
1581 const { usage, offers, send, startTurn, until, throughPromptSettled } =
1582 yield* openSessionWithRunningCommand({}, profile);
1583 yield* startTurn(1, false);
1584 const statuses = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
1585 events.flatMap((event) =>
1586 event.type === "subagent.updated" ? [event.subagent.status] : [],
1587 );
1588 const prompt = yield* throughPromptSettled;
1589 assert.equal(statuses(prompt).at(-1), duringPrompt ? "idle" : "running");
1590 if (!duringPrompt) {
1591 yield* TestClock.adjust("10 minutes");
1592 yield* report;
1593 yield* send({
1594 sessionUpdate: "agent_message_chunk",
1595 content: { type: "text", text: "The researcher found it." },
1596 });
1597 yield* send(usage);
1598 yield* TestClock.adjust("3 seconds");
1599 }
1600 const run = yield* until((event) => event.type === "turn.terminal");
1601 const terminal = run.at(-1);
1602 assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1603 assert.equal(statuses([...prompt, ...run]).at(-1), "idle");
1604 assert.equal(
1605 JSON.stringify(run).includes("The researcher found it."),
1606 !duringPrompt,
1607 "the reply about the report is part of the run",
1608 );
1609 assert.lengthOf(offers, 0, "the open run needs no continuation");
1610 }).pipe(Effect.provide(layerSession)),
1611 );
1612
1613 it.effect("ends a continuation run whose replayed reply launched a subagent", () =>
1614 Effect.gen(function* () {
1615 const fileSystem = yield* FileSystem.FileSystem;
1616 // No records: nothing proves a child is at work, so none may hold a run open.
1617 const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" });
1618 const { usage, offers, send, startTurn, throughTerminal } =
1619 yield* openSessionWithRunningCommand({}, profile);
1620 yield* startTurn(1, false);
1621 yield* throughTerminal;
1622 yield* send({
1623 sessionUpdate: "tool_call",
1624 toolCallId: "call_follow_up",
1625 kind: "other",
1626 title: "Run invoke_subagent",
1627 status: "completed",
1628 rawInput: { TypeName: "research", Role: "Checker", Prompt: "Check it" },
1629 });
1630 yield* send({
1631 sessionUpdate: "agent_message_chunk",
1632 content: { type: "text", text: "Started a checker." },
1633 });
1634 yield* send(usage);
1635 assert.lengthOf(offers, 1, "the agent's own reply must wake the thread");
1636 yield* offers[0]!.dispatchIfCurrent!(Effect.void);
1637 yield* startTurn(2, true);
1638 yield* TestClock.adjust("3 seconds");
1639 const terminal = (yield* throughTerminal).at(-1);
1640 assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1641 }).pipe(Effect.provide(layerSession)),
1642 );
1643
1644 it.effect.each([
1645 // session/cancel ends the agent's commands, so only Stop may send it.
1646 { ending: "Stop", cancels: 1, status: "interrupted" },
1647 { ending: "a new message", cancels: 0, status: "interrupted" },
1648 { ending: "the agent exiting", cancels: 0, status: "failed" },
1649 ] as const)(
1650 "ends a run held open by a running command on $ending",
1651 ({ ending, cancels, status }) =>
1652 Effect.gen(function* () {
1653 const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 });
1654 yield* opened.startTurn(1, false);
1655 const started = yield* opened.throughPromptSettled;
1656 const turn = started.find((event) => event.type === "provider_turn.updated");
1657 if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start");
1658 if (ending === "the agent exiting") {
1659 yield* opened.runtimeDies;
1660 } else {
1661 yield* opened.session.interruptTurn({
1662 providerThread: opened.providerThread,
1663 providerTurnId: turn.providerTurn.id,
1664 ...(ending === "Stop" ? { requestRuntimeRestart: true } : {}),
1665 });
1666 }
1667 const terminal = (yield* opened.throughTerminal).at(-1);
1668 assert.equal(terminal?.type === "turn.terminal" && terminal.status, status);
1669 assert.equal(opened.cancels(), cancels);
1670 }).pipe(Effect.provide(layerSession)),
1671 );
1672 });
1673
1674 describe("AntigravityAdapterV2 subagent reads", () => {
1675 it.effect("completes a read T3 served when the agent later fails it with a step error", () =>
1676 Effect.gen(function* () {
1677 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1678 const fileSystem = yield* FileSystem.FileSystem;
1679 const path = yield* Path.Path;
1680 const crypto = yield* SecureRandom.SecureRandom;
1681 const mockAgentPath = yield* path.fromFileUrl(
1682 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1683 );
1684 const workspace = yield* fileSystem.makeTempDirectoryScoped({
1685 prefix: "t3-antigravity-reads-",
1686 });
1687 const outside = yield* fileSystem.makeTempDirectoryScoped({
1688 prefix: "t3-antigravity-reads-outside-",
1689 });
1690 const served = path.join(workspace, "served.ts");
1691 yield* fileSystem.writeFileString(served, "export {};");
1692 const denied = path.join(outside, "secret.txt");
1693 yield* fileSystem.writeFileString(denied, "secret");
1694 const unseen = path.join(workspace, "unseen.ts");
1695 const retried = path.join(workspace, "retried.ts");
1696 const stepError = 'Model produced invalid output. ("model output error")';
1697 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
1698 let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
1699 let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
1700 const instanceId = ProviderInstanceId.make("antigravity-subagent-reads-test");
1701 const threadId = ThreadId.make("thread-antigravity-subagent-reads");
1702 const adapter = yield* makeAntigravityAdapterV2({
1703 instanceId,
1704 selfInvocation: yield* resolveSelfInvocation(),
1705 makeRuntime: (input) =>
1706 makeAntigravityAcpRuntime({
1707 ...input,
1708 childProcessSpawner,
1709 spawn: {
1710 command: process.execPath,
1711 args: [mockAgentPath],
1712 cwd: input.cwd,
1713 env: { T3_ACP_ANTIGRAVITY: "1" },
1714 },
1715 }).pipe(
1716 Effect.provideService(SecureRandom.SecureRandom, crypto),
1717 Effect.map((runtime): RuntimeService => ({
1718 ...runtime,
1719 handleSessionUpdate: (handler) =>
1720 Effect.sync(() => {
1721 sessionUpdate = handler;
1722 }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
1723 handleReadTextFile: (handler) =>
1724 Effect.sync(() => {
1725 readTextFile = handler;
1726 }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))),
1727 // agy_acp_server announces a subagent's client_view_file on the parent session,
1728 // never completes it, then fails every open call with the next step error.
1729 prompt: () =>
1730 Effect.gen(function* () {
1731 if (sessionUpdate === undefined || readTextFile === undefined) {
1732 return yield* Effect.die("the adapter must handle updates and reads");
1733 }
1734 const send = sessionUpdate;
1735 const handleRead = readTextFile;
1736 const update = (update: EffectAcpSchema.SessionUpdate) =>
1737 send(
1738 normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }),
1739 );
1740 // The agent's own view_file never reaches T3, so it must not take a served read.
1741 const reads = [
1742 ["call_native", served, "Running view_file"],
1743 ["call_served", served, "Running client_view_file"],
1744 ["call_missing", retried, "Running client_view_file"],
1745 ["call_retried", retried, "Running client_view_file"],
1746 ["call_denied", denied, "Running client_view_file"],
1747 ["call_unseen", unseen, "Running client_view_file"],
1748 ] as const;
1749 for (const [toolCallId, target, title] of reads) {
1750 yield* update({
1751 sessionUpdate: "tool_call",
1752 toolCallId,
1753 title,
1754 kind: "read",
1755 status: "in_progress",
1756 rawInput: { absolute_path: target },
1757 locations: [{ path: target }],
1758 });
1759 }
1760 const serve = (target: string) =>
1761 handleRead(
1762 { sessionId: "subagent-conversation", path: target },
1763 { requestId: `read-${target}`, method: "fs/read_text_file" },
1764 ).pipe(Effect.exit);
1765 yield* serve(served);
1766 yield* serve(retried);
1767 yield* fileSystem.writeFileString(retried, "export {};").pipe(Effect.orDie);
1768 yield* serve(retried);
1769 yield* serve(denied);
1770 for (const [toolCallId] of reads) {
1771 yield* update({
1772 sessionUpdate: "tool_call_update",
1773 toolCallId,
1774 status: "failed",
1775 rawOutput: stepError,
1776 });
1777 }
1778 return { stopReason: "end_turn" as const };
1779 }),
1780 })),
1781 ),
1782 withProcess: (_stop, task) => task,
1783 defaultModel: Effect.undefined,
1784 });
1785 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1786 runtimeMode: "full-access",
1787 interactionMode: "default",
1788 cwd: workspace,
1789 });
1790 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
1791 const session = yield* adapter.openSession({
1792 threadId,
1793 providerSessionId: ProviderSessionId.make("provider-session-antigravity-subagent-reads"),
1794 modelSelection,
1795 runtimePolicy,
1796 });
1797 const providerThread = yield* session.ensureThread({
1798 threadId,
1799 modelSelection,
1800 runtimePolicy,
1801 });
1802 const now = yield* DateTime.now;
1803 yield* session.startTurn({
1804 appThread: {
1805 createdBy: "user",
1806 creationSource: "web",
1807 id: threadId,
1808 projectId: ProjectId.make("project-antigravity-subagent-reads"),
1809 title: "Antigravity subagent reads",
1810 providerInstanceId: instanceId,
1811 modelSelection,
1812 runtimeMode: "full-access",
1813 interactionMode: "default",
1814 branch: null,
1815 worktreePath: workspace,
1816 activeProviderThreadId: providerThread.id,
1817 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1818 forkedFrom: null,
1819 createdAt: now,
1820 updatedAt: now,
1821 archivedAt: null,
1822 settledOverride: null,
1823 settledAt: null,
1824 lastVisitedAt: null,
1825 deletedAt: null,
1826 },
1827 threadId,
1828 runId: RunId.make("run-antigravity-subagent-reads"),
1829 runOrdinal: 1,
1830 providerTurnOrdinal: 1,
1831 attemptId: RunAttemptId.make("attempt-antigravity-subagent-reads"),
1832 rootNodeId: NodeId.make("node-antigravity-subagent-reads"),
1833 providerThread,
1834 message: {
1835 createdBy: "user",
1836 creationSource: "web",
1837 messageId: MessageId.make("message-antigravity-subagent-reads"),
1838 text: "review the codebase",
1839 attachments: [],
1840 },
1841 modelSelection,
1842 runtimePolicy,
1843 });
1844 const events = Array.from(
1845 yield* session.events.pipe(
1846 Stream.takeUntil((event) => event.type === "turn.terminal"),
1847 Stream.runCollect,
1848 ),
1849 );
1850 const read = (nativeId: string) => {
1851 const event = events.findLast(
1852 (event) =>
1853 event.type === "turn_item.updated" &&
1854 event.turnItem.nativeItemRef?.nativeId === nativeId,
1855 );
1856 return event?.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
1857 ? { status: event.turnItem.status, output: event.turnItem.output }
1858 : undefined;
1859 };
1860
1861 const firstEvent = (nativeId: string, status: string) =>
1862 events.findIndex(
1863 (event) =>
1864 event.type === "turn_item.updated" &&
1865 event.turnItem.nativeItemRef?.nativeId === nativeId &&
1866 event.turnItem.status === status,
1867 );
1868 // T3 completes a served read itself instead of leaving it running until the flush.
1869 assert.isAbove(firstEvent("call_served", "completed"), -1);
1870 assert.isBelow(firstEvent("call_served", "completed"), firstEvent("call_native", "failed"));
1871 const failed = { status: "failed" as const, output: stepError };
1872 assert.deepEqual(read("call_served"), { status: "completed", output: undefined });
1873 assert.deepEqual(read("call_retried"), { status: "completed", output: undefined });
1874 assert.deepEqual(read("call_native"), failed);
1875 assert.deepEqual(read("call_missing"), failed);
1876 assert.deepEqual(read("call_denied"), failed);
1877 assert.deepEqual(read("call_unseen"), failed);
1878 }).pipe(Effect.provide(layerSession)),
1879 );
1880 });
1881
1882 describe("AntigravityAdapterV2 runtime mode ceiling", () => {
1883 const modesSetFor = (
1884 pickedMode: string,
1885 modes: Pick<ProviderAdapter.ProviderAdapterV2RuntimePolicy, "runtimeMode" | "maxRuntimeMode">,
1886 ) =>
1887 Effect.gen(function* () {
1888 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1889 const path = yield* Path.Path;
1890 const crypto = yield* SecureRandom.SecureRandom;
1891 const mockAgentPath = yield* path.fromFileUrl(
1892 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1893 );
1894 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
1895 const modesSet: Array<string> = [];
1896 const instanceId = ProviderInstanceId.make("antigravity-ceiling-test");
1897 const adapter = yield* makeAntigravityAdapterV2({
1898 instanceId,
1899 selfInvocation: yield* resolveSelfInvocation(),
1900 makeRuntime: (input) =>
1901 makeAntigravityAcpRuntime({
1902 ...input,
1903 childProcessSpawner,
1904 spawn: {
1905 command: process.execPath,
1906 args: [mockAgentPath],
1907 cwd: input.cwd,
1908 env: { T3_ACP_ANTIGRAVITY: "1" },
1909 },
1910 }).pipe(
1911 Effect.provideService(SecureRandom.SecureRandom, crypto),
1912 Effect.map((runtime): RuntimeService => ({
1913 ...runtime,
1914 setMode: (modeId) =>
1915 Effect.sync(() => {
1916 modesSet.push(modeId);
1917 }).pipe(Effect.andThen(runtime.setMode(modeId))),
1918 })),
1919 ),
1920 withProcess: (_stop, task) => task,
1921 defaultModel: Effect.undefined,
1922 });
1923 const threadId = ThreadId.make("thread-antigravity-ceiling");
1924 yield* adapter.openSession({
1925 threadId,
1926 providerSessionId: ProviderSessionId.make("provider-session-antigravity-ceiling"),
1927 modelSelection: {
1928 instanceId,
1929 model: "gemini-test-low",
1930 options: [{ id: "_t3/session-mode", value: pickedMode }],
1931 },
1932 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1933 ...modes,
1934 interactionMode: "default",
1935 cwd: process.cwd(),
1936 }),
1937 });
1938 return modesSet;
1939 }).pipe(Effect.provide(layerSession), Effect.scoped);
1940
1941 it.effect("does not apply a picked session mode above the thread's runtime mode", () =>
1942 Effect.gen(function* () {
1943 assert.deepEqual(yield* modesSetFor("yolo", { runtimeMode: "approval-required" }), [
1944 "default",
1945 ]);
1946 assert.deepEqual(
1947 yield* modesSetFor("auto_edit", {
1948 runtimeMode: "approval-required",
1949 maxRuntimeMode: "auto-accept-edits",
1950 }),
1951 ["default"],
1952 );
1953 // A narrower mode is still the user's to pick.
1954 assert.deepEqual(yield* modesSetFor("default", { runtimeMode: "auto-accept-edits" }), [
1955 "auto_edit",
1956 "default",
1957 ]);
1958 }),
1959 );
1960
1961 it.effect("leaving Plan keeps the permission mode the thread has now", () =>
1962 Effect.gen(function* () {
1963 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1964 const path = yield* Path.Path;
1965 const crypto = yield* SecureRandom.SecureRandom;
1966 const mockAgentPath = yield* path.fromFileUrl(
1967 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1968 );
1969 let runtime: AcpSessionRuntime.AcpSessionRuntime["Service"] | undefined;
1970 const instanceId = ProviderInstanceId.make("antigravity-plan-exit-test");
1971 const adapter = yield* makeAntigravityAdapterV2({
1972 instanceId,
1973 selfInvocation: yield* resolveSelfInvocation(),
1974 makeRuntime: (input) =>
1975 makeAntigravityAcpRuntime({
1976 ...input,
1977 childProcessSpawner,
1978 spawn: {
1979 command: process.execPath,
1980 args: [mockAgentPath],
1981 cwd: input.cwd,
1982 env: { T3_ACP_ANTIGRAVITY: "1" },
1983 },
1984 }).pipe(
1985 Effect.provideService(SecureRandom.SecureRandom, crypto),
1986 Effect.tap((made) =>
1987 Effect.sync(() => {
1988 runtime = made;
1989 }),
1990 ),
1991 ),
1992 withProcess: (_stop, task) => task,
1993 defaultModel: Effect.undefined,
1994 });
1995 const threadId = ThreadId.make("thread-antigravity-plan-exit");
1996 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
1997 const planPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1998 runtimeMode: "full-access",
1999 interactionMode: "plan",
2000 cwd: process.cwd(),
2001 });
2002 const session = yield* adapter.openSession({
2003 threadId,
2004 providerSessionId: ProviderSessionId.make("provider-session-antigravity-plan-exit"),
2005 modelSelection,
2006 runtimePolicy: planPolicy,
2007 });
2008 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
2009 yield* session.events.pipe(
2010 Stream.runForEach((event) => Queue.offer(events, event)),
2011 Effect.forkScoped,
2012 );
2013 const providerThread = yield* session.ensureThread({
2014 threadId,
2015 modelSelection,
2016 runtimePolicy: planPolicy,
2017 });
2018 const supervisedPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2019 runtimeMode: "approval-required",
2020 interactionMode: "default",
2021 cwd: process.cwd(),
2022 });
2023 yield* session.startTurn(
2024 makeTurnInput({
2025 threadId,
2026 providerThread,
2027 instanceId,
2028 runtimePolicy: supervisedPolicy,
2029 modelSelection,
2030 now: yield* DateTime.now,
2031 }),
2032 );
2033 yield* Stream.fromQueue(events).pipe(
2034 Stream.filter((event) => event.type === "turn.terminal"),
2035 Stream.runHead,
2036 );
2037 assert.equal((yield* runtime!.getModeState)?.currentModeId, "default");
2038 }).pipe(Effect.provide(layerSession), Effect.scoped),
2039 );
2040 });
2041
2042 describe("AntigravityAdapterV2 session system prompt", () => {
2043 it.effect.each(["1.5.0"])(
2044 "carries PR linking once per turn on %s, which does not advertise a system prompt append",
2045 (agentVersion) =>
2046 Effect.gen(function* () {
2047 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
2048 const fileSystem = yield* FileSystem.FileSystem;
2049 const path = yield* Path.Path;
2050 const crypto = yield* SecureRandom.SecureRandom;
2051 const mockAgentPath = yield* path.fromFileUrl(
2052 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
2053 );
2054 const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-log-" });
2055 const requestLog = path.join(logs, "requests.ndjson");
2056 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
2057 const promptReceived = yield* Deferred.make<Parameters<RuntimeService["prompt"]>[0]>();
2058 const instanceId = ProviderInstanceId.make("antigravity-system-prompt-test");
2059 const adapter = yield* makeAntigravityAdapterV2({
2060 instanceId,
2061 selfInvocation: yield* resolveSelfInvocation(),
2062 makeRuntime: (input) =>
2063 makeAntigravityAcpRuntime({
2064 ...input,
2065 childProcessSpawner,
2066 spawn: {
2067 command: process.execPath,
2068 args: [mockAgentPath],
2069 cwd: input.cwd,
2070 env: {
2071 T3_ACP_ANTIGRAVITY: "1",
2072 T3_ACP_AGENT_VERSION: agentVersion,
2073 T3_ACP_REQUEST_LOG_PATH: requestLog,
2074 T3_ACP_HANG_PROMPT_FOREVER: "1",
2075 },
2076 },
2077 }).pipe(
2078 Effect.provideService(SecureRandom.SecureRandom, crypto),
2079 Effect.map((runtime): RuntimeService => ({
2080 ...runtime,
2081 prompt: (request) =>
2082 Deferred.succeed(promptReceived, request).pipe(
2083 Effect.andThen(runtime.prompt(request)),
2084 ),
2085 })),
2086 ),
2087 withProcess: (_stop, task) => task,
2088 defaultModel: Effect.undefined,
2089 });
2090 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-sp-" });
2091 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2092 runtimeMode: "full-access",
2093 interactionMode: "default",
2094 cwd: workspace,
2095 });
2096 const threadId = ThreadId.make("thread-antigravity-system-prompt");
2097 const modelSelection = { instanceId, model: "gemini-test-low" } as const;
2098 const session = yield* adapter.openSession({
2099 threadId,
2100 providerSessionId: ProviderSessionId.make("provider-session-antigravity-system-prompt"),
2101 modelSelection,
2102 runtimePolicy,
2103 });
2104 const providerThread = yield* session.ensureThread({
2105 threadId,
2106 modelSelection,
2107 runtimePolicy,
2108 });
2109 const now = yield* DateTime.now;
2110 yield* session
2111 .startTurn({
2112 appThread: {
2113 createdBy: "user",
2114 creationSource: "web",
2115 id: threadId,
2116 projectId: ProjectId.make("project-antigravity-system-prompt"),
2117 title: "Antigravity system prompt",
2118 providerInstanceId: instanceId,
2119 modelSelection,
2120 runtimeMode: "full-access",
2121 interactionMode: "default",
2122 branch: null,
2123 worktreePath: null,
2124 activeProviderThreadId: providerThread.id,
2125 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
2126 forkedFrom: null,
2127 createdAt: now,
2128 updatedAt: now,
2129 archivedAt: null,
2130 settledOverride: null,
2131 settledAt: null,
2132 lastVisitedAt: null,
2133 deletedAt: null,
2134 },
2135 threadId,
2136 runId: RunId.make("run-antigravity-system-prompt"),
2137 runOrdinal: 1,
2138 providerTurnOrdinal: 1,
2139 attemptId: RunAttemptId.make("attempt-antigravity-system-prompt"),
2140 rootNodeId: NodeId.make("node-antigravity-system-prompt"),
2141 providerThread,
2142 message: {
2143 createdBy: "user",
2144 creationSource: "web",
2145 messageId: MessageId.make("message-antigravity-system-prompt"),
2146 text: "open a PR",
2147 attachments: [],
2148 },
2149 modelSelection,
2150 runtimePolicy,
2151 })
2152 .pipe(Effect.forkScoped);
2153 const sent = JSON.stringify((yield* Deferred.await(promptReceived)).prompt);
2154 const sessionNew = (yield* fileSystem.readFileString(requestLog))
2155 .trim()
2156 .split("\n")
2157 .map((line) => JSON.parse(line) as { method?: string; params?: { _meta?: unknown } })
2158 .find((request) => request.method === "session/new");
2159 const append = JSON.stringify(sessionNew?.params?._meta ?? null);
2160 // Identity stays per turn either way.
2161 assert.include(sent, "through the Antigravity harness, as gemini-test-low");
2162 assert.notInclude(append, "systemPrompt");
2163 assert.include(sent, "<pull_request_linking>");
2164 }).pipe(Effect.provide(layerSession)),
2165 );
2166 });