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

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

feat(antigravity): runtime 1.4.5 with real turn failures and subagent work (#28629)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Nov 1, 2026 at 22:32 UTC ab8e488e10d883fa880b0ddcf01917b51839ab07
45 files changed +3650 -142
apps/mobile/src/features/threads/NativeChildWorkSheet.tsx new
+116
@@ -0,0 +1,116 @@
1 +import type {
2 + EnvironmentId,
3 + OrchestrationV2GetNativeChildWorkResult,
4 + OrchestrationV2NativeChildWork,
5 + ThreadId,
6 +} from "@t3tools/contracts";
7 +import { ScrollView, View } from "react-native";
8 +import { useSafeAreaInsets } from "react-native-safe-area-context";
9 +
10 +import { AppText as Text } from "../../components/ui/AppText";
11 +import { Button } from "../../components/ui/Button";
12 +import { Sheet } from "../../components/ui/Sheet";
13 +import { orchestrationEnvironment } from "../../state/orchestration";
14 +import { useEnvironmentQuery } from "../../state/query";
15 +
16 +const stepLabel = (type: string) => {
17 + const words = type.toLowerCase().replaceAll("_", " ");
18 + return words.charAt(0).toUpperCase() + words.slice(1);
19 +};
20 +
21 +/** Read-only view of what a provider-native subagent's children did. Mount only while open. */
22 +export function NativeChildWorkSheet(props: {
23 + readonly environmentId: EnvironmentId;
24 + readonly threadId: ThreadId;
25 + readonly onClose: () => void;
26 +}) {
27 + const insets = useSafeAreaInsets();
28 + const query = useEnvironmentQuery<OrchestrationV2GetNativeChildWorkResult, unknown>(
29 + orchestrationEnvironment.nativeChildWork({
30 + environmentId: props.environmentId,
31 + input: { threadId: props.threadId },
32 + }),
33 + );
34 + const children = query.data?.children;
35 + return (
36 + <Sheet title="Subagent work" onClose={props.onClose}>
37 + <ScrollView
38 + contentInsetAdjustmentBehavior="automatic"
39 + contentContainerStyle={{
40 + gap: 16,
41 + paddingHorizontal: 20,
42 + paddingTop: 12,
43 + paddingBottom: Math.max(20, insets.bottom),
44 + }}
45 + >
46 + <Text className="font-sans text-xs text-foreground-secondary">
47 + Read only. These subagents cannot take messages.
48 + </Text>
49 + {query.error !== null ? (
50 + <Text selectable className="font-sans text-sm text-danger-foreground">
51 + {query.error}
52 + </Text>
53 + ) : children === undefined ? (
54 + <Text className="font-sans text-sm text-foreground-secondary">Loading…</Text>
55 + ) : children.length === 0 ? (
56 + <Text className="font-sans text-sm text-foreground-secondary">
57 + The provider has no record of which subagents this call started.
58 + </Text>
59 + ) : (
60 + children.map((child) => <NativeChild key={child.conversationId} child={child} />)
61 + )}
62 + <View className="flex-row justify-end">
63 + <Button
64 + label="Refresh"
65 + tone="secondary"
66 + disabled={query.isPending}
67 + onPress={query.refresh}
68 + />
69 + </View>
70 + </ScrollView>
71 + </Sheet>
72 + );
73 +}
74 +
75 +function NativeChild(props: { readonly child: OrchestrationV2NativeChildWork }) {
76 + const { child } = props;
77 + return (
78 + <View className="gap-2">
79 + <Text className="font-t3-bold text-sm text-foreground">{child.role || "Subagent"}</Text>
80 + <Text selectable className="font-sans text-sm text-foreground-secondary">
81 + {child.prompt}
82 + </Text>
83 + {child.truncated ? (
84 + <Text className="font-sans text-xs text-foreground-secondary">
85 + Earlier steps are not shown.
86 + </Text>
87 + ) : null}
88 + {child.steps === null ? (
89 + <Text className="font-sans text-xs text-foreground-secondary">No transcript yet.</Text>
90 + ) : (
91 + <View className="gap-2 border-l border-border ps-3">
92 + {child.steps.map((step) => (
93 + <View key={step.index} className="gap-1">
94 + <Text className="font-t3-bold text-xs text-foreground-secondary">
95 + {stepLabel(step.type)}
96 + {step.status !== null && step.status !== "DONE"
97 + ? ` · ${stepLabel(step.status)}`
98 + : ""}
99 + </Text>
100 + {step.toolCalls.length === 0 ? null : (
101 + <Text selectable className="font-mono text-xs text-foreground">
102 + {step.toolCalls.map((call) => `${call.name} ${call.input}`).join("\n")}
103 + </Text>
104 + )}
105 + {step.text === null ? null : (
106 + <Text selectable className="font-mono text-xs text-foreground">
107 + {step.text}
108 + </Text>
109 + )}
110 + </View>
111 + ))}
112 + </View>
113 + )}
114 + </View>
115 + );
116 +}
apps/mobile/src/features/threads/ProviderSubagentBar.tsx
+12 -1
@@ -2,12 +2,14 @@ import {
2 formatProviderSubagentStatus,
3 type ProviderSubagentStatus,
4 } from "@t3tools/client-runtime/state/thread-execution";
5 -import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
5 +import { isOrchestrationV2WorkActive, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
6 +import { useState } from "react";
7 import { View } from "react-native";
8
9 import { AppText as Text } from "../../components/ui/AppText";
10 import { ProviderIcon } from "../../components/ProviderIcon";
11 import { Button } from "../../components/ui/Button";
12 +import { NativeChildWorkSheet } from "./NativeChildWorkSheet";
13 import { useVisibleSecondClock } from "./use-visible-second-clock";
14
15 export function ProviderSubagentBar(props: {
@@ -16,7 +18,10 @@ export function ProviderSubagentBar(props: {
18 readonly effortLabel: string | null;
19 readonly status: ProviderSubagentStatus | null;
20 readonly onOpenParent: (() => void) | null;
21 + /** Set for providers whose children T3 reads on demand instead of streaming. */
22 + readonly inspect: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null;
23 }) {
24 + const [inspecting, setInspecting] = useState(false);
25 const live = props.status !== null && isOrchestrationV2WorkActive(props.status.status);
26 const nowMs = useVisibleSecondClock(live);
27 const statusLabel = formatProviderSubagentStatus(props.status, nowMs);
@@ -59,9 +64,15 @@ export function ProviderSubagentBar(props: {
64 {statusLabel} · Runs on its own
65 </Text>
66 </View>
67 + {props.inspect ? (
68 + <Button label="Work" tone="secondary" onPress={() => setInspecting(true)} />
69 + ) : null}
70 {props.onOpenParent ? (
71 <Button label="Open parent" tone="secondary" onPress={props.onOpenParent} />
72 ) : null}
73 + {props.inspect && inspecting ? (
74 + <NativeChildWorkSheet {...props.inspect} onClose={() => setInspecting(false)} />
75 + ) : null}
76 </View>
77 );
78 }
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+8
@@ -1722,6 +1722,14 @@ function ThreadDetailBody(
1722 reportedModelSelection,
1723 )}
1724 status={props.providerSubagentStatus ?? null}
1725 + inspect={
1726 + providerSubagentProvider?.driver === "antigravity"
1727 + ? {
1728 + environmentId: props.environmentId,
1729 + threadId: props.selectedThread.id,
1730 + }
1731 + : null
1732 + }
1733 onOpenParent={
1734 props.selectedThread.lineage.parentThreadId === null
1735 ? null
apps/server/scripts/acp-mock-agent.ts
+1 -1
@@ -512,7 +512,7 @@ const program = Effect.gen(function* () {
512 parameterizedModelPicker = request.capabilities?._meta?.parameterizedModelPicker === true;
513 return {
514 protocolVersion: 2,
515 - info: { name: "t3-acp-mock-agent", version: "0.0.0" },
515 + info: { name: "t3-acp-mock-agent", version: process.env.T3_ACP_AGENT_VERSION ?? "0.0.0" },
516 ...(omitInitializeModelState ? {} : { _meta: { modelState: modelState() } }),
517 capabilities: {
518 session: {
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -41,6 +41,7 @@ export const RPC_REQUIRED_SCOPES = {
41 ...CLIENT_GUARDED_RPC_SCOPES,
42 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
43 [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
44 + [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: AuthOrchestrationReadScope,
45 [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,
46 [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,
47 [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -13,6 +13,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
13 const RPC_AGGREGATES = {
14 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2",
15 [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration",
16 + [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: "orchestration",
17 [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: "orchestration",
18 [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: "orchestration",
19 [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration",
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+157
@@ -82,6 +82,7 @@ import {
82 acpPostSettleContinuationOfferEvidence,
83 acpPostSettleWakeEvidence,
84 acpToolCallDiffPatch,
85 + acpToolCallSnippetEdit,
86 makeAcpAdapterV2,
87 type AcpAdapterV2ExtensionContext,
88 type AcpAdapterV2Flavor,
@@ -138,6 +139,32 @@ describe("acpPerTurnPromptUsage", () => {
139 reasoningTokens: 3,
140 },
141 );
142 + // Antigravity 1.4.5: its harness reports prompt tokens without the 24 cached ones.
143 + assert.deepEqual(
144 + acpPerTurnPromptUsage(
145 + {
146 + inputTokens: 42,
147 + outputTokens: 3,
148 + totalTokens: 54,
149 + cachedReadTokens: 24,
150 + cachedWriteTokens: 0,
151 + thoughtTokens: 9,
152 + },
153 + false,
154 + "completed",
155 + true,
156 + ),
157 + {
158 + usageScope: "main_agent",
159 + usageStatus: "complete",
160 + hasSubagents: false,
161 + inputTokens: 66,
162 + outputTokens: 12,
163 + cachedInputTokens: 24,
164 + cacheCreationTokens: 0,
165 + reasoningTokens: 9,
166 + },
167 + );
168 });
169
170 it("clamps subsets that exceed their parents and drops unset counters", () => {
@@ -231,6 +258,45 @@ describe("acpPerTurnPromptUsage", () => {
258 });
259
260 describe("acpToolCallDiffPatch", () => {
261 + it("keeps an unplaced snippet as recorded text instead of numbering it from line 1", () => {
262 + const content = [
263 + {
264 + type: "diff",
265 + path: "/repo/a.ts",
266 + oldText: "const target = 10;",
267 + newText: "const target = 100;",
268 + patch: { format: "snippet", text: "@@ -1,1 +1,1 @@ snippet, line unknown\n" },
269 + },
270 + ];
271 + assert.isUndefined(acpToolCallDiffPatch(content));
272 + // An omitted preview is not re-diffed from the bare snippets either.
273 + assert.isUndefined(acpToolCallDiffPatch([{ ...content[0], patch: { format: "omitted" } }]));
274 + // A status block beside the snippet must not hide it.
275 + for (const blocks of [
276 + content,
277 + [{ type: "content", content: { type: "text", text: "Edited." } }, ...content],
278 + ]) {
279 + assert.isUndefined(acpToolCallDiffPatch(blocks));
280 + assert.deepEqual(acpToolCallSnippetEdit(blocks), {
281 + oldStr: "const target = 10;",
282 + newStr: "const target = 100;",
283 + });
284 + }
285 + // Beside another diff, the snippet is neither a patch nor a placed edit.
286 + const twoDiffs = [
287 + ...content,
288 + {
289 + type: "diff",
290 + path: "/repo/b.ts",
291 + oldText: "b\n",
292 + newText: "B\n",
293 + patch: { text: "@@ -1 +1 @@\n-b\n+B\n" },
294 + },
295 + ];
296 + assert.isUndefined(acpToolCallDiffPatch(twoDiffs));
297 + assert.isUndefined(acpToolCallSnippetEdit(twoDiffs));
298 + });
299 +
300 it("builds per-file patches from ACP hunks and recorded old/new text", () => {
301 for (const operation of ["add", "delete"]) {
302 const text = operation === "add" ? "@@ -0,0 +1 @@\n+content\n" : "@@ -1 +0,0 @@\n-content\n";
@@ -661,6 +727,97 @@ describe("AcpAdapterV2", () => {
727 assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt");
728 }).pipe(Effect.provide(layerTest), Effect.scoped),
729 );
730 + it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () =>
731 + Effect.gen(function* () {
732 + const path = yield* Path.Path;
733 + const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome");
734 + const threadId = ThreadId.make("thread-acp-prompt-outcome");
735 + const quota = {
736 + class: "usage_limit",
737 + message: "Quota reached.",
738 + code: "RESOURCE_EXHAUSTED",
739 + retryable: true,
740 + resetAt: "2030-01-01T00:00:00.000Z",
741 + } as const;
742 + // The runtime ordinal of each prompt, and the session each check watched.
743 + const promptRuntimes: Array<number> = [];
744 + const watchedSessions: Array<string> = [];
745 + const adapter = yield* makeAcpAdapterV2({
746 + instanceId,
747 + selfInvocation: yield* resolveSelfInvocation(),
748 + flavor: {
749 + driver: ACP_TEST_DRIVER,
750 + capabilities: AcpProviderCapabilitiesV2,
751 + watchPromptOutcome: (sessionId) =>
752 + Effect.sync(() => {
753 + watchedSessions.push(sessionId);
754 + const failed = watchedSessions.length === 1;
755 + return () => Effect.succeed(failed ? quota : undefined);
756 + }),
757 + makeRuntime: makeMockRuntime({
758 + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
759 + mockAgentPath: yield* path.fromFileUrl(
760 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
761 + ),
762 + wrapRuntime: (runtime, runtimeOrdinal) => ({
763 + ...runtime,
764 + prompt: () =>
765 + Effect.sync(() => {
766 + promptRuntimes.push(runtimeOrdinal);
767 + return { stopReason: "end_turn" as const };
768 + }),
769 + }),
770 + }),
771 + },
772 + });
773 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
774 + runtimeMode: "full-access",
775 + interactionMode: "default",
776 + cwd: process.cwd(),
777 + });
778 + const modelSelection = { instanceId, model: "default" } as const;
779 + const runtime = yield* adapter.openSession({
780 + threadId,
781 + providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"),
782 + modelSelection,
783 + runtimePolicy,
784 + });
785 + const providerThread = yield* runtime.ensureThread({
786 + threadId,
787 + modelSelection,
788 + runtimePolicy,
789 + });
790 + const runTurn = (ordinal: number) =>
791 + Effect.gen(function* () {
792 + yield* runtime.startTurn(
793 + makeTurnInput({
794 + threadId,
795 + providerThread,
796 + instanceId,
797 + runtimePolicy,
798 + now: yield* DateTime.now,
799 + ordinal,
800 + }),
801 + );
802 + const events = yield* runtime.events.pipe(
803 + Stream.takeUntil((event) => event.type === "turn.terminal"),
804 + Stream.runCollect,
805 + );
806 + return events.at(-1);
807 + });
808 +
809 + const failed = yield* runTurn(1);
810 + if (failed?.type !== "turn.terminal" || failed.status !== "failed") {
811 + return assert.fail("expected a failed terminal");
812 + }
813 + assert.deepEqual(failed.failure, quota);
814 + const completed = yield* runTurn(2);
815 + assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed");
816 + assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime");
817 + assert.equal(watchedSessions.length, 2);
818 + assert.equal(watchedSessions[0], watchedSessions[1]);
819 + }).pipe(Effect.provide(layerTest), Effect.scoped),
820 + );
821 it.live("retains returned usage when Stop finalizes before the prompt callback", () =>
822 Effect.gen(function* () {
823 const path = yield* Path.Path;
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+150 -6
@@ -31,7 +31,6 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
31 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
32 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
33 import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
34 -import { resolveAttachmentPath } from "../../attachmentStore.ts";
34 import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
35 import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts";
36 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -78,6 +77,21 @@ describe("AntigravityAdapterV2 flavor", () => {
77 assert.equal(batch?.prompt, "Started two agents.");
78 assert.isNull(batch?.result);
79 assert.isTrue(flavor.subagentsIdleOnTurnCompletion);
80 +
81 + // Permission prompts carry the launch; later updates for the same call do not.
82 + const launch = flavor.extractSubagentUpdate?.({
83 + toolCallId: "35bea692fa95447fbdae6333fec5515f",
84 + title: "Run invoke_subagent?",
85 + kind: "other",
86 + status: "pending",
87 + data: {
88 + rawInput: {
89 + Subagents: [{ TypeName: "research", Role: "Readme Reader", Prompt: "Read README.md" }],
90 + },
91 + },
92 + });
93 + assert.equal(launch?.title, "Readme Reader");
94 + assert.equal(launch?.prompt, "Read README.md");
95 });
96
97 it("routes interaction_* permission requests to the question card", () => {
@@ -395,10 +409,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {
409 mimeType: "application/pdf",
410 sizeBytes: 9,
411 });
398 - const documentPath = resolveAttachmentPath({
399 - attachmentsDir: host.paths.attachmentsDir,
400 - attachment: document,
401 - })!;
412 + const documentPath = host.resolveAttachmentPath(document)!;
413 yield* fileSystem.writeFileString(documentPath, "%PDF-1.7");
414 let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
415 const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test");
@@ -526,10 +537,11 @@ describe("AntigravityAdapterV2 workspace changes", () => {
537 uri: (yield* path.toFileUrl(documentPath)).href,
538 name: "diagram.pdf",
539 mimeType: "application/pdf",
540 + size: 8,
541 },
542 ],
543 );
532 - assert.include(JSON.stringify(sent.prompt), host.resolveAttachmentPath(document)!);
544 + assert.include(JSON.stringify(sent.prompt), documentPath);
545 if (readTextFile === undefined) {
546 return yield* Effect.die("Antigravity sessions must serve client file requests");
547 }
@@ -1104,3 +1116,135 @@ describe("AntigravityAdapterV2 runtime mode ceiling", () => {
1116 }),
1117 );
1118 });
1119 +
1120 +describe("AntigravityAdapterV2 session system prompt", () => {
1121 + it.effect.each(["1.4.5", "1.4.1"])(
1122 + "carries PR linking once in the %s session setup or once per turn",
1123 + (agentVersion) =>
1124 + Effect.gen(function* () {
1125 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1126 + const fileSystem = yield* FileSystem.FileSystem;
1127 + const path = yield* Path.Path;
1128 + const crypto = yield* Crypto.Crypto;
1129 + const mockAgentPath = yield* path.fromFileUrl(
1130 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1131 + );
1132 + const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-log-" });
1133 + const requestLog = path.join(logs, "requests.ndjson");
1134 + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
1135 + const promptReceived = yield* Deferred.make<Parameters<RuntimeService["prompt"]>[0]>();
1136 + const instanceId = ProviderInstanceId.make("antigravity-system-prompt-test");
1137 + const adapter = yield* makeAntigravityAdapterV2({
1138 + instanceId,
1139 + selfInvocation: yield* resolveSelfInvocation(),
1140 + makeRuntime: (input) =>
1141 + makeAntigravityAcpRuntime({
1142 + ...input,
1143 + childProcessSpawner,
1144 + spawn: {
1145 + command: process.execPath,
1146 + args: [mockAgentPath],
1147 + cwd: input.cwd,
1148 + env: {
1149 + T3_ACP_ANTIGRAVITY: "1",
1150 + T3_ACP_AGENT_VERSION: agentVersion,
1151 + T3_ACP_REQUEST_LOG_PATH: requestLog,
1152 + T3_ACP_HANG_PROMPT_FOREVER: "1",
1153 + },
1154 + },
1155 + }).pipe(
1156 + Effect.provideService(Crypto.Crypto, crypto),
1157 + Effect.map((runtime): RuntimeService => ({
1158 + ...runtime,
1159 + prompt: (request) =>
1160 + Deferred.succeed(promptReceived, request).pipe(
1161 + Effect.andThen(runtime.prompt(request)),
1162 + ),
1163 + })),
1164 + ),
1165 + withProcess: (_stop, task) => task,
1166 + // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
1167 + defaultModel: Effect.succeed(undefined),
1168 + });
1169 + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-sp-" });
1170 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1171 + runtimeMode: "full-access",
1172 + interactionMode: "default",
1173 + cwd: workspace,
1174 + });
1175 + const threadId = ThreadId.make("thread-antigravity-system-prompt");
1176 + const modelSelection = { instanceId, model: "gemini-test-low" } as const;
1177 + const session = yield* adapter.openSession({
1178 + threadId,
1179 + providerSessionId: ProviderSessionId.make("provider-session-antigravity-system-prompt"),
1180 + modelSelection,
1181 + runtimePolicy,
1182 + });
1183 + const providerThread = yield* session.ensureThread({
1184 + threadId,
1185 + modelSelection,
1186 + runtimePolicy,
1187 + });
1188 + const now = yield* DateTime.now;
1189 + yield* session
1190 + .startTurn({
1191 + appThread: {
1192 + createdBy: "user",
1193 + creationSource: "web",
1194 + id: threadId,
1195 + projectId: ProjectId.make("project-antigravity-system-prompt"),
1196 + title: "Antigravity system prompt",
1197 + providerInstanceId: instanceId,
1198 + modelSelection,
1199 + runtimeMode: "full-access",
1200 + interactionMode: "default",
1201 + branch: null,
1202 + worktreePath: null,
1203 + activeProviderThreadId: providerThread.id,
1204 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1205 + forkedFrom: null,
1206 + createdAt: now,
1207 + updatedAt: now,
1208 + archivedAt: null,
1209 + settledOverride: null,
1210 + settledAt: null,
1211 + lastVisitedAt: null,
1212 + deletedAt: null,
1213 + },
1214 + threadId,
1215 + runId: RunId.make("run-antigravity-system-prompt"),
1216 + runOrdinal: 1,
1217 + providerTurnOrdinal: 1,
1218 + attemptId: RunAttemptId.make("attempt-antigravity-system-prompt"),
1219 + rootNodeId: NodeId.make("node-antigravity-system-prompt"),
1220 + providerThread,
1221 + message: {
1222 + createdBy: "user",
1223 + creationSource: "web",
1224 + messageId: MessageId.make("message-antigravity-system-prompt"),
1225 + text: "open a PR",
1226 + attachments: [],
1227 + },
1228 + modelSelection,
1229 + runtimePolicy,
1230 + })
1231 + .pipe(Effect.forkScoped);
1232 + const sent = JSON.stringify((yield* Deferred.await(promptReceived)).prompt);
1233 + const sessionNew = (yield* fileSystem.readFileString(requestLog))
1234 + .trim()
1235 + .split("\n")
1236 + .map((line) => JSON.parse(line) as { method?: string; params?: { _meta?: unknown } })
1237 + .find((request) => request.method === "session/new");
1238 + const append = JSON.stringify(sessionNew?.params?._meta ?? null);
1239 + // Identity stays per turn either way.
1240 + assert.include(sent, "through the Antigravity harness, as gemini-test-low");
1241 + if (agentVersion === "1.4.5") {
1242 + assert.include(append, "pull_request_linking");
1243 + assert.notInclude(sent, "<pull_request_linking>");
1244 + } else {
1245 + assert.notInclude(append, "systemPrompt");
1246 + assert.include(sent, "<pull_request_linking>");
1247 + }
1248 + }).pipe(Effect.provide(layerSession), Effect.scoped),
1249 + );
1250 +});
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+44 -5
@@ -16,16 +16,24 @@ import * as Scope from "effect/Scope";
16 import * as EffectAcpErrors from "effect-acp/errors";
17
18 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
19 +import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions";
20 import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";
21 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
22 import {
23 + antigravityAppendsSystemPrompt,
24 antigravityPermissionMode,
25 antigravityRuntimeModeForSessionMode,
26 applyAntigravityAcpModelSelection,
27 buildAntigravityPrompt,
28 type AntigravityAcpRuntimeInput,
29 } from "../../provider/acp/AntigravityAcpSupport.ts";
30 +import {
31 + ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
32 + antigravitySubagentLaunches,
33 + describeAntigravitySubagentLaunches,
34 +} from "../../provider/acp/AntigravityChildWork.ts";
35 import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts";
36 +import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts";
37 import {
38 antigravityApprovalOptions,
39 antigravitySubagentOutput,
@@ -81,9 +89,14 @@ export interface AntigravityAdapterV2Options {
89 readonly onSessionEvent?: AcpAdapterV2Flavor["onSessionEvent"];
90 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
91 readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
92 + /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */
93 + readonly profileDirectory?: string;
94 }
95
86 -/** Native subagent tools report no child session ids. */
96 +/**
97 + * Native subagent tools report no child session ids, so children stay read-only.
98 + * Only permission prompts carry the launch; NativeChildWorkQuery matches their ids by this text.
99 + */
100 const extractAntigravitySubagentUpdate: NonNullable<AcpAdapterV2Flavor["extractSubagentUpdate"]> = (
101 toolCall,
102 ) => {
@@ -92,14 +105,17 @@ const extractAntigravitySubagentUpdate: NonNullable<AcpAdapterV2Flavor["extractS
105 }
106 const status =
107 toolCall.status === "failed" ? "failed" : toolCall.status === "pending" ? "pending" : "running";
108 + const launches = antigravitySubagentLaunches(toolCall.data.rawInput);
109 + const launch = launches === undefined ? undefined : describeAntigravitySubagentLaunches(launches);
110 return {
111 nativeTaskId: toolCall.toolCallId,
112 prompt:
113 + launch?.prompt ??
114 antigravitySubagentOutput(toolCall) ??
115 toolCall.detail ??
116 toolCall.title ??
101 - "Antigravity subagent batch",
102 - title: "Antigravity subagent batch",
117 + ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
118 + title: launch?.title ?? ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
119 model: null,
120 status,
121 childSessionId: null,
@@ -117,6 +133,7 @@ interface AntigravityFlavorServices {
133 export function makeAntigravityAcpAdapterFlavor(
134 options: AntigravityAdapterV2Options & AntigravityFlavorServices,
135 ): AcpAdapterV2Flavor {
136 + const { profileDirectory } = options;
137 const antigravityClientFileRoots = (cwd: string | null) =>
138 cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];
139 const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")(
@@ -128,6 +145,7 @@ export function makeAntigravityAcpAdapterFlavor(
145 options.makeRuntime({
146 ...input,
147 clientFileReads: true,
148 + sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS,
149 additionalDirectories: [options.host.paths.attachmentsDir],
150 }),
151 )
@@ -190,13 +208,25 @@ export function makeAntigravityAcpAdapterFlavor(
208 driver: ANTIGRAVITY_PROVIDER,
209 runtimeHarness: "Antigravity",
210 capabilities: AntigravityProviderCapabilitiesV2,
211 + // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio.
212 + mcpOverHttp: true,
213 + sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt,
214 makeRuntime,
194 - buildPrompt: ({ text, attachments, promptCapabilities }) =>
215 + buildPrompt: ({
216 + text,
217 + attachments,
218 + resolveAttachmentPath,
219 + promptCapabilities,
220 + agentVersion,
221 + currentModel,
222 + }) =>
223 buildAntigravityPrompt({
224 input: text,
225 attachments,
198 - attachmentsDir: options.host.paths.attachmentsDir,
226 + resolveAttachmentPath,
227 promptCapabilities,
228 + agentVersion,
229 + currentModel,
230 }).pipe(
231 Effect.provideService(FileSystem.FileSystem, options.fileSystem),
232 Effect.provideService(Path.Path, options.path),
@@ -243,6 +273,15 @@ export function makeAntigravityAcpAdapterFlavor(
273 // ACP 1.3.0 treats /compact as ordinary model input.
274 supportsCompaction: false,
275 requiresSignIn: isAntigravitySignInRequiredError,
276 + // 1.4.5 returns the root trajectory's Gemini usageMetadata delta; 1.4.1 returns none.
277 + reportsPerTurnPromptUsage: true,
278 + geminiPromptUsage: true,
279 + ...(profileDirectory === undefined
280 + ? {}
281 + : {
282 + watchPromptOutcome: (sessionId: string) =>
283 + watchAntigravityPromptOutcome(profileDirectory, sessionId),
284 + }),
285 };
286 }
287
apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts new
+117
@@ -0,0 +1,117 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { expect, it } from "@effect/vitest";
3 +import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +
7 +import * as ServerConfig from "../config.ts";
8 +import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";
9 +import {
10 + ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
11 + describeAntigravitySubagentLaunches,
12 +} from "../provider/acp/AntigravityChildWork.ts";
13 +import {
14 + CHILD,
15 + invokeStep,
16 + LAUNCH,
17 + makeProfile,
18 + ROOT,
19 +} from "../provider/acp/AntigravityChildWork.testkit.ts";
20 +import * as NativeChildWorkQuery from "./NativeChildWorkQuery.ts";
21 +import * as ThreadManagement from "./ThreadManagementService.ts";
22 +
23 +const instanceId = ProviderInstanceId.make("antigravity");
24 +const childThreadId = ThreadId.make("thread-child");
25 +const launch = describeAntigravitySubagentLaunches([LAUNCH]);
26 +
27 +// A permission-prompt batch in session ROOT, plus an older batch with no launch text in `olderRun`.
28 +const records = (olderRun: string) => ({
29 + thread: {
30 + id: childThreadId,
31 + creationSource: "provider",
32 + lineage: { parentThreadId: "thread-parent", relationshipToParent: "subagent" },
33 + forkedFrom: { type: "node", nodeId: "subagent-new" },
34 + },
35 + subagents: [
36 + {
37 + id: "subagent-new",
38 + childThreadId,
39 + driver: "antigravity",
40 + origin: "provider_native",
41 + providerInstanceId: instanceId,
42 + runId: "run-root",
43 + nativeTaskRef: { nativeId: "35bea692fa95447fbdae6333fec5515f" },
44 + ...launch,
45 + },
46 + {
47 + id: "subagent-old",
48 + childThreadId: "thread-old",
49 + driver: "antigravity",
50 + origin: "provider_native",
51 + providerInstanceId: instanceId,
52 + runId: olderRun,
53 + nativeTaskRef: { nativeId: "0ld" },
54 + title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
55 + prompt: "Running",
56 + },
57 + ],
58 + runs: [
59 + { id: "run-root", providerThreadId: "provider-root" },
60 + { id: "run-root-earlier", providerThreadId: "provider-root" },
61 + { id: "run-other", providerThreadId: "provider-other" },
62 + ],
63 + providerThreads: [
64 + { id: "provider-root", providerInstanceId: instanceId, nativeThreadRef: { nativeId: ROOT } },
65 + {
66 + id: "provider-other",
67 + providerInstanceId: instanceId,
68 + nativeThreadRef: { nativeId: "00000000-0000-4000-8000-000000000000" },
69 + },
70 + ],
71 +});
72 +
73 +const readChildren = (olderRun: string) =>
74 + Effect.gen(function* () {
75 + const query = yield* NativeChildWorkQuery.NativeChildWorkQuery;
76 + return (yield* query.getNativeChildWork({ threadId: childThreadId })).children;
77 + }).pipe(
78 + Effect.provide(
79 + NativeChildWorkQuery.layer.pipe(
80 + Layer.provide(
81 + Layer.mock(ThreadManagement.ThreadManagementService)({
82 + getThreadRecords: () => Effect.succeed(records(olderRun) as never),
83 + }),
84 + ),
85 + ),
86 + ),
87 + );
88 +
89 +it.layer(
90 + Layer.mergeAll(
91 + NodeServices.layer,
92 + ServerConfig.layerTest(process.cwd(), { prefix: "native-child-work-" }).pipe(
93 + Layer.provide(NodeServices.layer),
94 + ),
95 + ),
96 +)("NativeChildWorkQuery", (it) => {
97 + it.effect("weighs only batches from the same agent session", () =>
98 + Effect.gen(function* () {
99 + const { stateDir } = yield* ServerConfig.ServerConfig;
100 + const { profile } = yield* resolveAntigravityInstanceDirectories(stateDir, instanceId);
101 + yield* makeProfile({
102 + profile,
103 + steps: (logUri) => [
104 + [
105 + 2,
106 + 127,
107 + invokeStep({ callId: "x", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
108 + ],
109 + ],
110 + });
111 + const fromOtherSession = yield* readChildren("run-other");
112 + expect(fromOtherSession.map((child) => child.conversationId)).toEqual([CHILD]);
113 + // An earlier run in the same session may own the only record.
114 + expect(yield* readChildren("run-root-earlier")).toEqual([]);
115 + }),
116 + );
117 +});
apps/server/src/orchestration-v2/NativeChildWorkQuery.ts new
+116
@@ -0,0 +1,116 @@
1 +import {
2 + isProviderNativeSubagentThread,
3 + OrchestrationV2GetNativeChildWorkError,
4 + type OrchestrationV2GetNativeChildWorkInput,
5 + type OrchestrationV2GetNativeChildWorkResult,
6 +} from "@t3tools/contracts";
7 +import * as Context from "effect/Context";
8 +import * as Crypto from "effect/Crypto";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Path from "effect/Path";
12 +
13 +import * as ServerConfig from "../config.ts";
14 +import { readAntigravityChildWork } from "../provider/acp/AntigravityChildWork.ts";
15 +import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";
16 +import * as ThreadManagement from "./ThreadManagementService.ts";
17 +
18 +/** Reads what a provider-native subagent's children did, on demand. Other providers stream real child sessions. */
19 +export class NativeChildWorkQuery extends Context.Service<
20 + NativeChildWorkQuery,
21 + {
22 + readonly getNativeChildWork: (
23 + input: OrchestrationV2GetNativeChildWorkInput,
24 + ) => Effect.Effect<
25 + OrchestrationV2GetNativeChildWorkResult,
26 + OrchestrationV2GetNativeChildWorkError
27 + >;
28 + }
29 +>()("t3/orchestration-v2/NativeChildWorkQuery") {}
30 +
31 +const NO_CHILDREN: OrchestrationV2GetNativeChildWorkResult = { children: [] };
32 +
33 +const make = Effect.gen(function* () {
34 + const threads = yield* ThreadManagement.ThreadManagementService;
35 + const { stateDir } = yield* ServerConfig.ServerConfig;
36 + const crypto = yield* Crypto.Crypto;
37 + const path = yield* Path.Path;
38 +
39 + const getNativeChildWork = Effect.fn("NativeChildWorkQuery.getNativeChildWork")(
40 + function* (input: OrchestrationV2GetNativeChildWorkInput) {
41 + const { thread } = yield* threads.getThreadRecords(input.threadId, []);
42 + const parentThreadId = thread.lineage.parentThreadId;
43 + if (
44 + !isProviderNativeSubagentThread(thread) ||
45 + parentThreadId === null ||
46 + thread.forkedFrom?.type !== "node"
47 + ) {
48 + return NO_CHILDREN;
49 + }
50 + const subagentId = thread.forkedFrom.nodeId;
51 + const { subagents } = yield* threads.getThreadRecords(parentThreadId, ["subagents"]);
52 + const subagent = subagents.find(
53 + (candidate) => candidate.id === subagentId && candidate.childThreadId === thread.id,
54 + );
55 + const nativeTaskId = subagent?.nativeTaskRef?.nativeId;
56 + if (
57 + subagent?.driver !== "antigravity" ||
58 + subagent.origin !== "provider_native" ||
59 + subagent.runId === null ||
60 + !nativeTaskId
61 + ) {
62 + return NO_CHILDREN;
63 + }
64 + const others = subagents.filter(
65 + (candidate) =>
66 + candidate.id !== subagent.id &&
67 + candidate.driver === "antigravity" &&
68 + candidate.origin === "provider_native" &&
69 + candidate.providerInstanceId === subagent.providerInstanceId,
70 + );
71 + const { runs, providerThreads } = yield* threads.getThreadRecords(
72 + parentThreadId,
73 + ["runs", "providerThreads"],
74 + { runIds: [subagent.runId, ...others.flatMap((other) => other.runId ?? [])] },
75 + );
76 + const providerThreadOf = (runId: string | null) => {
77 + const providerThreadId = runs.find((run) => run.id === runId)?.providerThreadId;
78 + return providerThreads.find((candidate) => candidate.id === providerThreadId);
79 + };
80 + const providerThread = providerThreadOf(subagent.runId);
81 + const rootSessionId = providerThread?.nativeThreadRef?.nativeId;
82 + if (!rootSessionId || providerThread?.providerInstanceId !== subagent.providerInstanceId) {
83 + return NO_CHILDREN;
84 + }
85 + const directories = yield* resolveAntigravityInstanceDirectories(
86 + stateDir,
87 + subagent.providerInstanceId,
88 + ).pipe(Effect.provideService(Crypto.Crypto, crypto), Effect.provideService(Path.Path, path));
89 + const children = yield* readAntigravityChildWork({
90 + profileDirectory: directories.profile,
91 + rootSessionId,
92 + nativeTaskId,
93 + launch: { title: subagent.title, prompt: subagent.prompt },
94 + // Only batches from the same agent session can share its records.
95 + siblings: others.flatMap((other) => {
96 + const id = other.nativeTaskRef?.nativeId;
97 + return id && providerThreadOf(other.runId)?.nativeThreadRef?.nativeId === rootSessionId
98 + ? [{ nativeTaskId: id, title: other.title, prompt: other.prompt }]
99 + : [];
100 + }),
101 + });
102 + return { children };
103 + },
104 + (effect, input) =>
105 + effect.pipe(
106 + Effect.mapError(
107 + (cause) =>
108 + new OrchestrationV2GetNativeChildWorkError({ threadId: input.threadId, cause }),
109 + ),
110 + ),
111 + );
112 +
113 + return NativeChildWorkQuery.of({ getNativeChildWork });
114 +});
115 +
116 +export const layer = Layer.effect(NativeChildWorkQuery, make);
apps/server/src/provider/AntigravityProvider.test.ts
+99 -4
@@ -24,6 +24,7 @@ import * as ServerSettings from "../serverSettings.ts";
24 import * as ProviderHostLive from "./ProviderHostLive.ts";
25 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
27 +import type { ServerProvider } from "@t3tools/contracts";
28 import {
29 buildAntigravityModelsFromSession,
30 makeAntigravityProvider,
@@ -167,6 +168,11 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
168 Effect.andThen(initialUpdate),
169 Effect.asVoid,
170 );
171 + // Subscribe before the trigger; yield the returned pull to await the publish.
172 + const nextPublish = (predicate: (snapshot: ServerProvider) => boolean) =>
173 + Stream.toPull(provider.snapshot.streamChanges.pipe(Stream.filter(predicate))).pipe(
174 + Effect.map((pull) => pull.pipe(Effect.map((snapshots) => snapshots[0]))),
175 + );
176 return {
177 provider,
178 probe,
@@ -176,6 +182,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
182 initialProbe,
183 initialUpdate,
184 initialize,
185 + nextPublish,
186 };
187 });
188
@@ -687,15 +694,29 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
694 };
695 const usage = yield* Ref.make(limits);
696 const harness = yield* makeHarness({ probeUsage: Ref.get(usage) });
697 + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
698 yield* harness.initialize;
691 - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
692 - yield* Ref.set(harness.probe, Effect.succeed(initializeResult));
699 + expect((yield* published)?.usageLimits).toEqual(limits);
700 + // The second health check is the one the failed background read triggers.
701 + const checks = yield* Ref.make(0);
702 + const failedReadApplied = yield* Deferred.make<void>();
703 + yield* Ref.set(
704 + harness.probe,
705 + Ref.updateAndGet(checks, (count) => count + 1).pipe(
706 + Effect.tap((count) =>
707 + count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void,
708 + ),
709 + Effect.as(initializeResult),
710 + ),
711 + );
712 yield* Ref.set(usage, {
713 checkedAt: "2026-10-09T12:01:00.000Z",
714 windows: [],
715 unavailable: { reason: "probeFailed" },
716 });
698 - expect((yield* harness.provider.snapshot.refresh).usageLimits).toEqual(limits);
717 + yield* harness.provider.snapshot.refresh;
718 + yield* Deferred.await(failedReadApplied);
719 + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
720 yield* harness.provider.onSignedOut;
721 expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
722 yield* Ref.set(usage, {
@@ -703,7 +724,11 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
724 windows: [],
725 unavailable: { reason: "unsupported" },
726 });
706 - expect((yield* harness.provider.snapshot.refresh).usageLimits?.windows).toEqual([]);
727 + const unsupported = yield* harness.nextPublish(
728 + (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",
729 + );
730 + yield* harness.provider.snapshot.refresh;
731 + expect((yield* unsupported)?.usageLimits?.windows).toEqual([]);
732 }),
733 ),
734 );
@@ -737,4 +762,74 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
762 }),
763 ),
764 );
765 +
766 + it.effect("reports ready and starts sessions while one shared quota read is pending", () =>
767 + Effect.scoped(
768 + Effect.gen(function* () {
769 + const reads = yield* Ref.make(0);
770 + const readStarted = yield* Deferred.make<void>();
771 + const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
772 + const harness = yield* makeHarness({
773 + probeUsage: Ref.update(reads, (count) => count + 1).pipe(
774 + Effect.andThen(Deferred.succeed(readStarted, undefined)),
775 + Effect.andThen(Deferred.await(readResult)),
776 + ),
777 + });
778 + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
779 + yield* harness.initialize;
780 + yield* Deferred.await(readStarted);
781 + yield* harness.provider.onSessionStarted(started, "/workspace");
782 + yield* harness.provider.onSessionStarted(started, "/other");
783 + const ready = yield* harness.provider.snapshot.getSnapshot;
784 + expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } });
785 + expect(ready.usageLimits).toBeUndefined();
786 + expect(yield* Ref.get(reads)).toBe(1);
787 + const limits = {
788 + checkedAt: "2026-10-09T12:00:00.000Z",
789 + windows: [
790 + { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 },
791 + ],
792 + } satisfies ServerProviderUsageLimits;
793 + yield* Deferred.succeed(readResult, limits);
794 + expect((yield* published)?.usageLimits).toEqual(limits);
795 + }),
796 + ),
797 + );
798 +
799 + it.effect("a quota read for the previous account is dropped after a new sign-in", () =>
800 + Effect.scoped(
801 + Effect.gen(function* () {
802 + const oldReadStarted = yield* Deferred.make<void>();
803 + const newLimits = {
804 + checkedAt: "2026-10-09T12:01:00.000Z",
805 + windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }],
806 + } satisfies ServerProviderUsageLimits;
807 + const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
808 + Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)),
809 + );
810 + const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
811 + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
812 + yield* harness.initialize;
813 + yield* Deferred.await(oldReadStarted);
814 + yield* Ref.set(usage, Effect.succeed(newLimits));
815 + yield* harness.provider.onSignedIn;
816 + yield* harness.provider.onSessionStarted(started);
817 + expect((yield* published)?.usageLimits).toEqual(newLimits);
818 + // Switching again must not republish the previous account's limits, even if the read fails.
819 + const failed = {
820 + checkedAt: "2026-10-09T12:02:00.000Z",
821 + windows: [],
822 + unavailable: { reason: "probeFailed" },
823 + } satisfies ServerProviderUsageLimits;
824 + yield* Ref.set(usage, Effect.succeed(failed));
825 + const republished = yield* harness.nextPublish(
826 + (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",
827 + );
828 + yield* harness.provider.onSignedIn;
829 + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
830 + yield* harness.provider.onSessionStarted(started);
831 + expect((yield* republished)?.usageLimits).toEqual(failed);
832 + }),
833 + ),
834 + );
835 });
apps/server/src/provider/AntigravityProvider.ts
+70 -17
@@ -9,8 +9,11 @@ import {
9 type ServerProviderUsageLimits,
10 } from "@t3tools/contracts";
11 import { createModelCapabilities } from "@t3tools/shared/model";
12 +import * as Context from "effect/Context";
13 import * as DateTime from "effect/DateTime";
14 +import * as Deferred from "effect/Deferred";
15 import * as Effect from "effect/Effect";
16 +import * as FiberHandle from "effect/FiberHandle";
17 import * as Option from "effect/Option";
18 import * as Predicate from "effect/Predicate";
19 import * as Result from "effect/Result";
@@ -41,6 +44,10 @@ const HEALTH_CHECK_TIMEOUT = "90 seconds";
44 const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity.";
45 const AUTH_UNCHECKED_MESSAGE =
46 "Antigravity is installed. Google account access is not checked yet.";
47 +// Set while a finished quota read republishes, so that health check does not read again.
48 +const PublishingUsage = Context.Reference<boolean>("t3/provider/AntigravityPublishingUsage", {
49 + defaultValue: () => false,
50 +});
51
52 type SessionSetupResult = Pick<
53 AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
@@ -215,6 +222,47 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
222 Effect.flatMap((state) => options.stampIdentity(state.draft)),
223 );
224
225 + // The quota read can take 30 seconds, so it never blocks readiness or a session start.
226 + // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands.
227 + const usageRead = yield* FiberHandle.make();
228 + const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();
229 + const scope = yield* Effect.scope;
230 + const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {
231 + if (!options.probeUsage || (yield* PublishingUsage)) return;
232 + yield* FiberHandle.run(
233 + usageRead,
234 + options.probeUsage.pipe(
235 + Effect.flatMap((probed) =>
236 + SubscriptionRef.update(metadata, (state) => ({
237 + ...state,
238 + draft: {
239 + ...state.draft,
240 + usageLimits: resolveUsageLimitsAfterProbe({
241 + published: state.draft.usageLimits,
242 + probed,
243 + }),
244 + },
245 + })),
246 + ),
247 + // Enrichment cannot change published limits; a health check publishes them.
248 + Effect.andThen(
249 + Deferred.await(republish).pipe(
250 + Effect.flatten,
251 + Effect.provideService(PublishingUsage, true),
252 + Effect.ignoreCause({ log: true }),
253 + Effect.forkIn(scope),
254 + ),
255 + ),
256 + ),
257 + // Store the fiber before it runs, so a sign-out during the read can interrupt it.
258 + { onlyIfMissing: true, startImmediately: false },
259 + );
260 + });
261 + const resetUsage = Effect.gen(function* () {
262 + yield* FiberHandle.clear(usageRead);
263 + if (options.clearUsage) yield* options.clearUsage;
264 + });
265 +
266 const checkProvider = Effect.fn("checkAntigravityProvider")(function* () {
267 if (!settings.enabled) return yield* getSnapshot;
268 const before = yield* SubscriptionRef.get(metadata);
@@ -239,8 +287,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
287 : `Antigravity did not respond to its local health check within ${HEALTH_CHECK_TIMEOUT}.`;
288 const supportsTextGeneration =
289 initialized !== undefined ? yield* options.supportsTextGeneration : false;
242 - const usageLimits =
243 - initialized !== undefined && options.probeUsage ? yield* options.probeUsage : undefined;
290 const updatedAt = DateTime.formatIso(yield* DateTime.now);
291 const next = yield* SubscriptionRef.updateAndGet(metadata, (state) => {
292 if (state.authRevision !== before.authRevision) return state;
@@ -262,12 +308,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
308 version: version === "unknown" ? draft.version : version || draft.version,
309 status: errorMessage ? "error" : authenticated ? "ready" : "warning",
310 checkedAt: updatedAt,
265 - usageLimits: missingInstallation
266 - ? undefined
267 - : resolveUsageLimitsAfterProbe({
268 - published: draft.usageLimits,
269 - probed: usageLimits ?? draft.usageLimits,
270 - }),
311 + usageLimits: missingInstallation ? undefined : draft.usageLimits,
312 ...(missingInstallation
313 ? {
314 models: [],
@@ -287,6 +328,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
328 },
329 } satisfies AntigravityProviderState;
330 });
331 + if (initialized !== undefined) yield* refreshUsage();
332 return yield* options.stampIdentity(next.draft);
333 });
334
@@ -310,6 +352,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
352 ),
353 ),
354 });
355 + yield* Deferred.succeed(republish, managed.refresh);
356
357 const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
358 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
@@ -319,10 +362,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
362 observeThinkingLevels(started.sessionSetupResult.configOptions);
363 const before = yield* SubscriptionRef.get(metadata);
364 const supportsTextGeneration = yield* options.supportsTextGeneration;
322 - const usageLimits =
323 - options.probeUsage && (!before.draft.usageLimits || before.draft.usageLimits.unavailable)
324 - ? yield* options.probeUsage
325 - : before.draft.usageLimits;
365 const updatedAt = DateTime.formatIso(yield* DateTime.now);
366 yield* SubscriptionRef.update(metadata, (state) => {
367 if (
@@ -347,10 +386,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
386 label: options.auth?.label ?? "Google account",
387 },
388 checkedAt: updatedAt,
350 - usageLimits: resolveUsageLimitsAfterProbe({
351 - published: draft.usageLimits,
352 - probed: usageLimits ?? draft.usageLimits,
353 - }),
389 models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels),
390 supportsTextGeneration,
391 ...(cwd
@@ -369,6 +404,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
404 },
405 } satisfies AntigravityProviderState;
406 });
407 + if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage();
408 });
409
410 const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
@@ -418,7 +454,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
454 });
455
456 const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
421 - if (options.clearUsage) yield* options.clearUsage;
457 + yield* resetUsage;
458 if (!settings.enabled) return;
459 const updatedAt = DateTime.formatIso(yield* DateTime.now);
460 yield* SubscriptionRef.update(
@@ -481,6 +517,23 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
517 onSessionStarted,
518 onConfigOptionsUpdated,
519 onAvailableCommands,
520 + // The new sign-in may be another account. Clear and republish its limits so a failed read
521 + // cannot fall back to them; the session start then reads the new account's limits.
522 + onSignedIn: resetUsage.pipe(
523 + Effect.andThen(
524 + SubscriptionRef.update(metadata, (state) => {
525 + const { usageLimits: _previousAccount, ...draft } = state.draft;
526 + return { ...state, draft };
527 + }),
528 + ),
529 + Effect.andThen(
530 + Deferred.await(republish).pipe(
531 + Effect.flatten,
532 + Effect.provideService(PublishingUsage, true),
533 + ),
534 + ),
535 + Effect.asVoid,
536 + ),
537 onSignedOut: clearAccountMetadata(),
538 onAuthRequired: clearAccountMetadata(),
539 snapshotForCwd,
apps/server/src/provider/Drivers/AntigravityDriver.ts
+7 -1
@@ -244,6 +244,7 @@ export const AntigravityDriver: ProviderDriver<
244 );
245 const runtime = yield* makeAntigravityAcpRuntime({
246 ...input,
247 + runtimeVersion: executable.version,
248 authMethod: auth.authMethod,
249 childProcessSpawner: spawner,
250 spawn: buildAntigravityAcpSpawnInput({
@@ -347,7 +348,11 @@ export const AntigravityDriver: ProviderDriver<
348 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
349 instanceId,
350 makeRuntime: makeDisposableRuntime,
350 - onAuthenticated: publishCatalog,
351 + // A new sign-in may be another account; drop any in-flight quota read first.
352 + onAuthenticated: (started, runtime) =>
353 + Effect.suspend(() => provider.onSignedIn).pipe(
354 + Effect.andThen(publishCatalog(started, runtime)),
355 + ),
356 onSignedOut: Effect.suspend(() => provider.onSignedOut),
357 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
358 });
@@ -429,6 +434,7 @@ export const AntigravityDriver: ProviderDriver<
434 makeRuntime,
435 withProcess: authFlow.withProcess,
436 defaultModel,
437 + profileDirectory,
438 onSessionStarted: provider.onSessionStarted,
439 onSessionEvent: (event) => {
440 if (event._tag === "ConfigOptionsUpdated") {
apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+14
@@ -966,6 +966,16 @@ describe("AcpSessionRuntime", () => {
966 "logout",
967 ]),
968 );
969 + // Omitted roots clear an agent's stored ones, so every activation resends them.
970 + for (const method of ["session/new", "session/fork", "session/resume"]) {
971 + expect(
972 + requestEvents.find((event) => event.method === method && event.status === "started")
973 + ?.payload,
974 + ).toMatchObject({
975 + additionalDirectories: ["/tmp/t3-attachments"],
976 + _meta: { negotiated: "0.0.0" },
977 + });
978 + }
979 }).pipe(
980 Effect.provide(
981 AcpSessionRuntime.layer({
@@ -977,6 +987,10 @@ describe("AcpSessionRuntime", () => {
987 T3_ACP_SESSION_LIFECYCLE: "1",
988 },
989 },
990 + additionalDirectories: ["/tmp/t3-attachments"],
991 + sessionMeta: (initializeResult) => ({
992 + negotiated: initializeResult.agentInfo?.version ?? "none",
993 + }),
994 cwd: process.cwd(),
995 clientInfo: { name: "t3-test", version: "0.0.0" },
996 requestLogger: (event) =>
apps/server/src/provider/acp/AntigravityAcpSupport.test.ts
+146 -16
@@ -5,6 +5,7 @@ import {
5 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
6 type ChatAttachment,
7 } from "@t3tools/contracts";
8 +import * as HostProcess from "@t3tools/shared/HostProcess";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Path from "effect/Path";
@@ -15,7 +16,9 @@ import type * as EffectAcpSchema from "effect-acp/compat";
16 import { resolveAttachmentPath } from "../../attachmentStore.ts";
17 import {
18 applyAntigravityAcpModelSelection,
19 + antigravitySessionMeta,
20 buildAntigravityPrompt,
21 + isQualifiedAntigravityRelease,
22 } from "./AntigravityAcpSupport.ts";
23
24 const modelConfig = {
@@ -54,6 +57,39 @@ function makeModelRuntime(
57 };
58 }
59
60 +describe("Antigravity release gates", () => {
61 + it.each([
62 + { version: "1.4.1", filter: false, native: false },
63 + { version: "1.4.2", filter: true, native: false },
64 + { version: "1.4.4", filter: true, native: false },
65 + { version: "1.4.5", filter: true, native: true },
66 + { version: "1.4.6", filter: false, native: false },
67 + { version: "1.3.0", filter: false, native: false },
68 + { version: undefined, filter: false, native: false },
69 + { version: "unknown", filter: false, native: false },
70 + ])(
71 + "$version: workflow filter $filter, native reads and system prompt $native",
72 + ({ version, filter, native }) => {
73 + const initialize = {
74 + protocolVersion: 1,
75 + ...(version === undefined ? {} : { agentInfo: { name: "antigravity-acp", version } }),
76 + };
77 + // Helpers send no append, so only the workflow filter can apply.
78 + expect(antigravitySessionMeta(initialize)).toEqual(
79 + filter ? { antigravity: { disabledTools: ["run_workflow"] } } : undefined,
80 + );
81 + const antigravity = {
82 + ...(filter ? { disabledTools: ["run_workflow"] } : {}),
83 + ...(native ? { systemPrompt: { append: "<pull_request_linking/>" } } : {}),
84 + };
85 + expect(antigravitySessionMeta(initialize, "<pull_request_linking/>")).toEqual(
86 + filter || native ? { antigravity } : undefined,
87 + );
88 + expect(isQualifiedAntigravityRelease(version)).toBe(native);
89 + },
90 + );
91 +});
92 +
93 describe("applyAntigravityAcpModelSelection", () => {
94 it.effect("restores the saved model instead of the cold-resume default", () =>
95 Effect.gen(function* () {
@@ -214,7 +250,9 @@ const makeAttachmentFixture = Effect.fn("AntigravityAcpSupportTest.makeAttachmen
250 else yield* fs.writeFile(filePath, content);
251 return { filePath, uri: (yield* path.toFileUrl(filePath)).href };
252 });
217 - return { fs, attachmentsDir, write };
253 + const resolve = (attachment: ChatAttachment) =>
254 + resolveAttachmentPath({ attachmentsDir, attachment });
255 + return { fs, attachmentsDir, resolve, write };
256 },
257 );
258
@@ -230,7 +268,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
268 const prompt = yield* buildAntigravityPrompt({
269 input: " Explain this image. ",
270 attachments: [imageAttachment],
233 - attachmentsDir: fixture.attachmentsDir,
271 + resolveAttachmentPath: fixture.resolve,
272 promptCapabilities: { image: true, audio: true, embeddedContext: true },
273 });
274
@@ -251,7 +289,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
289 const prompt = yield* buildAntigravityPrompt({
290 input: undefined,
291 attachments: [textAttachment],
254 - attachmentsDir: selectedEnvironment.attachmentsDir,
292 + resolveAttachmentPath: selectedEnvironment.resolve,
293 promptCapabilities: { image: true, audio: true, embeddedContext: true },
294 });
295
@@ -282,7 +320,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
320 const prompt = yield* buildAntigravityPrompt({
321 input: "Inspect the pasted text only as needed.",
322 attachments: [pastedText],
285 - attachmentsDir: fixture.attachmentsDir,
323 + resolveAttachmentPath: fixture.resolve,
324 promptCapabilities: { image: true, audio: true, embeddedContext: true },
325 });
326
@@ -309,7 +347,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
347 const prompt = yield* buildAntigravityPrompt({
348 input,
349 attachments: [attachment, pdfAttachment],
312 - attachmentsDir: fixture.attachmentsDir,
350 + resolveAttachmentPath: fixture.resolve,
351 promptCapabilities: { image: true, audio: true, embeddedContext: true },
352 }).pipe(
353 Effect.provideService(FileSystem.FileSystem, {
@@ -321,11 +359,100 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
359 );
360 expect(prompt).toEqual([
361 { type: "text", text: input },
324 - { type: "resource_link", uri: pdf.uri, name: "report.pdf", mimeType: "application/pdf" },
362 + {
363 + type: "resource_link",
364 + uri: pdf.uri,
365 + name: "report.pdf",
366 + mimeType: "application/pdf",
367 + size: 50 * 1024 * 1024,
368 + },
369 ]);
370 }),
371 );
372
373 + it.effect.each([
374 + {
375 + case: "a Gemini model id",
376 + model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },
377 + linked: true,
378 + },
379 + {
380 + case: "an opaque id named Gemini",
381 + model: { id: "agy-model", name: "Gemini 4 Carbon" },
382 + linked: true,
383 + },
384 + { case: "an unknown model", model: { id: "agy-custom", name: "Custom" }, linked: false },
385 + { case: "an unlisted opaque id", model: { id: "agy-custom", name: undefined }, linked: false },
386 + { case: "an unresolved model", model: undefined, linked: false },
387 + {
388 + case: "a Claude model",
389 + model: { id: "claude-opus-5-5", name: "Claude Opus 5.5" },
390 + linked: false,
391 + },
392 + {
393 + case: "an unqualified runtime",
394 + agentVersion: "1.4.1",
395 + model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },
396 + linked: false,
397 + },
398 + {
399 + case: "a Windows host",
400 + platform: "win32" as const,
401 + model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },
402 + linked: false,
403 + },
404 + {
405 + case: "a clip over 20 MiB",
406 + model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },
407 + linked: false,
408 + sizeBytes: 20 * 1024 * 1024 + 1,
409 + },
410 + ])(
411 + "links an MP4 for $case only when supported",
412 + ({ agentVersion = "1.4.5", platform = "linux", model, linked, ...size }) =>
413 + Effect.gen(function* () {
414 + const fixture = yield* makeAttachmentFixture();
415 + const clip = {
416 + ...textAttachment,
417 + id: "clip",
418 + name: "clip.mp4",
419 + mimeType: "video/mp4",
420 + sizeBytes: 6 * 1024 * 1024,
421 + ...size,
422 + };
423 + const upload = yield* fixture.write(clip, "");
424 + yield* fixture.fs.truncate(upload.filePath, clip.sizeBytes);
425 + const prompt = yield* buildAntigravityPrompt({
426 + input: "What colors appear?",
427 + attachments: [clip],
428 + resolveAttachmentPath: fixture.resolve,
429 + promptCapabilities: { image: true, audio: true, embeddedContext: true },
430 + agentVersion,
431 + currentModel: model,
432 + }).pipe(
433 + Effect.provideService(HostProcess.Platform, platform),
434 + Effect.provideService(FileSystem.FileSystem, {
435 + ...fixture.fs,
436 + stream: () => Effect.die("Linked video is read by the agent").pipe(Stream.fromEffect),
437 + }),
438 + );
439 + expect(prompt).toEqual([
440 + { type: "text", text: "What colors appear?" },
441 + ...(linked
442 + ? [
443 + {
444 + type: "resource_link",
445 + uri: upload.uri,
446 + name: "clip.mp4",
447 + mimeType: "video/mp4",
448 + size: clip.sizeBytes,
449 + },
450 + ]
451 + : []),
452 + ]);
453 + }),
454 + );
455 +
456 it.effect.each([undefined, {}, { image: false, audio: false, embeddedContext: false }])(
457 "keeps attachments path-only when native prompt capabilities are absent: %s",
458 (promptCapabilities) =>
@@ -352,7 +479,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
479 const prompt = yield* buildAntigravityPrompt({
480 input,
481 attachments: [imageAttachment, gifAttachment, pdfAttachment, textAttachment, audio],
355 - attachmentsDir: fixture.attachmentsDir,
482 + resolveAttachmentPath: fixture.resolve,
483 promptCapabilities,
484 }).pipe(
485 Effect.provideService(FileSystem.FileSystem, {
@@ -366,7 +493,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
493 yield* buildAntigravityPrompt({
494 input: "Continue",
495 attachments: [],
369 - attachmentsDir: fixture.attachmentsDir,
496 + resolveAttachmentPath: fixture.resolve,
497 promptCapabilities,
498 }),
499 ).toEqual([{ type: "text", text: "Continue" }]);
@@ -387,7 +514,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
514 const prompt = yield* buildAntigravityPrompt({
515 input: "Transcribe this.",
516 attachments: [audioAttachment],
390 - attachmentsDir: fixture.attachmentsDir,
517 + resolveAttachmentPath: fixture.resolve,
518 promptCapabilities: { image: true, audio: true, embeddedContext: true },
519 });
520
@@ -409,7 +536,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
536 const prompt = yield* buildAntigravityPrompt({
537 input,
538 attachments: [attachment],
412 - attachmentsDir: fixture.attachmentsDir,
539 + resolveAttachmentPath: fixture.resolve,
540 promptCapabilities,
541 }).pipe(
542 Effect.provideService(FileSystem.FileSystem, {
@@ -430,7 +557,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
557 const error = yield* buildAntigravityPrompt({
558 input: "Read this attachment.",
559 attachments: [imageAttachment],
433 - attachmentsDir: fixture.attachmentsDir,
560 + resolveAttachmentPath: fixture.resolve,
561 promptCapabilities: { image: true, audio: true, embeddedContext: true },
562 }).pipe(Effect.flip);
563 expect(error).toMatchObject({
@@ -456,7 +583,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
583 const input = {
584 input: `Read ${first.filePath} and ${second.filePath}`,
585 attachments: [pdfAttachment, secondAttachment],
459 - attachmentsDir: fixture.attachmentsDir,
586 + resolveAttachmentPath: fixture.resolve,
587 promptCapabilities: { image: true, audio: true, embeddedContext: true },
588 };
589 const prompt = yield* buildAntigravityPrompt(input);
@@ -467,12 +594,14 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
594 uri: first.uri,
595 name: "report.pdf",
596 mimeType: "application/pdf",
597 + size: (50 * 1024 * 1024) / 2,
598 },
599 {
600 type: "resource_link",
601 uri: second.uri,
602 name: "second.pdf",
603 mimeType: "application/pdf",
604 + size: (50 * 1024 * 1024) / 2,
605 },
606 ]);
607
@@ -484,6 +613,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
613 uri: first.uri,
614 name: "report.pdf",
615 mimeType: "application/pdf",
616 + size: (50 * 1024 * 1024) / 2,
617 },
618 ]);
619 }),
@@ -498,7 +628,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
628 const error = yield* buildAntigravityPrompt({
629 input: "Inspect both attachments.",
630 attachments: [pdfAttachment, imageAttachment],
501 - attachmentsDir: fixture.attachmentsDir,
631 + resolveAttachmentPath: fixture.resolve,
632 promptCapabilities: { image: true, audio: true, embeddedContext: true },
633 }).pipe(Effect.flip);
634 expect(error).toMatchObject({
@@ -517,7 +647,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
647 const error = yield* buildAntigravityPrompt({
648 input: undefined,
649 attachments: [pdfAttachment, textAttachment],
520 - attachmentsDir: fixture.attachmentsDir,
650 + resolveAttachmentPath: fixture.resolve,
651 promptCapabilities: { image: true, audio: true, embeddedContext: true },
652 }).pipe(
653 Effect.provideService(FileSystem.FileSystem, {
@@ -551,7 +681,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
681 const error = yield* buildAntigravityPrompt({
682 input: undefined,
683 attachments: [textAttachment],
554 - attachmentsDir: fixture.attachmentsDir,
684 + resolveAttachmentPath: fixture.resolve,
685 promptCapabilities: { image: true, audio: true, embeddedContext: true },
686 }).pipe(Effect.flip);
687
@@ -569,7 +699,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
699 const error = yield* buildAntigravityPrompt({
700 input: "Read this image.",
701 attachments: [imageAttachment],
572 - attachmentsDir: fixture.attachmentsDir,
702 + resolveAttachmentPath: fixture.resolve,
703 promptCapabilities: { image: true, audio: true, embeddedContext: true },
704 }).pipe(Effect.flip);
705
apps/server/src/provider/acp/AntigravityAcpSupport.ts
+106 -11
@@ -6,6 +6,7 @@ import {
6 type ProviderSendTurnInput,
7 type RuntimeMode,
8 } from "@t3tools/contracts";
9 +import * as HostProcess from "@t3tools/shared/HostProcess";
10 import * as Crypto from "effect/Crypto";
11 import * as Effect from "effect/Effect";
12 import * as FileSystem from "effect/FileSystem";
@@ -17,7 +18,6 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18 import * as EffectAcpErrors from "effect-acp/errors";
19 import type * as EffectAcpSchema from "effect-acp/compat";
20
20 -import { resolveAttachmentPath } from "../../attachmentStore.ts";
21 import {
22 makeAntigravityStderrHandler,
23 makeAntigravityStdoutTransform,
@@ -34,15 +34,78 @@ export interface AntigravityAcpRuntimeInput extends Omit<
34 | "clientInfo"
35 | "onStderr"
36 | "resumeMethod"
37 + | "sessionMeta"
38 | "transformSessionUpdate"
39 | "transformStdout"
40 > {
41 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
42 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
43 + /** Serve `fs/read_text_file` for runtimes whose native reader is not qualified. */
44 readonly clientFileReads?: boolean;
45 + /** The installed version, known before `initialize`; it picks the file reader. */
46 + readonly runtimeVersion?: string | null;
47 + /** Conversational sessions only; helpers and probes leave the system prompt untouched. */
48 + readonly sessionSystemPromptAppend?: string;
49 readonly authMethod?: AntigravityAuthMethod;
50 }
51
52 +function parseAntigravityVersion(version: string | null | undefined) {
53 + const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version?.trim() ?? "");
54 + return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
55 +}
56 +
57 +function compareVersions(left: ReadonlyArray<number>, right: ReadonlyArray<number>) {
58 + for (let index = 0; index < 3; index++) {
59 + const difference = (left[index] ?? 0) - (right[index] ?? 0);
60 + if (difference !== 0) return difference;
61 + }
62 + return 0;
63 +}
64 +
65 +/**
66 + * 1.4.2 through 1.4.5 create or overwrite skills/system/run-workflow/SKILL.md in the workspace
67 + * unless `run_workflow` is disabled. Older builds offer the tool and leave the file alone.
68 + */
69 +function antigravityWritesRunWorkflowSkill(version: string | null | undefined): boolean {
70 + const parsed = parseAntigravityVersion(version);
71 + return (
72 + parsed !== undefined &&
73 + compareVersions(parsed, [1, 4, 2]) >= 0 &&
74 + compareVersions(parsed, [1, 4, 5]) <= 0
75 + );
76 +}
77 +
78 +/**
79 + * Releases T3 qualified for native range reads and linked video. On 1.4.5 the client-read path
80 + * sends a whole file to serve one line, and the native reader keeps diff edits.
81 + */
82 +export function isQualifiedAntigravityRelease(version: string | null | undefined): boolean {
83 + return version?.trim() === "1.4.5";
84 +}
85 +
86 +/**
87 + * 1.4.5 appends `systemPrompt.append` to its system instructions on new, load and resume, and
88 + * keeps none of it between processes, so every activation sends it again.
89 + */
90 +export const antigravityAppendsSystemPrompt = (
91 + initializeResult: EffectAcpSchema.InitializeResponse,
92 +) => isQualifiedAntigravityRelease(initializeResult.agentInfo?.version);
93 +
94 +export function antigravitySessionMeta(
95 + initializeResult: EffectAcpSchema.InitializeResponse,
96 + systemPromptAppend?: string,
97 +): EffectAcpSchema.NewSessionRequest["_meta"] | undefined {
98 + const antigravity = {
99 + ...(antigravityWritesRunWorkflowSkill(initializeResult.agentInfo?.version)
100 + ? { disabledTools: ["run_workflow"] }
101 + : {}),
102 + ...(systemPromptAppend !== undefined && antigravityAppendsSystemPrompt(initializeResult)
103 + ? { systemPrompt: { append: systemPromptAppend } }
104 + : {}),
105 + };
106 + return Object.keys(antigravity).length === 0 ? undefined : { antigravity };
107 +}
108 +
109 export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(function* (
110 input: AntigravityAcpRuntimeInput,
111 ): Effect.fn.Return<
@@ -59,9 +122,15 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(
122 cancelBehavior: "wait-for-prompt",
123 // The agent offers non-Gemini models only to allowlisted clients such as Zed.
124 clientInfo: { name: "zed", version: "0.0.0" },
125 + sessionMeta: (initializeResult) =>
126 + antigravitySessionMeta(initializeResult, input.sessionSystemPromptAppend),
127 clientCapabilities: {
128 // Advertising writes swaps the agent's diff edits for whole-file client_edit_file.
64 - fs: { readTextFile: input.clientFileReads === true, writeTextFile: false },
129 + fs: {
130 + readTextFile:
131 + input.clientFileReads === true && !isQualifiedAntigravityRelease(input.runtimeVersion),
132 + writeTextFile: false,
133 + },
134 terminal: false,
135 },
136 transformStdout: makeAntigravityStdoutTransform(
@@ -212,6 +281,18 @@ const AUDIO_MIME_TYPES = new Set([
281 "audio/webm",
282 ]);
283 const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024;
284 +// The agent inlines linked video bytes into one model request, so keep it under the inline limit.
285 +const ANTIGRAVITY_MAX_VIDEO_ATTACHMENT_BYTES = 20 * 1024 * 1024;
286 +
287 +/**
288 + * Only Gemini takes video. The evidence is the session's resolved model, so an account default
289 + * counts once the agent reports it; opaque ids such as `agy-model` need a Gemini display name.
290 + */
291 +function antigravityModelAcceptsVideo(
292 + model: { readonly id: string; readonly name: string | undefined } | undefined,
293 +): boolean {
294 + return model !== undefined && (/^gemini-/i.test(model.id) || /^gemini\b/i.test(model.name ?? ""));
295 +}
296 const TEXT_MIME_TYPES = new Set([
297 "application/json",
298 "application/ld+json",
@@ -277,8 +358,13 @@ const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;
358 export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {
359 readonly input: ProviderSendTurnInput["input"];
360 readonly attachments: ProviderSendTurnInput["attachments"];
280 - readonly attachmentsDir: string;
361 + readonly resolveAttachmentPath: (
362 + attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number],
363 + ) => string | null;
364 readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
365 + /** Linked video needs a runtime whose `resource_link` handling is qualified and a Gemini model. */
366 + readonly agentVersion?: string | undefined;
367 + readonly currentModel?: { readonly id: string; readonly name: string | undefined } | undefined;
368 }): Effect.fn.Return<
369 ReadonlyArray<EffectAcpSchema.ContentBlock>,
370 EffectAcpErrors.AcpError,
@@ -286,6 +372,8 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
372 > {
373 const fileSystem = yield* FileSystem.FileSystem;
374 const path = yield* Path.Path;
375 + // The agent runs on this host.
376 + const platform = yield* HostProcess.Platform;
377 const blocks: Array<EffectAcpSchema.ContentBlock> = [];
378 const text = input.input?.trim();
379 if (text) blocks.push({ type: "text", text });
@@ -301,6 +389,14 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
389 const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);
390 const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);
391 const pdf = attachment.type === "file" && mimeType === "application/pdf";
392 + const video =
393 + attachment.type === "file" &&
394 + mimeType === "video/mp4" &&
395 + isQualifiedAntigravityRelease(input.agentVersion) &&
396 + // The agent turns a file URI into a path with unquote(urlparse(uri).path), which drops
397 + // Windows drives and UNC hosts. Keep the saved path there until Google fixes it.
398 + platform !== "win32" &&
399 + antigravityModelAcceptsVideo(input.currentModel);
400 const textFile =
401 attachment.type === "file" &&
402 (mimeType.startsWith("text/") ||
@@ -314,11 +410,8 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
410 ? input.promptCapabilities?.audio !== true
411 : pdf || textFile
412 ? input.promptCapabilities?.embeddedContext !== true
317 - : true)));
318 - const attachmentPath = resolveAttachmentPath({
319 - attachmentsDir: input.attachmentsDir,
320 - attachment,
321 - });
413 + : !video)));
414 + const attachmentPath = input.resolveAttachmentPath(attachment);
415 if (!attachmentPath) {
416 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
417 `Invalid attachment '${attachment.name}'.`,
@@ -346,7 +439,9 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
439 ? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES
440 : pdf
441 ? MAX_TOTAL_ATTACHMENT_BYTES
349 - : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;
442 + : video
443 + ? ANTIGRAVITY_MAX_VIDEO_ATTACHMENT_BYTES
444 + : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;
445 if (
446 attachment.type === "file" &&
447 (size > limit || totalBytes + size > MAX_TOTAL_ATTACHMENT_BYTES)
@@ -365,8 +460,8 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
460 EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`),
461 ),
462 );
368 - if (pdf) {
369 - blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType });
463 + if (pdf || video) {
464 + blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType, size });
465 continue;
466 }
467 const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe(
apps/server/src/provider/acp/AntigravityChildWork.test.ts new
+344
@@ -0,0 +1,344 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- fixtures name transcript files by URL.
2 +import * as NodeURL from "node:url";
3 +
4 +import * as NodeServices from "@effect/platform-node/NodeServices";
5 +import { expect, it } from "@effect/vitest";
6 +import * as Effect from "effect/Effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Path from "effect/Path";
9 +
10 +import {
11 + ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
12 + antigravitySubagentLaunches,
13 + describeAntigravitySubagentLaunches,
14 + readAntigravityChildWork,
15 +} from "./AntigravityChildWork.ts";
16 +import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts";
17 +import {
18 + autoApproved,
19 + CHILD,
20 + invokeStep,
21 + LAUNCH,
22 + makeProfile,
23 + plannerStep,
24 + ROOT,
25 + transcriptLines,
26 +} from "./AntigravityChildWork.testkit.ts";
27 +
28 +const read = (
29 + profileDirectory: string,
30 + nativeTaskId: string,
31 + launch: { readonly title: string | null; readonly prompt: string } = {
32 + title: null,
33 + prompt: "Readme check",
34 + },
35 + siblings: ReadonlyArray<{
36 + readonly nativeTaskId: string;
37 + readonly title: string | null;
38 + readonly prompt: string;
39 + }> = [],
40 +) =>
41 + readAntigravityChildWork({
42 + profileDirectory,
43 + rootSessionId: ROOT,
44 + nativeTaskId,
45 + launch,
46 + siblings,
47 + });
48 +
49 +it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => {
50 + it.effect("follows an auto-approved call id through its planner step to the record", () =>
51 + Effect.gen(function* () {
52 + const { profile } = yield* makeProfile({ steps: autoApproved });
53 + const [child, ...rest] = yield* read(profile, `${ROOT}:1`);
54 + expect(rest).toEqual([]);
55 + expect(child).toMatchObject({
56 + conversationId: CHILD,
57 + role: LAUNCH.role,
58 + prompt: LAUNCH.prompt,
59 + truncated: false,
60 + });
61 + // The launch envelope repeats the prompt shown above, so the steps start with the child's work.
62 + expect(child?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([
63 + "view_file",
64 + "2: child read marker 4242",
65 + "marker 4242 found",
66 + ]);
67 + expect(child?.steps?.[0]?.toolCalls[0]?.input).toBe('{"AbsolutePath":"/project/README.md"}');
68 + }),
69 + );
70 +
71 + it.effect("needs proof that the call id belongs to the parent's record", () =>
72 + Effect.gen(function* () {
73 + const { profile } = yield* makeProfile({
74 + steps: (logUri) => [
75 + ...autoApproved(logUri),
76 + [5, 15, plannerStep(["call-b", "call-c"])],
77 + [
78 + 6,
79 + 127,
80 + invokeStep({ callId: "call-b", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
81 + ],
82 + [
83 + 7,
84 + 127,
85 + invokeStep({ callId: "call-c", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
86 + ],
87 + ],
88 + });
89 + // Another session's id, a step that is not the planner call, and parallel calls that share one id.
90 + expect(yield* read(profile, `00000000-0000-4000-8000-000000000000:1`)).toEqual([]);
91 + expect(yield* read(profile, `${ROOT}:2`)).toEqual([]);
92 + expect(yield* read(profile, `${ROOT}:5`)).toEqual([]);
93 + }),
94 + );
95 +
96 + it.effect("matches a permission-prompt call by its launch text, only when unique", () =>
97 + Effect.gen(function* () {
98 + const other = { role: "Test Runner", prompt: "Run the tests" };
99 + const long = { role: "Long Reader", prompt: `Read this:\n${"x".repeat(9_000)}` };
100 + // A role's leading byte order mark is part of its text.
101 + const marked = { role: "\uFEFFMarked", prompt: "Check the mark" };
102 + const { profile } = yield* makeProfile({
103 + steps: (logUri) => [
104 + [
105 + 2,
106 + 127,
107 + invokeStep({ callId: "x", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
108 + ],
109 + [
110 + 8,
111 + 127,
112 + invokeStep({ callId: "w", launches: [long], children: [{ id: CHILD, logUri }] }),
113 + ],
114 + [
115 + 10,
116 + 127,
117 + invokeStep({ callId: "v", launches: [marked], children: [{ id: CHILD, logUri }] }),
118 + ],
119 + [
120 + 4,
121 + 127,
122 + invokeStep({ callId: "y", launches: [other], children: [{ id: CHILD, logUri }] }),
123 + ],
124 + [
125 + 6,
126 + 127,
127 + invokeStep({ callId: "z", launches: [other], children: [{ id: CHILD, logUri }] }),
128 + ],
129 + ],
130 + });
131 + const opaque = "35bea692fa95447fbdae6333fec5515f";
132 + const matched = yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]));
133 + expect(matched.map((child) => child.role)).toEqual([LAUNCH.role]);
134 + // T3 knows a second batch with this text that the agent has not recorded yet.
135 + const twin = { nativeTaskId: "f00d", ...describeAntigravitySubagentLaunches([LAUNCH]) };
136 + expect(
137 + yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]), [twin]),
138 + ).toEqual([]);
139 + // T3 stores the launch from the bounded tool payload, which keeps only a long prompt's tail.
140 + const stored = antigravitySubagentLaunches(
141 + sanitizeAntigravityToolPayload({ Subagents: [{ Role: long.role, Prompt: long.prompt }] }),
142 + );
143 + const longMatch = yield* read(profile, opaque, describeAntigravitySubagentLaunches(stored!));
144 + expect(longMatch.map((child) => child.prompt)).toEqual([long.prompt]);
145 + expect(
146 + yield* read(profile, opaque, describeAntigravitySubagentLaunches([marked])),
147 + ).toHaveLength(1);
148 + expect(yield* read(profile, opaque, { title: "Marked", prompt: marked.prompt })).toEqual([]);
149 + expect(yield* read(profile, opaque, describeAntigravitySubagentLaunches([other]))).toEqual(
150 + [],
151 + );
152 + expect(yield* read(profile, opaque, { title: null, prompt: "Readme check" })).toEqual([]);
153 + }),
154 + );
155 +
156 + it.effect("leaves an auto-approved batch's record out of a launch-text match", () =>
157 + Effect.gen(function* () {
158 + const { profile } = yield* makeProfile({ steps: autoApproved });
159 + const launch = describeAntigravitySubagentLaunches([LAUNCH]);
160 + const opaque = "35bea692fa95447fbdae6333fec5515f";
161 + expect(yield* read(profile, opaque, launch)).toHaveLength(1);
162 + // An earlier auto-approved batch stored no launch text, but its planner step claims the record.
163 + const auto = {
164 + nativeTaskId: `${ROOT}:1`,
165 + title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
166 + prompt: "",
167 + };
168 + expect(yield* read(profile, opaque, launch, [auto])).toEqual([]);
169 + // A sibling that cannot be ruled out refuses the match: its planner step is unreadable,
170 + // or it is a permission batch whose launch text is missing or cut.
171 + for (const sibling of [
172 + { ...auto, nativeTaskId: `${ROOT}:99` },
173 + { nativeTaskId: "0ld", title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE, prompt: "Running" },
174 + // Its stored launch was cut, so it may be this same launch.
175 + { nativeTaskId: "cut", title: LAUNCH.role, prompt: "[Earlier output truncated]\n\nmarker" },
176 + { nativeTaskId: "cut", title: "[Earlier output truncated]\n\nReader", prompt: "x" },
177 + { nativeTaskId: "cut", title: null, prompt: "[Earlier output truncated]\n\nx" },
178 + ]) {
179 + expect(yield* read(profile, opaque, launch, [sibling])).toEqual([]);
180 + }
181 + // A cut prompt under different roles is another launch.
182 + const other = {
183 + nativeTaskId: "cut",
184 + title: "Test Runner",
185 + prompt: "[Earlier output truncated]\n\nx",
186 + };
187 + expect(yield* read(profile, opaque, launch, [other])).toHaveLength(1);
188 + }),
189 + );
190 +
191 + it.effect("reads no transcript outside the child's own profile path", () =>
192 + Effect.gen(function* () {
193 + const fs = yield* FileSystem.FileSystem;
194 + const path = yield* Path.Path;
195 + const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });
196 + const secret = path.join(outside, "transcript.jsonl");
197 + yield* fs.writeFileString(secret, JSON.stringify(transcriptLines[3]) + "\n");
198 + const named = yield* makeProfile({
199 + steps: () => autoApproved(NodeURL.pathToFileURL(secret).href),
200 + });
201 + const [namedChild] = yield* read(named.profile, `${ROOT}:1`);
202 + expect(namedChild?.role).toBe(LAUNCH.role);
203 + expect(namedChild?.steps).toBeNull();
204 +
205 + const linked = yield* makeProfile({ steps: autoApproved });
206 + yield* fs.remove(linked.transcriptPath);
207 + yield* fs.symlink(secret, linked.transcriptPath);
208 + const [linkedChild] = yield* read(linked.profile, `${ROOT}:1`);
209 + expect(linkedChild?.steps).toBeNull();
210 + }),
211 + );
212 +
213 + it.effect("reads only the tail of a large transcript", () =>
214 + Effect.gen(function* () {
215 + const filler = JSON.stringify({
216 + step_index: 0,
217 + type: "VIEW_FILE",
218 + status: "DONE",
219 + content: "x".repeat(10_000),
220 + });
221 + const { profile } = yield* makeProfile({
222 + steps: autoApproved,
223 + transcript: `${Array.from({ length: 40 }, () => filler).join("\n")}\n${JSON.stringify(transcriptLines[3])}\n`,
224 + });
225 + const [child] = yield* read(profile, `${ROOT}:1`);
226 + expect(child?.truncated).toBe(true);
227 + expect(child?.steps?.length).toBeLessThan(40);
228 + expect(child?.steps?.at(-1)?.text).toBe("marker 4242 found");
229 + expect(child?.steps?.[0]?.text?.length).toBeLessThanOrEqual(4_001);
230 + }),
231 + );
232 +
233 + it.effect("refuses links between children and sessions inside the same profile", () =>
234 + Effect.gen(function* () {
235 + const fs = yield* FileSystem.FileSystem;
236 + const path = yield* Path.Path;
237 + const sibling = "b468c0e1d2f34a5b6c7d8e9f0a1b2c3d";
238 + // The record names this child's literal path, but the child directory links to a sibling.
239 + const linked = yield* makeProfile({ steps: autoApproved });
240 + const brain = path.join(linked.profile, "antigravity-acp", "brain");
241 + yield* fs.rename(path.join(brain, CHILD), path.join(brain, sibling));
242 + yield* fs.symlink(path.join(brain, sibling), path.join(brain, CHILD));
243 + const [child] = yield* read(linked.profile, `${ROOT}:1`);
244 + expect(child?.role).toBe(LAUNCH.role);
245 + expect(child?.steps).toBeNull();
246 +
247 + // This session's database links to another session's records.
248 + const other = yield* makeProfile({ steps: autoApproved });
249 + const conversations = path.join(other.profile, "antigravity-acp", "conversations");
250 + const peer = path.join(conversations, "00000000-0000-4000-8000-000000000000.db");
251 + yield* fs.rename(path.join(conversations, `${ROOT}.db`), peer);
252 + yield* fs.symlink(peer, path.join(conversations, `${ROOT}.db`));
253 + expect(yield* read(other.profile, `${ROOT}:1`)).toEqual([]);
254 + }),
255 + );
256 +
257 + it.effect("declines a launch-text match it cannot prove unique within its scan bounds", () =>
258 + Effect.gen(function* () {
259 + const record = (callId: string, logUri: string) =>
260 + invokeStep({ callId, launches: [LAUNCH], children: [{ id: CHILD, logUri }] });
261 + const other = { role: "Test Runner", prompt: "Run the tests" };
262 + const filler = (idx: number, logUri: string) =>
263 + [
264 + idx,
265 + 127,
266 + invokeStep({ callId: `f${idx}`, launches: [other], children: [{ id: CHILD, logUri }] }),
267 + ] as const;
268 + const opaque = "35bea692fa95447fbdae6333fec5515f";
269 + const launch = describeAntigravitySubagentLaunches([LAUNCH]);
270 + const cases = [
271 + // More records than one open may scan.
272 + (logUri: string) => [
273 + [1, 127, record("x", logUri)] as const,
274 + ...Array.from({ length: 200 }, (_, index) => filler(index + 2, logUri)),
275 + ],
276 + // An oversized record could hold an identical launch.
277 + (logUri: string) => [
278 + [1, 127, record("x", logUri)] as const,
279 + [2, 127, new Uint8Array(1024 * 1024 + 1)] as const,
280 + ],
281 + // So could one this reader cannot decode.
282 + (logUri: string) => [
283 + [1, 127, record("x", logUri)] as const,
284 + [2, 127, Uint8Array.from([0xff, 0xff])] as const,
285 + ],
286 + ];
287 + for (const steps of cases) {
288 + const { profile } = yield* makeProfile({ steps });
289 + expect(yield* read(profile, opaque, launch)).toEqual([]);
290 + }
291 + }),
292 + );
293 +
294 + it.effect("keeps the batch view for a batch over the child limit", () =>
295 + Effect.gen(function* () {
296 + const { profile } = yield* makeProfile({
297 + steps: (logUri) => [
298 + [1, 15, plannerStep(["call-a"])],
299 + [
300 + 2,
301 + 127,
302 + invokeStep({
303 + callId: "call-a",
304 + launches: Array.from({ length: 17 }, () => LAUNCH),
305 + children: Array.from({ length: 17 }, () => ({ id: CHILD, logUri })),
306 + }),
307 + ],
308 + ],
309 + });
310 + expect(yield* read(profile, `${ROOT}:1`)).toEqual([]);
311 + }),
312 + );
313 +
314 + it.effect("shares one transcript budget across the batch", () =>
315 + Effect.gen(function* () {
316 + const filler = JSON.stringify({
317 + step_index: 0,
318 + type: "VIEW_FILE",
319 + status: "DONE",
320 + content: "x".repeat(1_000),
321 + });
322 + const transcript = `${Array.from({ length: 300 }, () => filler).join("\n")}\n`;
323 + const { profile } = yield* makeProfile({
324 + transcript,
325 + steps: (logUri) => [
326 + [1, 15, plannerStep(["call-a"])],
327 + [
328 + 2,
329 + 127,
330 + invokeStep({
331 + callId: "call-a",
332 + launches: Array.from({ length: 16 }, () => LAUNCH),
333 + children: Array.from({ length: 16 }, () => ({ id: CHILD, logUri })),
334 + }),
335 + ],
336 + ],
337 + });
338 + const children = yield* read(profile, `${ROOT}:1`);
339 + expect(children).toHaveLength(16);
340 + expect(children.every((child) => child.truncated)).toBe(true);
341 + expect(JSON.stringify(children).length).toBeLessThan(600 * 1024);
342 + }),
343 + );
344 +});
apps/server/src/provider/acp/AntigravityChildWork.testkit.ts new
+111
@@ -0,0 +1,111 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- fixtures write a native session database.
2 +import * as NodeSqlite from "node:sqlite";
3 +import * as NodeURL from "node:url";
4 +
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Path from "effect/Path";
8 +
9 +export const ROOT = "7d40e54d-5977-4239-940b-246cdd81a12b";
10 +export const CHILD = "a357bf2720914589dd1ec49f7a816115";
11 +export const LAUNCH = { role: "Readme Reader", prompt: "Read README.md and report the marker" };
12 +
13 +// Mirrors the 1.4.5 runtime: Step{5: metadata{4: tool call{1 id, 2 name}}, 20: planner{7: calls},
14 +// 143: invoke_subagent{9: specs{2 role, 3 prompt}, 10: results{1 conversation, 2 log uri}}}.
15 +const varint = (value: number): number[] => {
16 + const bytes: number[] = [];
17 + while (value >= 0x80) {
18 + bytes.push((value & 0x7f) | 0x80);
19 + value = Math.floor(value / 0x80);
20 + }
21 + return [...bytes, value];
22 +};
23 +const field = (number: number, value: string | Uint8Array) => {
24 + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
25 + return [...varint(number * 8 + 2), ...varint(bytes.length), ...bytes];
26 +};
27 +const proto = (...parts: number[][]) => Uint8Array.from(parts.flat());
28 +const toolCall = (id: string) => proto(field(1, id), field(2, "invoke_subagent"));
29 +
30 +export const invokeStep = (input: {
31 + readonly callId: string;
32 + readonly launches: ReadonlyArray<typeof LAUNCH>;
33 + readonly children: ReadonlyArray<{ readonly id: string; readonly logUri: string }>;
34 +}) =>
35 + proto(
36 + [...varint(1 * 8), ...varint(127)],
37 + field(5, proto(field(4, toolCall(input.callId)))),
38 + field(
39 + 143,
40 + proto(
41 + ...input.launches.map((launch) =>
42 + field(9, proto(field(1, "research"), field(2, launch.role), field(3, launch.prompt))),
43 + ),
44 + ...input.children.map((child) =>
45 + field(10, proto(field(1, child.id), field(2, child.logUri))),
46 + ),
47 + ),
48 + ),
49 + );
50 +export const plannerStep = (callIds: ReadonlyArray<string>) =>
51 + proto(field(20, proto(...callIds.map((id) => field(7, toolCall(id))))));
52 +
53 +export const transcriptLines = [
54 + // Trimmed from 1.4.5: the launch envelope around the prompt the parent record already holds.
55 + {
56 + step_index: 0,
57 + type: "SYSTEM_MESSAGE",
58 + status: "DONE",
59 + content: `<USER_REQUEST sender="7d40e54d-5977-4239-940b-246cdd81a12b" timestamp="2026-10-31T18:00:00Z">\n${LAUNCH.prompt}\n</USER_REQUEST>`,
60 + },
61 + {
62 + step_index: 1,
63 + type: "PLANNER_RESPONSE",
64 + status: "DONE",
65 + // The runtime stores each argument value as JSON text.
66 + tool_calls: [{ name: "view_file", args: { AbsolutePath: '"/project/README.md"' } }],
67 + },
68 + { step_index: 2, type: "VIEW_FILE", status: "DONE", content: "2: child read marker 4242" },
69 + { step_index: 3, type: "PLANNER_RESPONSE", status: "DONE", content: "marker 4242 found" },
70 +];
71 +
72 +export const makeProfile = Effect.fn("makeProfile")(function* (input: {
73 + /** Defaults to a scoped temp directory. */
74 + readonly profile?: string;
75 + readonly steps: (logUri: string) => ReadonlyArray<readonly [number, number, Uint8Array]>;
76 + readonly transcript?: string;
77 +}) {
78 + const fs = yield* FileSystem.FileSystem;
79 + const path = yield* Path.Path;
80 + const profile = input.profile ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-child-" }));
81 + const acp = path.join(profile, "antigravity-acp");
82 + const logs = path.join(acp, "brain", CHILD, ".system_generated", "logs");
83 + yield* fs.makeDirectory(path.join(acp, "conversations"), { recursive: true });
84 + yield* fs.makeDirectory(logs, { recursive: true });
85 + const transcriptPath = path.join(logs, "transcript.jsonl");
86 + yield* fs.writeFileString(
87 + transcriptPath,
88 + input.transcript ?? transcriptLines.map((line) => JSON.stringify(line)).join("\n") + "\n",
89 + );
90 + const logUri = NodeURL.pathToFileURL(transcriptPath).href;
91 + const database = new NodeSqlite.DatabaseSync(path.join(acp, "conversations", `${ROOT}.db`));
92 + database.exec(
93 + "CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer NOT NULL DEFAULT 0, step_format integer NOT NULL DEFAULT 0, step_payload blob)",
94 + );
95 + const insert = database.prepare(
96 + "INSERT INTO steps (idx, step_type, step_payload) VALUES (?, ?, ?)",
97 + );
98 + for (const [idx, type, payload] of input.steps(logUri)) insert.run(idx, type, payload);
99 + database.close();
100 + return { profile, transcriptPath, logUri };
101 +});
102 +
103 +export const autoApproved = (logUri: string) =>
104 + [
105 + [1, 15, plannerStep(["call-a"])],
106 + [
107 + 2,
108 + 127,
109 + invokeStep({ callId: "call-a", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
110 + ],
111 + ] as const;
apps/server/src/provider/acp/AntigravityChildWork.ts new
+478
@@ -0,0 +1,478 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only.
2 +import * as NodeFS from "node:fs";
3 +import * as NodeFSP from "node:fs/promises";
4 +import * as NodeSqlite from "node:sqlite";
5 +import * as NodeURL from "node:url";
6 +
7 +import type {
8 + OrchestrationV2NativeChildStep,
9 + OrchestrationV2NativeChildWork,
10 +} from "@t3tools/contracts";
11 +import * as Effect from "effect/Effect";
12 +import * as Option from "effect/Option";
13 +import * as Predicate from "effect/Predicate";
14 +import * as Schema from "effect/Schema";
15 +
16 +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
17 +import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts";
18 +
19 +// Field numbers from the runtime's trajectory protos (exa.cortex_pb).
20 +const STEP_METADATA = 5;
21 +const METADATA_TOOL_CALL = 4;
22 +const STEP_PLANNER_RESPONSE = 20;
23 +const PLANNER_TOOL_CALLS = 7;
24 +const STEP_INVOKE_SUBAGENT = 143;
25 +const INVOKE_SPECS = 9;
26 +const INVOKE_RESULTS = 10;
27 +const INVOKE_SUBAGENT_STEP_TYPE = 127;
28 +
29 +// One open reads at most this much; past any bound the batch view stays as it was.
30 +const MAX_STEP_BYTES = 1024 * 1024;
31 +const MAX_INVOKE_ROWS = 200;
32 +const MAX_SCAN_BYTES = 8 * 1024 * 1024;
33 +const MAX_CHILDREN = 16;
34 +const TRANSCRIPT_BYTE_CAP = 256 * 1024;
35 +const BATCH_TRANSCRIPT_BYTES = 512 * 1024;
36 +const STEP_TEXT_CAP = 4_000;
37 +const TOOL_INPUT_CAP = 1_000;
38 +
39 +/** T3's title for a batch whose launch text it never saw. */
40 +export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch";
41 +
42 +interface AntigravityChildLaunch {
43 + readonly role: string;
44 + readonly prompt: string;
45 +}
46 +
47 +const decodeLaunchInput = Schema.decodeUnknownOption(
48 + Schema.Struct({
49 + Subagents: Schema.NonEmptyArray(Schema.Struct({ Role: Schema.String, Prompt: Schema.String })),
50 + }),
51 +);
52 +
53 +/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */
54 +export function antigravitySubagentLaunches(
55 + input: unknown,
56 +): ReadonlyArray<AntigravityChildLaunch> | undefined {
57 + return Option.getOrUndefined(
58 + Option.map(decodeLaunchInput(input), (decoded) =>
59 + decoded.Subagents.map((entry) => ({ role: entry.Role, prompt: entry.Prompt })),
60 + ),
61 + );
62 +}
63 +
64 +/** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */
65 +export function describeAntigravitySubagentLaunches(
66 + launches: ReadonlyArray<AntigravityChildLaunch>,
67 +) {
68 + const [only] = launches;
69 + return launches.length === 1 && only !== undefined
70 + ? { title: only.role, prompt: only.prompt }
71 + : {
72 + title: launches.map((launch) => launch.role).join(", "),
73 + prompt: launches.map((launch) => `${launch.role}\n${launch.prompt}`).join("\n\n"),
74 + };
75 +}
76 +
77 +/** Length-delimited fields only; varints and fixed values are skipped. */
78 +function protoFields(bytes: Uint8Array): ReadonlyArray<readonly [number, Uint8Array]> {
79 + const fields: Array<readonly [number, Uint8Array]> = [];
80 + let offset = 0;
81 + const varint = () => {
82 + let value = 0;
83 + for (let shift = 0; shift < 64; shift += 7) {
84 + const byte = bytes[offset++];
85 + if (byte === undefined) throw new Error("Truncated varint");
86 + value += (byte & 0x7f) * 2 ** shift;
87 + if (byte < 0x80) return value;
88 + }
89 + throw new Error("Overlong varint");
90 + };
91 + while (offset < bytes.length) {
92 + const key = varint();
93 + const wire = key % 8;
94 + const field = Math.floor(key / 8);
95 + if (wire === 0) varint();
96 + else if (wire === 1) offset += 8;
97 + else if (wire === 5) offset += 4;
98 + else if (wire === 2) {
99 + const length = varint();
100 + if (offset + length > bytes.length) throw new Error("Truncated field");
101 + fields.push([field, bytes.subarray(offset, offset + length)]);
102 + offset += length;
103 + } else throw new Error("Unsupported wire type");
104 + }
105 + if (offset > bytes.length) throw new Error("Truncated field");
106 + return fields;
107 +}
108 +
109 +// Keep a leading byte order mark: T3 stores launch text with it.
110 +const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
111 +const messages = (bytes: Uint8Array, field: number) =>
112 + protoFields(bytes).flatMap(([number, value]) => (number === field ? [value] : []));
113 +const message = (bytes: Uint8Array | undefined, field: number) =>
114 + bytes === undefined ? undefined : messages(bytes, field)[0];
115 +const text = (bytes: Uint8Array | undefined, field: number) => {
116 + const value = message(bytes, field);
117 + return value === undefined ? undefined : textDecoder.decode(value);
118 +};
119 +
120 +interface InvokeRecord {
121 + readonly toolCallId: string | undefined;
122 + readonly launches: ReadonlyArray<AntigravityChildLaunch>;
123 + readonly children: ReadonlyArray<{ readonly conversationId: string; readonly logUri: string }>;
124 +}
125 +
126 +const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/;
127 +
128 +/** Undefined for steps this reader cannot decode, so they never count as proof. */
129 +const safely =
130 + <A>(decode: (payload: Uint8Array) => A) =>
131 + (payload: Uint8Array): A | undefined => {
132 + try {
133 + return decode(payload);
134 + } catch {
135 + return undefined;
136 + }
137 + };
138 +
139 +const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => {
140 + const invoke = message(payload, STEP_INVOKE_SUBAGENT);
141 + if (invoke === undefined) return undefined;
142 + const children = messages(invoke, INVOKE_RESULTS).map((result) => ({
143 + conversationId: text(result, 1) ?? "",
144 + logUri: text(result, 2) ?? "",
145 + }));
146 + if (!children.every((child) => NATIVE_ID.test(child.conversationId))) return undefined;
147 + return {
148 + toolCallId: text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1),
149 + launches: messages(invoke, INVOKE_SPECS).map((spec) => ({
150 + role: text(spec, 2) ?? "",
151 + prompt: text(spec, 3) ?? "",
152 + })),
153 + children,
154 + };
155 +});
156 +
157 +const plannerInvokeCallIds = safely((payload): ReadonlyArray<string> => {
158 + const planner = message(payload, STEP_PLANNER_RESPONSE);
159 + if (planner === undefined) return [];
160 + return messages(planner, PLANNER_TOOL_CALLS).flatMap((call) => {
161 + const id = text(call, 1);
162 + return text(call, 2) === "invoke_subagent" && id !== undefined ? [id] : [];
163 + });
164 +});
165 +
166 +const payloadOf = (row: unknown) =>
167 + row !== null &&
168 + typeof row === "object" &&
169 + "step_payload" in row &&
170 + row.step_payload instanceof Uint8Array
171 + ? row.step_payload
172 + : undefined;
173 +
174 +interface BatchLaunch {
175 + readonly title: string | null;
176 + readonly prompt: string;
177 +}
178 +
179 +const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => {
180 + const planner = payloadOf(
181 + database
182 + .prepare(
183 + "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?",
184 + )
185 + .get(plannerIdx, MAX_STEP_BYTES),
186 + );
187 + return planner === undefined ? undefined : plannerInvokeCallIds(planner);
188 +};
189 +
190 +/**
191 + * Auto-approved calls carry `<sessionId>:<plannerStep>`; the record with that planner call's id
192 + * is the proof. Permission prompts carry a random id, so the launch text must match one record
193 + * no auto-approved sibling claims, and no sibling may share the text.
194 + */
195 +function findInvokeRecord(
196 + database: NodeSqlite.DatabaseSync,
197 + input: {
198 + readonly rootSessionId: string;
199 + readonly nativeTaskId: string;
200 + readonly launch: BatchLaunch;
201 + readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
202 + },
203 +): InvokeRecord | undefined {
204 + const plannerIdxOf = (nativeTaskId: string) => {
205 + const stepId = /^(.+):(\d+)$/.exec(nativeTaskId);
206 + return stepId === null ? undefined : stepId[1] === input.rootSessionId ? Number(stepId[2]) : -1;
207 + };
208 + const plannerIdx = plannerIdxOf(input.nativeTaskId);
209 + if (plannerIdx !== undefined) {
210 + if (plannerIdx < 0) return undefined;
211 + const callIds = plannerCallIdsAt(database, plannerIdx) ?? [];
212 + const [callId] = callIds;
213 + if (callIds.length !== 1) return undefined;
214 + // The record follows the planner step that issued the call.
215 + let rows = 0;
216 + let bytes = 0;
217 + for (const row of database
218 + .prepare(
219 + // SQLite returns only in-bound payloads, so an oversized row never reaches this process.
220 + "SELECT length(step_payload) AS size, CASE WHEN length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type = ? AND step_format = 0 AND idx > ? ORDER BY idx",
221 + )
222 + .iterate(MAX_STEP_BYTES, INVOKE_SUBAGENT_STEP_TYPE, plannerIdx)) {
223 + const size = row !== null && typeof row === "object" && "size" in row ? Number(row.size) : 0;
224 + rows += 1;
225 + bytes += size;
226 + if (rows > MAX_INVOKE_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES)
227 + return undefined;
228 + const payload = payloadOf(row);
229 + const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
230 + if (record !== undefined && record.toolCallId === callId) return complete(record);
231 + }
232 + return undefined;
233 + }
234 + const totals = database
235 + .prepare(
236 + "SELECT count(*) AS rows, coalesce(sum(length(step_payload)), 0) AS bytes, coalesce(max(length(step_payload)), 0) AS largest, sum(step_format != 0) AS other FROM steps WHERE step_type = ?",
237 + )
238 + .get(INVOKE_SUBAGENT_STEP_TYPE);
239 + const total = (key: string) =>
240 + totals !== undefined && key in totals ? Number(totals[key as keyof typeof totals] ?? 0) : 0;
241 + const sameText = (launch: BatchLaunch) =>
242 + launch.title === input.launch.title && launch.prompt === input.launch.prompt;
243 + if (
244 + input.siblings.some(sameText) ||
245 + total("rows") > MAX_INVOKE_ROWS ||
246 + total("bytes") > MAX_SCAN_BYTES ||
247 + total("largest") > MAX_STEP_BYTES ||
248 + total("other") > 0
249 + ) {
250 + return undefined;
251 + }
252 + const claimed = new Set<string>();
253 + for (const sibling of input.siblings) {
254 + const idx = plannerIdxOf(sibling.nativeTaskId);
255 + // A sibling whose launch text is missing, or cut under the same roles, or whose planner step
256 + // is unreadable, cannot be ruled out.
257 + if (idx === undefined) {
258 + if (
259 + sibling.title === ANTIGRAVITY_SUBAGENT_BATCH_TITLE ||
260 + (sibling.title !== null && isCutAntigravityToolText(sibling.title)) ||
261 + (isCutAntigravityToolText(sibling.prompt) &&
262 + (sibling.title === null || sibling.title === input.launch.title))
263 + )
264 + return undefined;
265 + continue;
266 + }
267 + if (idx < 0) continue;
268 + const callIds = plannerCallIdsAt(database, idx);
269 + if (callIds === undefined || callIds.length === 0) return undefined;
270 + for (const callId of callIds) claimed.add(callId);
271 + }
272 + const matches: Array<InvokeRecord> = [];
273 + for (const row of database
274 + .prepare("SELECT step_payload FROM steps WHERE step_type = ? ORDER BY idx")
275 + .iterate(INVOKE_SUBAGENT_STEP_TYPE)) {
276 + const payload = payloadOf(row);
277 + const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
278 + // An unreadable record could be an identical launch, so uniqueness is unproven.
279 + if (record === undefined) return undefined;
280 + if (record.toolCallId !== undefined && claimed.has(record.toolCallId)) continue;
281 + // T3 stored the launch from the bounded tool payload, so bound the record the same way.
282 + const described = describeAntigravitySubagentLaunches(
283 + record.launches.map((launch) => ({
284 + role: boundAntigravityToolText(launch.role),
285 + prompt: boundAntigravityToolText(launch.prompt),
286 + })),
287 + );
288 + if (sameText(described)) {
289 + matches.push(record);
290 + }
291 + }
292 + const [match] = matches;
293 + return matches.length === 1 && match !== undefined ? complete(match) : undefined;
294 +}
295 +
296 +const complete = (record: InvokeRecord) =>
297 + record.launches.length === record.children.length && record.children.length <= MAX_CHILDREN
298 + ? record
299 + : undefined;
300 +
301 +const TranscriptLine = Schema.Struct({
302 + step_index: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
303 + type: Schema.String,
304 + status: Schema.optional(Schema.String),
305 + content: Schema.optional(Schema.String),
306 + error: Schema.optional(Schema.String),
307 + tool_calls: Schema.optional(
308 + Schema.Array(Schema.Struct({ name: Schema.String, args: Schema.optional(Schema.Unknown) })),
309 + ),
310 +});
311 +const decodeTranscriptLine = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptLine));
312 +
313 +// The runtime records each tool argument value as JSON text.
314 +const decodeArgument = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
315 +const toolArguments = (args: unknown) =>
316 + Predicate.isObject(args)
317 + ? Object.fromEntries(
318 + Object.entries(args).map(([key, value]) => [
319 + key,
320 + typeof value === "string" ? Option.getOrElse(decodeArgument(value), () => value) : value,
321 + ]),
322 + )
323 + : (args ?? {});
324 +
325 +const capText = (value: string, limit: number) =>
326 + value.length <= limit ? value : `${value.slice(0, limit)}…`;
327 +
328 +/** Skips the runtime's opening envelope around the launch prompt the view already shows. */
329 +function transcriptSteps(
330 + contents: string,
331 + prompt: string,
332 +): ReadonlyArray<OrchestrationV2NativeChildStep> {
333 + const launchPrompt = prompt.trim();
334 + return contents.split("\n").flatMap((line) =>
335 + Option.match(decodeTranscriptLine(line), {
336 + onNone: () => [],
337 + onSome: (step) =>
338 + step.step_index === 0 &&
339 + step.type === "SYSTEM_MESSAGE" &&
340 + launchPrompt !== "" &&
341 + step.content?.includes(launchPrompt) === true
342 + ? []
343 + : [
344 + {
345 + index: step.step_index,
346 + type: step.type,
347 + status: step.status ?? null,
348 + text:
349 + step.content !== undefined || step.error !== undefined
350 + ? capText(step.content ?? step.error ?? "", STEP_TEXT_CAP)
351 + : null,
352 + toolCalls: (step.tool_calls ?? []).map((call) => ({
353 + name: call.name,
354 + input: capText(JSON.stringify(toolArguments(call.args)), TOOL_INPUT_CAP),
355 + })),
356 + },
357 + ],
358 + }),
359 + );
360 +}
361 +
362 +/** Reads the tail of the transcript at the named child's own unlinked profile path. */
363 +async function readChildTranscript(
364 + profileRoot: string,
365 + child: InvokeRecord["children"][number],
366 + prompt: string,
367 + byteCap: number,
368 +) {
369 + const expected = (
370 + await antigravityManagedPath(
371 + profileRoot,
372 + [
373 + "antigravity-acp",
374 + "brain",
375 + child.conversationId,
376 + ".system_generated",
377 + "logs",
378 + "transcript.jsonl",
379 + ],
380 + "file",
381 + )
382 + )?.path;
383 + if (expected === undefined) return undefined;
384 + let named: string;
385 + try {
386 + named = NodeURL.fileURLToPath(child.logUri);
387 + } catch {
388 + return undefined;
389 + }
390 + if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined;
391 + const handle = await NodeFSP.open(
392 + expected,
393 + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0),
394 + );
395 + try {
396 + const stat = await handle.stat();
397 + if (!stat.isFile()) return undefined;
398 + const length = Math.min(stat.size, byteCap);
399 + const buffer = Buffer.alloc(length);
400 + const { bytesRead } = await handle.read(buffer, 0, length, stat.size - length);
401 + const truncated = stat.size > length;
402 + let contents = buffer.subarray(0, bytesRead).toString("utf8");
403 + // A tail read starts mid-line.
404 + if (truncated) contents = contents.slice(contents.indexOf("\n") + 1);
405 + return { steps: transcriptSteps(contents, prompt), truncated };
406 + } finally {
407 + await handle.close();
408 + }
409 +}
410 +
411 +class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()(
412 + "AntigravityChildWorkReadError",
413 + { cause: Schema.Defect() },
414 +) {
415 + override get message(): string {
416 + return "Could not read Antigravity subagent records.";
417 + }
418 +}
419 +
420 +/** Children a subagent tool call launched, proven by the parent's own session record. */
421 +export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: {
422 + readonly profileDirectory: string;
423 + readonly rootSessionId: string;
424 + readonly nativeTaskId: string;
425 + readonly launch: BatchLaunch;
426 + /** The thread's other Antigravity batches from this instance. */
427 + readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
428 +}) {
429 + if (!NATIVE_ID.test(input.rootSessionId)) return [];
430 + return yield* Effect.tryPromise({
431 + try: async (): Promise<ReadonlyArray<OrchestrationV2NativeChildWork>> => {
432 + const profileRoot = await antigravityProfileRoot(input.profileDirectory);
433 + const databasePath =
434 + profileRoot === undefined
435 + ? undefined
436 + : (
437 + await antigravityManagedPath(
438 + profileRoot,
439 + ["antigravity-acp", "conversations", `${input.rootSessionId}.db`],
440 + "file",
441 + )
442 + )?.path;
443 + if (profileRoot === undefined || databasePath === undefined) return [];
444 + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
445 + let record: InvokeRecord | undefined;
446 + try {
447 + record = findInvokeRecord(database, input);
448 + } finally {
449 + database.close();
450 + }
451 + if (record === undefined) return [];
452 + const { launches, children } = record;
453 + // One budget for the whole batch, so the response stays small however many children ran.
454 + const byteCap = Math.min(
455 + TRANSCRIPT_BYTE_CAP,
456 + Math.floor(BATCH_TRANSCRIPT_BYTES / Math.max(1, children.length)),
457 + );
458 + return Promise.all(
459 + children.map(async (child, index) => {
460 + const transcript = await readChildTranscript(
461 + profileRoot,
462 + child,
463 + launches[index]?.prompt ?? "",
464 + byteCap,
465 + ).catch(() => undefined);
466 + return {
467 + conversationId: child.conversationId,
468 + role: launches[index]?.role ?? "",
469 + prompt: launches[index]?.prompt ?? "",
470 + steps: transcript?.steps ?? null,
471 + truncated: transcript?.truncated ?? false,
472 + };
473 + }),
474 + );
475 + },
476 + catch: (cause) => new AntigravityChildWorkReadError({ cause }),
477 + });
478 +});
apps/server/src/provider/acp/AntigravityEditLocation.test.ts new
+245
@@ -0,0 +1,245 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { ANTIGRAVITY_EDIT_DIFF_OMITTED, antigravityEditPatch } from "./AntigravityEditLocation.ts";
4 +
5 +const path = "/workspace/app.ts";
6 +const file = Array.from({ length: 20 }, (_, i) =>
7 + i === 9
8 + ? "const target = 10;"
9 + : i === 14
10 + ? "const other = 15;"
11 + : `const line${i + 1} = ${i + 1};`,
12 +).join("\n");
13 +const replace = { TargetContent: "const target = 10;", ReplacementContent: "const target = 100;" };
14 +const header = `--- ${path}\n+++ ${path}\n`;
15 +
16 +describe("antigravityEditPatch", () => {
17 + it("finds the target inside the announced search range, in either argument casing", () => {
18 + const expected = `${header}@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`;
19 + const readPreEditFile = () => file;
20 + for (const rawInput of [
21 + { ...replace, StartLine: 5, EndLine: 20 },
22 + {
23 + target_content: replace.TargetContent,
24 + replacement_content: replace.ReplacementContent,
25 + start_line: 5,
26 + end_line: 20,
27 + },
28 + {
29 + replacement_chunks: [
30 + {
31 + target_content: replace.TargetContent,
32 + replacement_content: replace.ReplacementContent,
33 + start_line: 5,
34 + end_line: 20,
35 + },
36 + ],
37 + },
38 + // Like the runtime, a present PascalCase value wins, and a 0 line means unspecified.
39 + { ...replace, target_content: "const other = 15;", StartLine: 5, EndLine: 0 },
40 + ]) {
41 + expect(antigravityEditPatch({ path, rawInput, readPreEditFile })).toBe(expected);
42 + }
43 + for (const rawInput of [replace, { ReplacementChunks: [replace] }]) {
44 + expect(
45 + antigravityEditPatch({ path, rawInput, locations: [{ path, line: 5 }], readPreEditFile }),
46 + ).toBe(expected);
47 + }
48 + // A hunk replaces whole lines, so a match inside a line is not a placement.
49 + expect(
50 + antigravityEditPatch({
51 + path,
52 + rawInput: { TargetContent: "10", ReplacementContent: "100" },
53 + readPreEditFile,
54 + }),
55 + ).toMatch(/ snippet, line unknown$/m);
56 + // The range start is not the target's line: without the file, or outside the range, it stays unplaced.
57 + const snippet = `${header}@@ -1,1 +1,1 @@ snippet, line unknown\n-const target = 10;\n+const target = 100;\n`;
58 + expect(
59 + antigravityEditPatch({ path, rawInput: { ...replace, StartLine: 5, EndLine: 20 } }),
60 + ).toBe(snippet);
61 + expect(
62 + antigravityEditPatch({
63 + path,
64 + rawInput: { ...replace, StartLine: 11, EndLine: 20 },
65 + readPreEditFile,
66 + }),
67 + ).toBe(snippet);
68 + });
69 +
70 + it("finds an unannounced snippet in the pre-edit file", () => {
71 + const expected = `${header}@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`;
72 + expect(antigravityEditPatch({ path, rawInput: replace, readPreEditFile: () => file })).toBe(
73 + expected,
74 + );
75 + const crlf = file.replaceAll("\n", "\r\n");
76 + expect(antigravityEditPatch({ path, rawInput: replace, readPreEditFile: () => crlf })).toBe(
77 + expected,
78 + );
79 + // A target written with CRLF previews the same lines, without carriage returns.
80 + expect(
81 + antigravityEditPatch({
82 + path,
83 + rawInput: {
84 + TargetContent: "const target = 10;\r\n",
85 + ReplacementContent: "const target = 100;\r\n",
86 + },
87 + readPreEditFile: () => crlf,
88 + }),
89 + ).toBe(expected);
90 + // A change to the line ending alone has no LF hunk to place.
91 + const endingOnly = {
92 + TargetContent: "const target = 10;\r\n",
93 + ReplacementContent: "const target = 10;\n",
94 + };
95 + for (const readPreEditFile of [() => crlf, undefined]) {
96 + expect(antigravityEditPatch({ path, rawInput: endingOnly, readPreEditFile })).toBe(
97 + ANTIGRAVITY_EDIT_DIFF_OMITTED,
98 + );
99 + }
100 + // A multi-line target written with LF still finds its lines in a CRLF file.
101 + expect(
102 + antigravityEditPatch({
103 + path,
104 + rawInput: {
105 + TargetContent: "const line9 = 9;\nconst target = 10;",
106 + ReplacementContent: "const line9 = 9;\nconst target = 100;",
107 + },
108 + readPreEditFile: () => crlf,
109 + }),
110 + ).toMatch(/^@@ -9,2 \+9,2 @@$/m);
111 + });
112 +
113 + it("omits the preview when a chunk adds or removes a line break at its end", () => {
114 + // Whether that splits or joins lines depends on what follows the match.
115 + for (const [TargetContent, ReplacementContent] of [
116 + ["const line3 = 3;", "x\n"],
117 + ["const line3 = 3;\n", "x"],
118 + ["const line20 = 20;", "x\n"],
119 + // Clearing the last line of a file with no final newline removes the line.
120 + ["const line20 = 20;", ""],
121 + ]) {
122 + expect(
123 + antigravityEditPatch({
124 + path,
125 + rawInput: { TargetContent, ReplacementContent },
126 + readPreEditFile: () => file,
127 + }),
128 + ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);
129 + }
130 + });
131 +
132 + it("labels repeated or unmatched snippets instead of placing them at line 1", () => {
133 + const snippet = `${header}@@ -1,1 +1,1 @@ snippet, line unknown\n-const target = 10;\n+const target = 100;\n`;
134 + for (const readPreEditFile of [
135 + () => `${file}\n${file}`,
136 + () => "unrelated\n",
137 + () => undefined,
138 + undefined,
139 + ]) {
140 + expect(antigravityEditPatch({ path, rawInput: replace, readPreEditFile })).toBe(snippet);
141 + }
142 + });
143 +
144 + it("places each replacement chunk and shifts later chunks by earlier line changes", () => {
145 + const patch = antigravityEditPatch({
146 + path,
147 + rawInput: {
148 + ReplacementChunks: [
149 + {
150 + TargetContent: "const other = 15;\n",
151 + ReplacementContent: "const other = 150;\n",
152 + StartLine: 15,
153 + EndLine: 15,
154 + },
155 + {
156 + TargetContent: "const target = 10;\n",
157 + ReplacementContent: "const target = 100;\nconst added = 1;\n",
158 + StartLine: 10,
159 + EndLine: 10,
160 + },
161 + ],
162 + },
163 + readPreEditFile: () => file,
164 + });
165 + expect(patch).toBe(
166 + [
167 + header.trimEnd(),
168 + "@@ -10,1 +10,2 @@",
169 + "-const target = 10;",
170 + "+const target = 100;",
171 + "+const added = 1;",
172 + "@@ -15,1 +16,1 @@",
173 + "-const other = 15;",
174 + "+const other = 150;",
175 + "",
176 + ].join("\n"),
177 + );
178 + });
179 +
180 + it("omits the preview when only some chunks can be placed", () => {
181 + const patch = antigravityEditPatch({
182 + path,
183 + rawInput: {
184 + ReplacementChunks: [
185 + {
186 + TargetContent: "const target = 10;\n",
187 + ReplacementContent: "const target = 100;\n",
188 + StartLine: 10,
189 + EndLine: 10,
190 + },
191 + { TargetContent: "missing", ReplacementContent: "still missing" },
192 + ],
193 + },
194 + readPreEditFile: () => file,
195 + });
196 + expect(patch).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);
197 + });
198 +
199 + it("leaves whole-file writes and unknown inputs to the generic diff", () => {
200 + expect(antigravityEditPatch({ path, rawInput: { CodeContent: "x" } })).toBeUndefined();
201 + expect(antigravityEditPatch({ path, rawInput: undefined })).toBeUndefined();
202 + });
203 +
204 + it("omits the preview once an edit exceeds the shared diff budget", () => {
205 + const lines = (prefix: string, count: number) =>
206 + Array.from({ length: count }, (_, index) => `${prefix} ${index} ${"x".repeat(8)}`).join("\n");
207 + // A 7,000-line wholesale replacement, as one chunk.
208 + expect(
209 + antigravityEditPatch({
210 + path,
211 + rawInput: {
212 + TargetContent: lines("old", 7_000),
213 + ReplacementContent: lines("new", 7_000),
214 + StartLine: 1,
215 + },
216 + }),
217 + ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);
218 + // Chunks that each fit, but not together.
219 + const chunk = (start: number) => ({
220 + TargetContent: lines(`old-${start}`, 300),
221 + ReplacementContent: lines(`new-${start}`, 300),
222 + StartLine: start,
223 + });
224 + expect(
225 + antigravityEditPatch({
226 + path,
227 + rawInput: { ReplacementChunks: [chunk(1), chunk(1_000)] },
228 + }),
229 + ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);
230 + // Text over the size limit is not diffed at all.
231 + expect(
232 + antigravityEditPatch({
233 + path,
234 + rawInput: {
235 + TargetContent: "a".repeat(200_000),
236 + ReplacementContent: "b".repeat(100_000),
237 + StartLine: 1,
238 + },
239 + }),
240 + ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);
241 + expect(antigravityEditPatch({ path, rawInput: { ReplacementChunks: [chunk(1)] } })).toMatch(
242 + /^@@ -1,300 \+1,300 @@/m,
243 + );
244 + });
245 +});
apps/server/src/provider/acp/AntigravityEditLocation.ts new
+226
@@ -0,0 +1,226 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - the tool-call normalizer is synchronous
2 +import * as NodeFS from "node:fs";
3 +
4 +import { PositiveInt } from "@t3tools/contracts";
5 +import { FILE_HEADERS_ONLY, formatPatch, structuredPatch, type StructuredPatchHunk } from "diff";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 +
9 +const PRE_EDIT_FILE_LIMIT = 1024 * 1024;
10 +// The live preview runs synchronously. One budget covers every chunk in a call: the generic
11 +// ACP formatter's edit-distance limit, plus a size limit that skips diffing entirely.
12 +const EDIT_DIFF_BUDGET = 1_000;
13 +const EDIT_TEXT_BUDGET = 256 * 1024;
14 +
15 +/** The edit is too large to preview cheaply; the turn's checkpoint diff still shows it. */
16 +export const ANTIGRAVITY_EDIT_DIFF_OMITTED = Symbol("AntigravityEditDiffOmitted");
17 +const SNIPPET_LABEL = " snippet, line unknown";
18 +
19 +/** True when no chunk could be placed; a patch never mixes placed and unplaced chunks. */
20 +export function isAntigravitySnippetPatch(patch: string): boolean {
21 + return /^@@ .* @@.*$/m.exec(patch)?.[0].endsWith(SNIPPET_LABEL) === true;
22 +}
23 +
24 +// The runtime reads a missing, 0 or invalid line as unspecified.
25 +const Line = Schema.optional(Schema.Unknown);
26 +const decodeLine = Schema.decodeUnknownOption(PositiveInt);
27 +const lineOf = (value: unknown) => Option.getOrUndefined(decodeLine(value));
28 +const ReplacementChunk = Schema.Struct({
29 + TargetContent: Schema.String,
30 + ReplacementContent: Schema.String,
31 + StartLine: Line,
32 + EndLine: Line,
33 +});
34 +// replace_file_content sends one chunk at the top level; multi_replace_file_content sends a list.
35 +const decodeEditInput = Schema.decodeUnknownOption(
36 + Schema.Union([
37 + Schema.Struct({ ReplacementChunks: Schema.NonEmptyArray(ReplacementChunk) }),
38 + ReplacementChunk,
39 + ]),
40 +);
41 +const decodeLocations = Schema.decodeUnknownOption(Schema.Array(Schema.Struct({ line: Line })));
42 +// The runtime accepts edit arguments in either casing.
43 +const PASCAL_KEYS: Readonly<Record<string, string>> = {
44 + replacement_chunks: "ReplacementChunks",
45 + target_content: "TargetContent",
46 + replacement_content: "ReplacementContent",
47 + start_line: "StartLine",
48 + end_line: "EndLine",
49 +};
50 +const pascalKeys = (value: unknown): unknown => {
51 + if (Array.isArray(value)) return value.map(pascalKeys);
52 + if (typeof value !== "object" || value === null) return value;
53 + const fields: Record<string, unknown> = value as Record<string, unknown>;
54 + const result: Record<string, unknown> = {};
55 + for (const [key, entry] of Object.entries(fields)) {
56 + const pascal = PASCAL_KEYS[key];
57 + // Like the runtime, a present PascalCase value wins over its snake_case alias.
58 + if (pascal === undefined) result[key] ??= pascalKeys(entry);
59 + else if (fields[pascal] == null) result[pascal] = pascalKeys(entry);
60 + }
61 + return result;
62 +};
63 +
64 +/** Reads a small file for snippet matching; edits to large or unreadable files stay unlocated. */
65 +export function readAntigravityPreEditFile(path: string): string | undefined {
66 + try {
67 + const stat = NodeFS.statSync(path);
68 + return stat.isFile() && stat.size <= PRE_EDIT_FILE_LIMIT
69 + ? NodeFS.readFileSync(path, "utf8")
70 + : undefined;
71 + } catch {
72 + return undefined;
73 + }
74 +}
75 +
76 +/** The line of the snippet's only match starting within `from`..`to`, if it spans whole lines. */
77 +function uniqueStartLine(
78 + text: string | undefined,
79 + snippet: string,
80 + from = 1,
81 + to = Number.POSITIVE_INFINITY,
82 +): number | undefined {
83 + if (text === undefined || snippet === "") return undefined;
84 + let found: { readonly line: number; readonly whole: boolean } | undefined;
85 + let line = 1;
86 + let lineStart = 0;
87 + let nextBreak = text.indexOf("\n");
88 + for (let index = text.indexOf(snippet); index !== -1; index = text.indexOf(snippet, index + 1)) {
89 + while (nextBreak !== -1 && nextBreak < index) {
90 + line++;
91 + lineStart = nextBreak + 1;
92 + nextBreak = text.indexOf("\n", lineStart);
93 + }
94 + if (line > to) break;
95 + if (line < from) continue;
96 + if (found !== undefined) return undefined;
97 + const end = index + snippet.length;
98 + // A hunk replaces whole lines.
99 + const whole =
100 + index === lineStart && (end === text.length || snippet.endsWith("\n") || text[end] === "\n");
101 + found = { line, whole };
102 + }
103 + return found?.whole === true ? found.line : undefined;
104 +}
105 +
106 +function snippetHunks(
107 + oldText: string,
108 + newText: string,
109 + maxEditLength: number,
110 +): StructuredPatchHunk[] | undefined {
111 + const before = oldText.replaceAll("\r\n", "\n");
112 + const after = newText.replaceAll("\r\n", "\n");
113 + // A target without its newline keeps the line's own newline, on both sides.
114 + const eol = before.endsWith("\n") ? "" : "\n";
115 + return structuredPatch("", "", before + eol, after + eol, undefined, undefined, {
116 + maxEditLength,
117 + })?.hunks;
118 +}
119 +
120 +const changedLines = (hunks: ReadonlyArray<StructuredPatchHunk>) =>
121 + hunks.reduce(
122 + (total, hunk) =>
123 + total + hunk.lines.filter((line) => line.startsWith("+") || line.startsWith("-")).length,
124 + 0,
125 + );
126 +
127 +/**
128 + * Antigravity reports replacements as bare old/new snippets. `StartLine` only starts the
129 + * runtime's search range, so a chunk is placed at its unique match in the pre-edit file within
130 + * that range. All-unplaced chunks get hunks labeled as snippets; a mix is omitted.
131 + */
132 +export function antigravityEditPatch(input: {
133 + readonly path: string;
134 + readonly rawInput: unknown;
135 + readonly locations?: unknown;
136 + /** Pass only while the edit is pending, when the file still holds the old text. */
137 + readonly readPreEditFile?: ((path: string) => string | undefined) | undefined;
138 +}): string | typeof ANTIGRAVITY_EDIT_DIFF_OMITTED | undefined {
139 + const edit = Option.getOrUndefined(decodeEditInput(pascalKeys(input.rawInput)));
140 + if (edit === undefined) return undefined;
141 + const announced = lineOf(Option.getOrUndefined(decodeLocations(input.locations))?.[0]?.line);
142 + const listed = "ReplacementChunks" in edit ? edit.ReplacementChunks : [edit];
143 + const chunks = listed.map((chunk) => ({
144 + ...chunk,
145 + StartLine: lineOf(chunk.StartLine) ?? (listed.length === 1 ? announced : undefined),
146 + EndLine: lineOf(chunk.EndLine),
147 + }));
148 + let file: string | undefined;
149 + let fileRead = false;
150 + const textSize = chunks.reduce(
151 + (total, chunk) => total + chunk.TargetContent.length + chunk.ReplacementContent.length,
152 + 0,
153 + );
154 + if (textSize > EDIT_TEXT_BUDGET) return ANTIGRAVITY_EDIT_DIFF_OMITTED;
155 + let budget = EDIT_DIFF_BUDGET;
156 + const placed: Array<{ readonly start: number; readonly hunks: StructuredPatchHunk[] }> = [];
157 + const snippets: StructuredPatchHunk[] = [];
158 + for (const chunk of chunks) {
159 + // Whether a changed final line break, or a cleared line, splits, joins or removes lines
160 + // depends on what follows the match. Only a whole-line delete is certain.
161 + const targetEndsLine = chunk.TargetContent.endsWith("\n");
162 + if (
163 + chunk.ReplacementContent === ""
164 + ? !targetEndsLine
165 + : targetEndsLine !== chunk.ReplacementContent.endsWith("\n")
166 + )
167 + return ANTIGRAVITY_EDIT_DIFF_OMITTED;
168 + const hunks = snippetHunks(chunk.TargetContent, chunk.ReplacementContent, budget);
169 + // A change to the line ending alone leaves no LF hunk to show.
170 + if (
171 + hunks === undefined ||
172 + (hunks.length === 0 && chunk.TargetContent !== chunk.ReplacementContent)
173 + )
174 + return ANTIGRAVITY_EDIT_DIFF_OMITTED;
175 + budget -= changedLines(hunks);
176 + if (budget < 0) return ANTIGRAVITY_EDIT_DIFF_OMITTED;
177 + let start: number | undefined;
178 + if (input.readPreEditFile !== undefined) {
179 + // Line numbers do not depend on CRLF, so search with LF on both sides.
180 + if (!fileRead) file = input.readPreEditFile(input.path)?.replaceAll("\r\n", "\n");
181 + fileRead = true;
182 + start = uniqueStartLine(
183 + file,
184 + chunk.TargetContent.replaceAll("\r\n", "\n"),
185 + chunk.StartLine,
186 + chunk.EndLine,
187 + );
188 + }
189 + if (start === undefined) snippets.push(...hunks);
190 + else placed.push({ start, hunks });
191 + }
192 + // A placed hunk beside an unplaced one would still number the unplaced one from line 1.
193 + if (placed.length > 0 && snippets.length > 0) return ANTIGRAVITY_EDIT_DIFF_OMITTED;
194 + let shift = 0;
195 + const placedHunks = placed
196 + .toSorted((left, right) => left.start - right.start)
197 + .flatMap(({ start, hunks }) => {
198 + const shifted = hunks.map((hunk) => ({
199 + ...hunk,
200 + oldStart: hunk.oldStart + start - 1,
201 + newStart: hunk.newStart + start - 1 + shift,
202 + }));
203 + for (const hunk of hunks) shift += hunk.newLines - hunk.oldLines;
204 + return shifted;
205 + });
206 + const section = (hunks: StructuredPatchHunk[]) =>
207 + hunks.length === 0
208 + ? ""
209 + : formatPatch(
210 + {
211 + oldFileName: input.path,
212 + newFileName: input.path,
213 + oldHeader: undefined,
214 + newHeader: undefined,
215 + hunks,
216 + },
217 + FILE_HEADERS_ONLY,
218 + );
219 + const patch = [
220 + section(placedHunks),
221 + section(snippets).replace(/^@@ .* @@$/gm, `$&${SNIPPET_LABEL}`),
222 + ]
223 + .filter(Boolean)
224 + .join("\n");
225 + return patch || undefined;
226 +}
apps/server/src/provider/acp/AntigravityProfilePaths.ts new
+37
@@ -0,0 +1,37 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- lstat proves no managed component is a link.
2 +import type * as NodeFS from "node:fs";
3 +import * as NodeFSP from "node:fs/promises";
4 +import * as NodePath from "node:path";
5 +
6 +/**
7 + * Proves a native runtime entry is at its literal path below the canonical profile: every
8 + * component exists with the expected type and none is a link. A link could point at another
9 + * child's transcript or another session's database under the same profile.
10 + */
11 +export async function antigravityManagedPath(
12 + profileRoot: string,
13 + segments: ReadonlyArray<string>,
14 + kind: "file" | "directory",
15 +): Promise<{ readonly path: string; readonly info: NodeFS.Stats } | undefined> {
16 + let current = profileRoot;
17 + let info: NodeFS.Stats | undefined;
18 + for (const [index, segment] of segments.entries()) {
19 + current = NodePath.join(current, segment);
20 + info = await NodeFSP.lstat(current).catch(() => undefined);
21 + const expectFile = kind === "file" && index === segments.length - 1;
22 + if (
23 + info === undefined ||
24 + info.isSymbolicLink() ||
25 + (expectFile ? !info.isFile() : !info.isDirectory())
26 + ) {
27 + return undefined;
28 + }
29 + }
30 + if (info === undefined) return undefined;
31 + return (await NodeFSP.realpath(current).catch(() => undefined)) === current
32 + ? { path: current, info }
33 + : undefined;
34 +}
35 +
36 +export const antigravityProfileRoot = (profileDirectory: string) =>
37 + NodeFSP.realpath(profileDirectory).catch(() => undefined);
apps/server/src/provider/acp/AntigravityProtocol.test.ts
+130
@@ -19,6 +19,7 @@ import {
19 mergeToolCallState,
20 parseSessionUpdateEvent,
21 } from "@t3tools/provider-acp/server/runtimeModel";
22 +import { acpToolCallDiffPatch } from "@t3tools/provider-acp/server/adapter";
23
24 const isSessionNotification = Schema.is(AcpWireSchema.SessionNotification);
25
@@ -291,6 +292,135 @@ describe("Antigravity tool results", () => {
292 expect(commandCompleted.update.rawOutput.formatted_output).toBe("after\n");
293 });
294
295 + it("keeps the captured edit location through approval and completion", () => {
296 + const path = "/workspace/app.ts";
297 + const replace = {
298 + TargetContent: "const target = 10;",
299 + ReplacementContent: "const target = 100;",
300 + TargetFile: path,
301 + };
302 + const frame = (rawInput: Record<string, unknown>, line?: number) =>
303 + ({
304 + sessionId: "session-1",
305 + update: {
306 + sessionUpdate: "tool_call",
307 + toolCallId: "edit-1",
308 + title: "Run edit_file?",
309 + kind: "edit",
310 + status: "pending",
311 + content: [
312 + {
313 + type: "diff",
314 + path,
315 + oldText: replace.TargetContent,
316 + newText: replace.ReplacementContent,
317 + },
318 + ],
319 + locations: [line === undefined ? { path } : { path, line }],
320 + rawInput,
321 + },
322 + }) satisfies EffectAcpSchema.SessionNotification;
323 + const running = parseToolUpdate({
324 + sessionId: "session-1",
325 + update: {
326 + sessionUpdate: "tool_call_update",
327 + toolCallId: "edit-1",
328 + kind: "edit",
329 + status: "in_progress",
330 + title: "Running edit_file",
331 + locations: [{ path }],
332 + rawInput: { file_path: path },
333 + },
334 + }).toolCall;
335 + const completed = parseToolUpdate({
336 + sessionId: "session-1",
337 + update: {
338 + sessionUpdate: "tool_call_update",
339 + toolCallId: "edit-1",
340 + status: "completed",
341 + rawOutput: "Tool execution",
342 + },
343 + }).toolCall;
344 + const preEdit = Array.from({ length: 12 }, (_, i) =>
345 + i === 9 ? replace.TargetContent : `line ${i + 1}`,
346 + ).join("\n");
347 + const postEdit = preEdit.replace(replace.TargetContent, replace.ReplacementContent);
348 + for (const [pending, readFile] of [
349 + [frame({ ...replace, StartLine: 5, EndLine: 12 }, 5), () => preEdit],
350 + [frame(replace), () => preEdit],
351 + ] as const) {
352 + let toolCall = normalizeAntigravityToolCall(parseToolUpdate(pending).toolCall, readFile);
353 + for (const next of [running, completed]) {
354 + toolCall = normalizeAntigravityToolCall(mergeToolCallState(toolCall, next), () => postEdit);
355 + }
356 + expect(toolCall.status).toBe("completed");
357 + expect(acpToolCallDiffPatch(toolCall.data.content)).toBe(
358 + `--- ${path}\n+++ ${path}\n@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`,
359 + );
360 + }
361 + // Full-access edits arrive path-only; no hunk is offered instead of the tool's status text.
362 + let pathOnly = normalizeAntigravityToolCall(
363 + parseToolUpdate({
364 + sessionId: "session-1",
365 + update: {
366 + sessionUpdate: "tool_call",
367 + toolCallId: "edit-2",
368 + kind: "edit",
369 + status: "in_progress",
370 + title: "Running edit_file",
371 + locations: [{ path }],
372 + rawInput: { file_path: path },
373 + },
374 + }).toolCall,
375 + );
376 + pathOnly = normalizeAntigravityToolCall(mergeToolCallState(pathOnly, completed));
377 + expect(pathOnly.data.content).toEqual([{ type: "diff", patch: { format: "omitted" } }]);
378 + expect(acpToolCallDiffPatch(pathOnly.data.content)).toBeUndefined();
379 + // A captured patch that a later update's shared text budget cut or dropped is omitted.
380 + for (const patch of [{ text: "[Earlier output truncated]\n\n@@ -80,1 +80,1 @@" }, {}]) {
381 + const kept = normalizeAntigravityToolCall({
382 + toolCallId: "edit-cut",
383 + kind: "edit",
384 + status: "completed",
385 + data: { content: [{ type: "diff", path, patch }] },
386 + });
387 + expect(kept.data.content).toEqual([{ type: "diff", path, patch: { format: "omitted" } }]);
388 + }
389 + // A whole-file write whose old text was cut to its tail must not show the cut as deletions.
390 + const overwrite = normalizeAntigravityToolCall({
391 + toolCallId: "edit-overwrite",
392 + kind: "edit",
393 + status: "completed",
394 + data: {
395 + rawInput: { TargetFile: path, CodeContent: "one line\n" },
396 + content: [
397 + {
398 + type: "diff",
399 + path,
400 + oldText: "[Earlier output truncated]\n\nrow 999\n",
401 + newText: "one line\n",
402 + },
403 + ],
404 + },
405 + });
406 + expect(acpToolCallDiffPatch(overwrite.data.content)).toBeUndefined();
407 + // A patch too long to keep, or input cut to its tail, must not fall back to line-1 snippets.
408 + for (const width of [60, 120]) {
409 + const block = (value: string) =>
410 + Array.from({ length: 120 }, (_, i) => `${value} ${i} `.padEnd(width, "x")).join("\n");
411 + const long = {
412 + TargetContent: block("old"),
413 + ReplacementContent: block("new"),
414 + TargetFile: path,
415 + };
416 + const toolCall = normalizeAntigravityToolCall(
417 + parseToolUpdate(frame({ ...long, StartLine: 80, EndLine: 199 }, 80)).toolCall,
418 + );
419 + expect(toolCall.data.content).toMatchObject([{ patch: { format: "omitted" } }]);
420 + expect(acpToolCallDiffPatch(toolCall.data.content)).toBeUndefined();
421 + }
422 + });
423 +
424 it.each([
425 { CommandLine: "pwd", Cwd: "/one" },
426 { CommandLine: "pwd", WorkingDirectory: "/one" },
apps/server/src/provider/acp/AntigravityProtocol.ts
+76 -1
@@ -12,6 +12,13 @@ import * as AcpWireSchema from "effect-acp/schema-v1";
12
13 import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
14
15 +import {
16 + ANTIGRAVITY_EDIT_DIFF_OMITTED,
17 + antigravityEditPatch,
18 + isAntigravitySnippetPatch,
19 + readAntigravityPreEditFile,
20 +} from "./AntigravityEditLocation.ts";
21 +
22 const TOOL_TEXT_LIMIT = 8_000;
23 const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n";
24 const QUESTION_LABEL_LIMIT = 512;
@@ -163,6 +170,12 @@ function boundText(text: string, limit = TOOL_TEXT_LIMIT): string {
170 : copyBoundedText(`${TOOL_TEXT_TRUNCATED}${text.slice(-limit)}`);
171 }
172
173 +/** Keeps the tail of long tool text, as every bounded tool payload does. */
174 +export { boundText as boundAntigravityToolText };
175 +
176 +/** True when bounding cut some of this text. */
177 +export const isCutAntigravityToolText = (text: string) => text.includes(TOOL_TEXT_TRUNCATED);
178 +
179 interface ToolPayloadBudget {
180 nodes: number;
181 text: number;
@@ -350,7 +363,58 @@ function localImagePath(imagePath: string | undefined): string | undefined {
363 return /^[a-z][a-z\d+.-]*:/i.test(path) && !/^[a-z]:[\\/]/i.test(path) ? undefined : path;
364 }
365
353 -export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState {
366 +function hasTruncatedText(value: unknown): boolean {
367 + if (typeof value === "string") return value.startsWith(TOOL_TEXT_TRUNCATED);
368 + return Predicate.isObject(value) && Object.values(value).some(hasTruncatedText);
369 +}
370 +
371 +/** The ACP adapter renders a diff's `patch.text` ahead of its bare old/new snippets. */
372 +function withAntigravityEditPatches(
373 + content: ReadonlyArray<unknown>,
374 + data: Record<string, unknown>,
375 + readPreEditFile: ((path: string) => string | undefined) | undefined,
376 +) {
377 + return content.map((entry) => {
378 + if (!Predicate.isObject(entry) || entry.type !== "diff" || typeof entry.path !== "string")
379 + return entry;
380 + // Keep the first patch: once the edit runs, the file no longer holds the old text. A later
381 + // update's shared text budget can cut or drop it, and a cut patch would misplace the hunk.
382 + if (entry.patch !== undefined) {
383 + const patch: unknown = entry.patch;
384 + const cut =
385 + Predicate.isObject(patch) &&
386 + patch.format !== "omitted" &&
387 + (typeof patch.text !== "string" || patch.text.startsWith(TOOL_TEXT_TRUNCATED));
388 + return cut ? { ...entry, patch: { format: "omitted" } } : entry;
389 + }
390 + // Bounding keeps only the tail of long text, so a cut snippet cannot be located and a cut
391 + // old or new text would render the cut as file content.
392 + if ([data.rawInput, entry.oldText, entry.newText].some(hasTruncatedText))
393 + return { ...entry, patch: { format: "omitted" } };
394 + const text = antigravityEditPatch({
395 + path: entry.path,
396 + rawInput: data.rawInput,
397 + locations: data.locations,
398 + readPreEditFile,
399 + });
400 + // A truncated patch would no longer parse, and bare snippets would render at line 1.
401 + if (
402 + text === ANTIGRAVITY_EDIT_DIFF_OMITTED ||
403 + (text !== undefined && text.length > TOOL_TEXT_LIMIT)
404 + )
405 + return { ...entry, patch: { format: "omitted" } };
406 + if (text === undefined) return entry;
407 + return {
408 + ...entry,
409 + patch: isAntigravitySnippetPatch(text) ? { format: "snippet", text } : { text },
410 + };
411 + });
412 +}
413 +
414 +export function normalizeAntigravityToolCall(
415 + toolCall: AcpToolCallState,
416 + readPreEditFile = readAntigravityPreEditFile,
417 +): AcpToolCallState {
418 const input = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawInput));
419 const output = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawOutput));
420 const nativeCommand =
@@ -382,6 +446,17 @@ export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToo
446 if (command !== undefined) data.command = command;
447 if (cwd !== undefined) data.cwd = cwd;
448 if (imagePath !== undefined) data.imagePath = imagePath;
449 + if (kind === "edit") {
450 + const content = Array.isArray(data.content) ? data.content : [];
451 + // Full-access edits report only a path; without a hunk the checkpoint diff is the review.
452 + data.content = content.some((entry) => Predicate.isObject(entry) && entry.type === "diff")
453 + ? withAntigravityEditPatches(
454 + content,
455 + data,
456 + toolCall.status === "pending" ? readPreEditFile : undefined,
457 + )
458 + : [...content, { type: "diff", patch: { format: "omitted" } }];
459 + }
460 if (kind === "execute") {
461 data.item = {
462 ...(Predicate.isObject(data.item) ? data.item : {}),
apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts new
+195
@@ -0,0 +1,195 @@
1 +import * as NodeSqlite from "node:sqlite";
2 +
3 +import * as NodeServices from "@effect/platform-node/NodeServices";
4 +import { assert, describe, it } from "@effect/vitest";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Path from "effect/Path";
8 +import type * as EffectAcpSchema from "effect-acp/compat";
9 +
10 +import { watchAntigravityPromptOutcome } from "./AntigravityTurnOutcome.ts";
11 +
12 +const USER_INPUT = 14;
13 +const PLANNER_RESPONSE = 15;
14 +const TOOL = 8;
15 +const ERROR_MESSAGE = 17;
16 +
17 +// Error-step payloads trimmed from Antigravity 1.4.5 against a local Gemini endpoint.
18 +const errorPayload = (error: string) =>
19 + Buffer.concat([
20 + Buffer.from([0x0a, 0x24]),
21 + Buffer.from(
22 + `Agent execution terminated due to error.\u0012agent executor error: ${error}: ${error}\n(1) attached stack trace\n -- stack trace:`,
23 + ),
24 + ]);
25 +// An unparsable reset timestamp must not hide the reset delay.
26 +const QUOTA_ERROR = errorPayload(
27 + "Error 429, Message: Quota exhausted for test model., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:googleapis.com metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:soon] reason:QUOTA_EXHAUSTED]]",
28 +);
29 +const INVALID_ARGUMENT_ERROR = errorPayload(
30 + "Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []",
31 +);
32 +// The model's reply quoting the agent's quota notice is an ordinary planner response.
33 +const QUOTED_NOTICE = Buffer.from(
34 + "Usage Limit Reached\n\nYou have reached your current quota for this period. Your limit will reset in 1 hour.",
35 +);
36 +
37 +describe("watchAntigravityPromptOutcome", () => {
38 + it.effect("fails only turns whose own steps end in an upstream error", () =>
39 + Effect.gen(function* () {
40 + const fs = yield* FileSystem.FileSystem;
41 + const path = yield* Path.Path;
42 + const profileDirectory = yield* fs.makeTempDirectoryScoped();
43 + const sessionId = "e6aba774-5472-4277-b6ee-27b2e05570a7";
44 + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations");
45 + yield* fs.makeDirectory(conversations, { recursive: true });
46 + let nextIndex = 0;
47 + const appendSteps = (steps: ReadonlyArray<readonly [number, Uint8Array]>) => {
48 + const database = new NodeSqlite.DatabaseSync(path.join(conversations, `${sessionId}.db`));
49 + try {
50 + database.exec(
51 + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)",
52 + );
53 + const insert = database.prepare("INSERT INTO steps VALUES (?, ?, ?)");
54 + for (const [type, payload] of steps) insert.run(nextIndex++, type, payload);
55 + } finally {
56 + database.close();
57 + }
58 + };
59 + const turn = (
60 + steps: ReadonlyArray<readonly [number, Uint8Array]>,
61 + result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" },
62 + ) =>
63 + Effect.gen(function* () {
64 + const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId);
65 + appendSteps(steps);
66 + return yield* check(result);
67 + });
68 + const input = Buffer.from("Run the fixture.");
69 + const reply = Buffer.from("FIXTURE_OK");
70 +
71 + // The first prompt creates the session log.
72 + assert.isUndefined(
73 + yield* turn([
74 + [USER_INPUT, input],
75 + [PLANNER_RESPONSE, reply],
76 + ]),
77 + );
78 + assert.deepEqual(
79 + yield* turn([
80 + [USER_INPUT, input],
81 + [ERROR_MESSAGE, QUOTA_ERROR],
82 + ]),
83 + {
84 + class: "usage_limit",
85 + message: "You have reached your Antigravity quota for this period.",
86 + code: "RESOURCE_EXHAUSTED",
87 + retryable: true,
88 + resetAt: "1970-01-01T01:00:00.000Z",
89 + },
90 + );
91 + // The earlier error step is outside this turn.
92 + assert.isUndefined(
93 + yield* turn(
94 + [
95 + [USER_INPUT, input],
96 + [PLANNER_RESPONSE, QUOTED_NOTICE],
97 + ],
98 + {
99 + stopReason: "end_turn",
100 + usage: { inputTokens: 42, outputTokens: 3, totalTokens: 54 },
101 + },
102 + ),
103 + );
104 + assert.deepEqual(
105 + yield* turn([
106 + [USER_INPUT, input],
107 + [ERROR_MESSAGE, INVALID_ARGUMENT_ERROR],
108 + ]),
109 + {
110 + class: "provider_error",
111 + message: "Request contains an invalid argument.",
112 + code: "INVALID_ARGUMENT",
113 + retryable: false,
114 + },
115 + );
116 + // A completed tool keeps its usage, and the turn still fails.
117 + assert.equal(
118 + (yield* turn(
119 + [
120 + [USER_INPUT, input],
121 + [PLANNER_RESPONSE, reply],
122 + [TOOL, reply],
123 + [ERROR_MESSAGE, QUOTA_ERROR],
124 + ],
125 + {
126 + stopReason: "end_turn",
127 + usage: { inputTokens: 40, outputTokens: 5, totalTokens: 45 },
128 + },
129 + ))?.class,
130 + "usage_limit",
131 + );
132 + assert.isUndefined(
133 + yield* turn([
134 + [USER_INPUT, input],
135 + [PLANNER_RESPONSE, reply],
136 + ]),
137 + );
138 + // The agent maps the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.
139 + assert.deepEqual(yield* turn([], { stopReason: "refusal" }), {
140 + class: "usage_limit",
141 + message: "You have reached your Antigravity quota for this period.",
142 + code: "QUOTA_EXHAUSTED",
143 + retryable: true,
144 + });
145 + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
146 + );
147 +
148 + it.effect("reads only this session's own unlinked log, and keeps a typed refusal", () =>
149 + Effect.gen(function* () {
150 + const fs = yield* FileSystem.FileSystem;
151 + const path = yield* Path.Path;
152 + const profileDirectory = yield* fs.makeTempDirectoryScoped();
153 + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations");
154 + yield* fs.makeDirectory(conversations, { recursive: true });
155 + const own = "e6aba774-5472-4277-b6ee-27b2e05570a7";
156 + const peer = "0d9c2b4e-1111-4222-8333-944455556666";
157 + const append = (sessionId: string, type: number, payload: Uint8Array) => {
158 + const database = new NodeSqlite.DatabaseSync(path.join(conversations, `${sessionId}.db`));
159 + try {
160 + database.exec(
161 + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)",
162 + );
163 + database
164 + .prepare("INSERT INTO steps (step_type, step_payload) VALUES (?, ?)")
165 + .run(type, payload);
166 + } finally {
167 + database.close();
168 + }
169 + };
170 +
171 + // own.db links to a peer session; the peer's new error step is not this turn's.
172 + append(peer, USER_INPUT, Buffer.from("peer"));
173 + yield* fs.symlink(
174 + path.join(conversations, `${peer}.db`),
175 + path.join(conversations, `${own}.db`),
176 + );
177 + const linked = yield* watchAntigravityPromptOutcome(profileDirectory, own);
178 + append(peer, ERROR_MESSAGE, QUOTA_ERROR);
179 + assert.isUndefined(yield* linked({ stopReason: "end_turn" }));
180 + assert.equal((yield* linked({ stopReason: "refusal" }))?.class, "usage_limit");
181 +
182 + // An unreadable log gives no evidence, but the agent's typed refusal still fails the turn.
183 + yield* fs.remove(path.join(conversations, `${own}.db`));
184 + yield* fs.writeFileString(path.join(conversations, `${own}.db`), "not a database");
185 + const corrupt = yield* watchAntigravityPromptOutcome(profileDirectory, own);
186 + assert.isUndefined(yield* corrupt({ stopReason: "end_turn" }));
187 + assert.deepEqual(yield* corrupt({ stopReason: "refusal" }), {
188 + class: "usage_limit",
189 + message: "You have reached your Antigravity quota for this period.",
190 + code: "QUOTA_EXHAUSTED",
191 + retryable: true,
192 + });
193 + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
194 + );
195 +});
apps/server/src/provider/acp/AntigravityTurnOutcome.ts new
+194
@@ -0,0 +1,194 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and lstat read the native session log.
2 +import * as NodeFSP from "node:fs/promises";
3 +import * as NodePath from "node:path";
4 +import * as NodeSqlite from "node:sqlite";
5 +
6 +import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts";
7 +import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
8 +import * as DateTime from "effect/DateTime";
9 +import * as Effect from "effect/Effect";
10 +import * as Option from "effect/Option";
11 +import type * as EffectAcpSchema from "effect-acp/compat";
12 +
13 +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
14 +
15 +// CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory.
16 +const ERROR_STEP_TYPE = 17;
17 +// The harness error text leads the payload; a Go stack trace follows it.
18 +const MAX_ERROR_PAYLOAD_BYTES = 16_384;
19 +// The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.
20 +const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;
21 +const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;
22 +const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;
23 +const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;
24 +const GO_DURATION_PART = /(\d+(?:\.\d+)?)(ns|us|µs|μs|ms|h|m|s)/g;
25 +const GO_DURATION_UNIT_MS: Record<string, number> = {
26 + ns: 1e-6,
27 + us: 1e-3,
28 + µs: 1e-3,
29 + μs: 1e-3,
30 + ms: 1,
31 + s: 1_000,
32 + m: 60_000,
33 + h: 3_600_000,
34 +};
35 +const NATIVE_SESSION_ID = /^[\w-]+$/;
36 +
37 +interface LastStep {
38 + readonly type: number;
39 + readonly payload: Uint8Array | null;
40 +}
41 +
42 +const readSteps = <A>(file: string, read: (database: NodeSqlite.DatabaseSync) => A) =>
43 + Effect.try(() => {
44 + const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
45 + try {
46 + database.exec("PRAGMA busy_timeout = 100");
47 + const hasSteps =
48 + database
49 + .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
50 + .get() !== undefined;
51 + return hasSteps ? read(database) : undefined;
52 + } finally {
53 + database.close();
54 + }
55 + });
56 +
57 +const lastStepIndex = (database: NodeSqlite.DatabaseSync) => {
58 + const index = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx;
59 + return typeof index === "number" ? index : -1;
60 +};
61 +
62 +const lastStepAfter =
63 + (index: number) =>
64 + (database: NodeSqlite.DatabaseSync): LastStep | undefined => {
65 + const row = database
66 + .prepare(
67 + `SELECT step_type AS type, substr(step_payload, 1, ?) AS payload
68 + FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1`,
69 + )
70 + .get(MAX_ERROR_PAYLOAD_BYTES, index);
71 + if (typeof row?.type !== "number") return undefined;
72 + return { type: row.type, payload: row.payload instanceof Uint8Array ? row.payload : null };
73 + };
74 +
75 +function resetAtFrom(text: string, now: DateTime.Utc): string | undefined {
76 + // makeProviderFailure drops a timestamp that does not parse, so fall back to the delay.
77 + const timestamp = RESET_TIMESTAMP.exec(text)?.[1];
78 + if (timestamp !== undefined && Option.isSome(DateTime.make(timestamp))) return timestamp;
79 + const delay = RESET_DELAY.exec(text)?.[1];
80 + if (delay === undefined) return undefined;
81 + let delayMs = 0;
82 + for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) {
83 + delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0);
84 + }
85 + return delayMs > 0 ? DateTime.formatIso(DateTime.add(now, { milliseconds: delayMs })) : undefined;
86 +}
87 +
88 +function turnFailure(
89 + stopReason: EffectAcpSchema.StopReason,
90 + step: LastStep | undefined,
91 + now: DateTime.Utc,
92 +): OrchestrationV2ProviderFailure | undefined {
93 + const errorText =
94 + step?.type === ERROR_STEP_TYPE
95 + ? new TextDecoder().decode(step.payload ?? new Uint8Array())
96 + : undefined;
97 + // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.
98 + if (errorText === undefined && stopReason !== "refusal") return undefined;
99 + const text = errorText ?? "";
100 + const apiError = API_ERROR.exec(text);
101 + if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) {
102 + return makeProviderFailure({
103 + class: "usage_limit",
104 + message: "You have reached your Antigravity quota for this period.",
105 + code: apiError?.[3] ?? "QUOTA_EXHAUSTED",
106 + retryable: true,
107 + resetAt: resetAtFrom(text, now) ?? null,
108 + });
109 + }
110 + if (apiError === null) {
111 + return makeProviderFailure({
112 + class: "provider_error",
113 + message: "Antigravity stopped this turn because of an error.",
114 + });
115 + }
116 + const [, httpStatus, message, status] = apiError;
117 + const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED";
118 + return makeProviderFailure({
119 + class: rateLimited ? "usage_limit" : "provider_error",
120 + message: message!.trim(),
121 + code: status ?? null,
122 + retryable: rateLimited || Number(httpStatus) >= 500,
123 + });
124 +}
125 +
126 +const conversationSegments = ["antigravity-acp", "conversations"];
127 +
128 +/**
129 + * Antigravity reports an upstream API failure as a chat message and `end_turn`. Its
130 + * session log ends that turn with an error step, so the check reads only steps the
131 + * current prompt added, read-only, from this session's own unlinked database. Without
132 + * that evidence a typed `refusal` still fails the turn.
133 + */
134 +export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.watch")(function* (
135 + profileDirectory: string,
136 + sessionId: string,
137 +) {
138 + const typedOnly = (result: EffectAcpSchema.PromptResponse) =>
139 + DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now)));
140 + if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;
141 + const segments = [...conversationSegments, `${sessionId}.db`];
142 + const before = yield* Effect.tryPromise(async () => {
143 + const root = await antigravityProfileRoot(profileDirectory);
144 + if (root === undefined) return undefined;
145 + if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
146 + return undefined;
147 + }
148 + const database = await antigravityManagedPath(root, segments, "file");
149 + // A path that exists but fails the proof is a link or other foreign entry.
150 + if (database === undefined) {
151 + const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
152 + () => true,
153 + () => false,
154 + );
155 + return present ? undefined : { root, identity: undefined, startIndex: -1 };
156 + }
157 + return { root, identity: database.info, startIndex: undefined };
158 + }).pipe(Effect.orElseSucceed(() => undefined));
159 + if (before === undefined) {
160 + yield* Effect.logWarning("The Antigravity session log is not this session's own file.");
161 + return typedOnly;
162 + }
163 + const startIndex =
164 + before.startIndex ??
165 + (yield* readSteps(NodePath.join(before.root, ...segments), lastStepIndex).pipe(
166 + Effect.map((index) => index ?? -1),
167 + Effect.orElseSucceed(() => undefined),
168 + ));
169 + if (startIndex === undefined) {
170 + yield* Effect.logWarning("Could not read the Antigravity session log before the prompt.");
171 + return typedOnly;
172 + }
173 + return Effect.fn("AntigravityTurnOutcome.check")(function* (
174 + result: EffectAcpSchema.PromptResponse,
175 + ) {
176 + // The same file as before the prompt, or one this prompt created, still unlinked.
177 + const after = yield* Effect.tryPromise(() =>
178 + antigravityManagedPath(before.root, segments, "file"),
179 + ).pipe(Effect.orElseSucceed(() => undefined));
180 + const sameFile =
181 + after !== undefined &&
182 + (before.identity === undefined ||
183 + (after.info.dev === before.identity.dev && after.info.ino === before.identity.ino));
184 + const step = sameFile
185 + ? yield* readSteps(after.path, lastStepAfter(startIndex)).pipe(
186 + Effect.tapError(() =>
187 + Effect.logWarning("Could not read the Antigravity session log after the prompt."),
188 + ),
189 + Effect.orElseSucceed(() => undefined),
190 + )
191 + : undefined;
192 + return turnFailure(result.stopReason, step, yield* DateTime.now);
193 + });
194 +});
apps/server/src/provider/antigravityRelease.ts
+33 -32
@@ -1,5 +1,6 @@
1 -// 1.4.2 through 1.4.4 write skills/system/run-workflow/SKILL.md into every session workspace.
2 -const ANTIGRAVITY_RELEASE_VERSION = "1.4.1";
1 +// Hashes and sizes match the official ACP registry release. Like 1.4.2 through 1.4.4, it writes a
2 +// run-workflow skill into the workspace unless T3 disables the tool (antigravitySessionMeta).
3 +const ANTIGRAVITY_RELEASE_VERSION = "1.4.5";
4
5 export interface AntigravityReleaseAsset {
6 readonly version: string;
@@ -21,66 +22,66 @@ const releaseAssets = new Map<string, AntigravityReleaseAsset>([
22 "darwin-arm64",
23 {
24 version: ANTIGRAVITY_RELEASE_VERSION,
24 - url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.1-darwin-arm64.zip",
25 - sha256: "f9bdd68291ae78c38d2141e63bc86b84e6cc7b9f60f71652c68435a7943deb17",
26 - archiveBytes: 112_737_434,
27 - executable: { name: "agy_acp_server.par", bytes: 280_996_576 },
28 - harness: { name: "localharness_external", bytes: 120_246_928 },
25 + url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-arm64.zip",
26 + sha256: "886fff7767d08994ca39eb02c3d01a7532c7325a94aa33aaf52d52068733284f",
27 + archiveBytes: 97_923_855,
28 + executable: { name: "agy_acp_server.par", bytes: 178_915_920 },
29 + harness: { name: "localharness_external", bytes: 122_957_936 },
30 },
31 ],
32 [
33 "darwin-x64",
34 {
35 version: ANTIGRAVITY_RELEASE_VERSION,
35 - url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.1-darwin-x86_64.zip",
36 - sha256: "27e31f096874704f14167b07ef9e84cc77134615ee41d024f7b1c957add85307",
37 - archiveBytes: 118_349_036,
38 - executable: { name: "agy_acp_server.par", bytes: 285_186_624 },
39 - harness: { name: "localharness_external", bytes: 124_910_048 },
36 + url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-x86_64.zip",
37 + sha256: "b39f3573c03b9acb9df028853f647527f1f3133f32bd77e78b796e48a205114a",
38 + archiveBytes: 103_577_295,
39 + executable: { name: "agy_acp_server.par", bytes: 183_127_600 },
40 + harness: { name: "localharness_external", bytes: 127_612_208 },
41 },
42 ],
43 [
44 "linux-x64",
45 {
46 version: ANTIGRAVITY_RELEASE_VERSION,
46 - url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.1-linux-x86_64.zip",
47 - sha256: "2e37012ceb2a5c7fc7309b6e6596234fb637ee3c62a5199f65d4cbe777871384",
48 - archiveBytes: 336_170_339,
49 - executable: { name: "agy_acp_server.par", bytes: 930_826_753 },
50 - harness: { name: "localharness_external", bytes: 131_187_512 },
47 + url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-x86_64.zip",
48 + sha256: "923923a0d7dc8073f66cc6f78647a3107e3a7ee2b7e1a24df8b3927b5188013b",
49 + archiveBytes: 321_783_181,
50 + executable: { name: "agy_acp_server.par", bytes: 826_226_766 },
51 + harness: { name: "localharness_external", bytes: 133_926_136 },
52 },
53 ],
54 [
55 "linux-arm64",
56 {
57 version: ANTIGRAVITY_RELEASE_VERSION,
57 - url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.1-linux-arm64.zip",
58 - sha256: "609336a1c97545487e3ddd55dbd153dc0f40f4e6534486cc1c5f4c0ebb85c2da",
59 - archiveBytes: 321_922_507,
60 - executable: { name: "agy_acp_server.par", bytes: 933_416_796 },
61 - harness: { name: "localharness_external", bytes: 124_895_000 },
58 + url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-arm64.zip",
59 + sha256: "7d64246633ae094f67e3bbcd2d679e89048f91346d5339313336e7483f40f056",
60 + archiveBytes: 307_829_008,
61 + executable: { name: "agy_acp_server.par", bytes: 831_194_025 },
62 + harness: { name: "localharness_external", bytes: 127_512_832 },
63 },
64 ],
65 [
66 "win32-x64",
67 {
68 version: ANTIGRAVITY_RELEASE_VERSION,
68 - url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.1-windows-x86_64.zip",
69 - sha256: "5f5b7d0328df17c128b2be338d4567b0d24e56ace8196e88794fec37d1372554",
70 - archiveBytes: 129_599_308,
71 - executable: { name: "agy_acp_server.exe", bytes: 86_098_784 },
72 - harness: { name: "localharness_external.exe", bytes: 146_036_888 },
69 + url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-x86_64.zip",
70 + sha256: "d24f4c73c9f96d4f44384e281c855a56c72d8eaa9c5b0fad7ccb1635c6b63f50",
71 + archiveBytes: 100_423_655,
72 + executable: { name: "agy_acp_server.exe", bytes: 55_839_864 },
73 + harness: { name: "localharness_external.exe", bytes: 147_843_736 },
74 },
75 ],
76 [
77 "win32-arm64",
78 {
79 version: ANTIGRAVITY_RELEASE_VERSION,
79 - url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.1-windows-arm64.zip",
80 - sha256: "24c52bbc12aae20f55eb53d373669412d95a9c44fd59be4ea4e355918b91fbf7",
81 - archiveBytes: 132_507_344,
82 - executable: { name: "agy_acp_server.exe", bytes: 93_197_744 },
83 - harness: { name: "localharness_external.exe", bytes: 136_970_904 },
80 + url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-arm64.zip",
81 + sha256: "ab0a9aac8349e08ef289be6d16da8f89e3abe60eba5158032ef78c4a1220261c",
82 + archiveBytes: 102_703_121,
83 + executable: { name: "agy_acp_server.exe", bytes: 62_293_488 },
84 + harness: { name: "localharness_external.exe", bytes: 139_322_008 },
85 },
86 ],
87 ]);
apps/server/src/provider/model-manifest.json
+2 -1
@@ -75,8 +75,9 @@
75 {
76 "driver": "antigravity",
77 "t3CodeRange": ">=0.0.42",
78 - "recommendedRange": "=1.4.1",
78 + "recommendedRange": "=1.4.5 || =1.4.1",
79 "ranges": [
80 + { "range": "=1.4.5", "status": "supported" },
81 { "range": "=1.4.1", "status": "supported" },
82 { "range": "=1.3.0", "status": "supported" },
83 { "range": "=1.1.1", "status": "supported" }
apps/server/src/provider/providerCompatibility.test.ts
+18 -12
@@ -133,18 +133,24 @@ describe("provider compatibility", () => {
133 }
134 });
135
136 - it("supports the managed Antigravity runtime in the bundled manifest", () => {
137 - const policies = decodeCompatibilityPolicies(bundledManifest.compatibility);
138 - const release = resolveAntigravityReleaseAsset("darwin", "arm64");
139 - assert.strictEqual(
140 - resolveProviderCompatibility(
141 - policies,
142 - ProviderDriverKind.make("antigravity"),
143 - `agy_acp_server_${release?.version}`,
144 - )?.status,
145 - "supported",
146 - );
147 - });
136 + it.each([
137 + ["darwin", "arm64"],
138 + ["win32", "x64"],
139 + ] as const)(
140 + "supports the managed Antigravity runtime for %s-%s in the bundled manifest",
141 + (platform, arch) => {
142 + const policies = decodeCompatibilityPolicies(bundledManifest.compatibility);
143 + const release = resolveAntigravityReleaseAsset(platform, arch);
144 + assert.strictEqual(
145 + resolveProviderCompatibility(
146 + policies,
147 + ProviderDriverKind.make("antigravity"),
148 + `agy_acp_server_${release?.version}`,
149 + )?.status,
150 + "supported",
151 + );
152 + },
153 + );
154
155 it("classifies boundaries and treats unlisted versions and release tags as unknown", () => {
156 for (const [version, expected] of [
apps/server/src/server.ts
+5 -4
@@ -59,6 +59,7 @@ import * as ProviderHostLive from "./provider/ProviderHostLive.ts";
59 import * as DocumentText from "./provider/DocumentText.ts";
60 import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
61 import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
62 +import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";
63 import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
64 import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
65 import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";
@@ -570,10 +571,10 @@ const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe(
571 ),
572 );
573
573 -const layerOrchestrationApplication = CheckpointDiffQuery.layer.pipe(
574 - Layer.provideMerge(layerCheckpointStore),
575 - Layer.provideMerge(layerOrchestrationV2Runtime),
576 -);
574 +const layerOrchestrationApplication = Layer.merge(
575 + CheckpointDiffQuery.layer,
576 + NativeChildWorkQuery.layer,
577 +).pipe(Layer.provideMerge(layerCheckpointStore), Layer.provideMerge(layerOrchestrationV2Runtime));
578
579 const layerThreadSettlementWorker = Layer.effectDiscard(
580 ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())),
apps/server/src/ws.test.ts
+2
@@ -41,6 +41,7 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
41 import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
42 import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
43 import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
44 +import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";
45 import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";
46 import * as CodexInstallation from "./provider/CodexInstallation.ts";
47 import * as DeviceService from "./device/DeviceService.ts";
@@ -541,6 +542,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
542 Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }),
543 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
544 Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}),
545 + Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}),
546 Layer.mock(CommandOutputHub.CommandOutputHub)({}),
547 Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }),
548 Layer.mock(DeviceService.DeviceService)({}),
apps/server/src/ws.ts
+4
@@ -109,6 +109,7 @@ import {
109 import { RpcGroup, RpcSerialization, RpcServer } from "effect/rpc";
110
111 import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
112 +import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";
113 import * as ServerConfig from "./config.ts";
114 import * as EnvironmentTheme from "./environmentTheme.ts";
115 import * as Keybindings from "./keybindings.ts";
@@ -1350,6 +1351,7 @@ export const layerWsRpc = (
1351 const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;
1352 const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter;
1353 const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
1354 + const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery;
1355 const keybindings = yield* Keybindings.Keybindings;
1356 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
1357 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
@@ -1965,6 +1967,8 @@ export const layerWsRpc = (
1967 threadManagement.forceStopThread(input),
1968 [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) =>
1969 readWorkflowScript({ scriptPath: input.scriptPath }),
1970 + [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: (input) =>
1971 + nativeChildWork.getNativeChildWork(input),
1972 [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) =>
1973 threadManagement.getTurnItem(input).pipe(
1974 Effect.mapError(
apps/web/src/components/ChatView.tsx
+9
@@ -270,6 +270,7 @@ import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
270 import { useCitedHistory } from "./chat/citationProcedure";
271 import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
272 import { ThreadTimeline } from "./chat/ThreadTimeline";
273 +import { NativeChildWorkDialog } from "./chat/NativeChildWorkDialog";
274 import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
275 import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
276 import { resolveScrollToEndClearance } from "./composerFooterLayout";
@@ -3560,6 +3561,14 @@ export default function ChatView(props: ChatViewProps) {
3561 effortLabel={providerSubagentEffortLabel}
3562 status={providerSubagentStatus}
3563 onOpenParent={parentThreadLink?.open ?? null}
3564 + actions={
3565 + selectedProviderEntry?.driverKind === "antigravity" ? (
3566 + <NativeChildWorkDialog
3567 + environmentId={environmentId}
3568 + threadId={threadId}
3569 + />
3570 + ) : null
3571 + }
3572 />
3573 ) : null}
3574 {!composerMounted ? null : (
apps/web/src/components/chat/NativeChildWorkDialog.tsx new
+131
@@ -0,0 +1,131 @@
1 +import type {
2 + EnvironmentId,
3 + OrchestrationV2GetNativeChildWorkResult,
4 + OrchestrationV2NativeChildStep,
5 + OrchestrationV2NativeChildWork,
6 + ThreadId,
7 +} from "@t3tools/contracts";
8 +import { ListTreeIcon } from "lucide-react";
9 +import { useState } from "react";
10 +
11 +import { orchestrationEnvironment } from "../../state/orchestration";
12 +import { useEnvironmentQuery } from "../../state/query";
13 +import { Button } from "../ui/button";
14 +import {
15 + Dialog,
16 + DialogDescription,
17 + DialogFooter,
18 + DialogHeader,
19 + DialogPanel,
20 + DialogPopup,
21 + DialogTitle,
22 +} from "../ui/dialog";
23 +
24 +const stepLabel = (type: string) => {
25 + const words = type.toLowerCase().replaceAll("_", " ");
26 + return words.charAt(0).toUpperCase() + words.slice(1);
27 +};
28 +
29 +/** Read-only view of what a provider-native subagent's children did. Loads only while open. */
30 +export function NativeChildWorkDialog(props: {
31 + readonly environmentId: EnvironmentId;
32 + readonly threadId: ThreadId;
33 +}) {
34 + const [open, setOpen] = useState(false);
35 + return (
36 + <Dialog open={open} onOpenChange={setOpen}>
37 + <Button size="sm" variant="ghost" onClick={() => setOpen(true)}>
38 + <ListTreeIcon />
39 + <span className="@max-[420px]/composer-surface:sr-only">Subagent work</span>
40 + </Button>
41 + <DialogPopup className="max-w-2xl">
42 + <DialogHeader>
43 + <DialogTitle>Subagent work</DialogTitle>
44 + <DialogDescription>Read only. These subagents cannot take messages.</DialogDescription>
45 + </DialogHeader>
46 + {open ? <NativeChildWorkContent {...props} /> : null}
47 + </DialogPopup>
48 + </Dialog>
49 + );
50 +}
51 +
52 +function NativeChildWorkContent(props: {
53 + readonly environmentId: EnvironmentId;
54 + readonly threadId: ThreadId;
55 +}) {
56 + const query = useEnvironmentQuery<OrchestrationV2GetNativeChildWorkResult, unknown>(
57 + orchestrationEnvironment.nativeChildWork({
58 + environmentId: props.environmentId,
59 + input: { threadId: props.threadId },
60 + }),
61 + );
62 + const children = query.data?.children;
63 + return (
64 + <>
65 + <DialogPanel>
66 + {query.error !== null ? (
67 + <p className="text-sm text-destructive-foreground">{query.error}</p>
68 + ) : children === undefined ? (
69 + <p className="text-sm text-muted-foreground">Loading…</p>
70 + ) : children.length === 0 ? (
71 + <p className="text-sm text-muted-foreground">
72 + The provider has no record of which subagents this call started.
73 + </p>
74 + ) : (
75 + children.map((child) => <NativeChild key={child.conversationId} child={child} />)
76 + )}
77 + </DialogPanel>
78 + <DialogFooter variant="bare">
79 + <Button size="sm" variant="outline" disabled={query.isPending} onClick={query.refresh}>
80 + Refresh
81 + </Button>
82 + </DialogFooter>
83 + </>
84 + );
85 +}
86 +
87 +function NativeChild(props: { readonly child: OrchestrationV2NativeChildWork }) {
88 + const { child } = props;
89 + return (
90 + <section aria-label={child.role || "Subagent"} className="flex min-w-0 flex-col gap-2">
91 + <h3 className="text-sm font-medium text-foreground">{child.role || "Subagent"}</h3>
92 + <p className="whitespace-pre-wrap break-words text-sm text-muted-foreground">
93 + {child.prompt}
94 + </p>
95 + {child.truncated ? (
96 + <p className="text-xs text-muted-foreground">Earlier steps are not shown.</p>
97 + ) : null}
98 + {child.steps === null ? (
99 + <p className="text-xs text-muted-foreground">No transcript yet.</p>
100 + ) : (
101 + <ol className="m-0 flex list-none flex-col gap-2 border-s ps-3">
102 + {child.steps.map((step) => (
103 + <NativeChildStep key={step.index} step={step} />
104 + ))}
105 + </ol>
106 + )}
107 + </section>
108 + );
109 +}
110 +
111 +function NativeChildStep(props: { readonly step: OrchestrationV2NativeChildStep }) {
112 + const { step } = props;
113 + return (
114 + <li className="flex min-w-0 flex-col gap-1">
115 + <span className="text-xs font-medium text-muted-foreground">
116 + {stepLabel(step.type)}
117 + {step.status !== null && step.status !== "DONE" ? ` · ${stepLabel(step.status)}` : ""}
118 + </span>
119 + {step.toolCalls.length === 0 ? null : (
120 + <code className="whitespace-pre-wrap break-all text-xs text-foreground">
121 + {step.toolCalls.map((call) => `${call.name} ${call.input}`).join("\n")}
122 + </code>
123 + )}
124 + {step.text === null ? null : (
125 + <pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground">
126 + {step.text}
127 + </pre>
128 + )}
129 + </li>
130 + );
131 +}
apps/web/src/components/chat/ProviderSubagentBar.tsx
+3
@@ -4,6 +4,7 @@ import {
4 } from "@t3tools/client-runtime/state/thread-execution";
5 import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
6 import { ArrowUpLeftIcon } from "lucide-react";
7 +import type { ReactNode } from "react";
8
9 import { tickTextContent } from "~/lib/tickTextContent";
10 import type { ProviderInstanceEntry } from "../../providerInstances";
@@ -17,6 +18,7 @@ export function ProviderSubagentBar(props: {
18 readonly effortLabel: string | null;
19 readonly status: ProviderSubagentStatus | null;
20 readonly onOpenParent: (() => void) | null;
21 + readonly actions?: ReactNode;
22 }) {
23 const { status } = props;
24 const live = status !== null && isOrchestrationV2WorkActive(status.status);
@@ -64,6 +66,7 @@ export function ProviderSubagentBar(props: {
66 <span className="shrink-0 text-muted-foreground @max-[640px]/composer-surface:sr-only">
67 Runs on its own
68 </span>
69 + {props.actions}
70 {props.onOpenParent ? (
71 <Button size="sm" variant="ghost" onClick={props.onOpenParent}>
72 <ArrowUpLeftIcon />
docs/user/composer.md
+2 -1
@@ -37,7 +37,8 @@ Attach up to 100 files per message. Each image can be up to 10 MiB, with at most
37 50 MiB each, subject to the environment's upload support and limit. The agent
38 receives them on the environment's machine. Provider and model limits still
39 apply, including images already in the conversation. A video attachment gives
40 -the agent a file path; it does not enable native video input.
40 +the agent a file path; only [Antigravity](./providers-antigravity.md#skills-and-attachments)
41 +sends supported videos to Gemini models as video.
42
43 Uploads begin when you add an attachment. All uploads must finish before the
44 message can send. Retry or remove a failed upload. On web and desktop, reloading
docs/user/providers-antigravity.md
+11 -7
@@ -101,16 +101,20 @@ Skills for every project go in `~/.gemini/config/skills` or
101 `~/.gemini/antigravity-cli/skills`. Antigravity does not read `~/.agents/skills`,
102 so a skill there only appears when the project itself is your home directory.
103
104 -Antigravity receives images directly. Every other attachment, including PDFs,
105 -text, audio, archives, and videos, is passed as a saved file path for the agent
106 -to inspect with its tools. A video path does not enable native video input.
104 +Antigravity receives images and audio directly, and reads PDFs and text files as
105 +documents. With the managed runtime on macOS and Linux, an MP4 video up to 20 MiB
106 +is sent as video to Gemini models. Other attachments, and videos for other models, are passed as a
107 +saved file path for the agent to inspect with its tools.
108
109 ### Subagents
110
110 -Antigravity groups subagent activity into batches. You cannot open or control
111 -individual subagents, and an idle batch does not confirm that every child
112 -succeeded. See [agent work](./thread-sidebar.md#inspect-agent-work) for where to
113 -inspect activity.
111 +Antigravity groups subagent activity into batches. Open a batch and select
112 +**Subagent work** (**Work** on mobile) to read each child's role, prompt, and recent steps. This view
113 +is read only: you cannot message or control individual subagents, and an idle
114 +batch does not confirm that every child succeeded. If Antigravity did not record
115 +which children a batch started, the view says so. See
116 +[agent work](./thread-sidebar.md#inspect-agent-work) for where to inspect
117 +activity.
118
119 ## Accounts and removal
120
packages/client-runtime/src/state/orchestration.ts
+7
@@ -103,6 +103,13 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
103 staleTimeMs: 300_000,
104 idleTtlMs: 300_000,
105 }),
106 + // Mounted only while a subagent inspector is open; running children change between opens.
107 + nativeChildWork: createEnvironmentRpcQueryAtomFamily(runtime, {
108 + label: "environment-data:orchestration:native-child-work",
109 + tag: ORCHESTRATION_V2_WS_METHODS.getNativeChildWork,
110 + staleTimeMs: 0,
111 + idleTtlMs: 0,
112 + }),
113 stopWorkflow: createEnvironmentRpcCommand(runtime, {
114 label: "environment-data:orchestration:stop-workflow",
115 tag: ORCHESTRATION_V2_WS_METHODS.stopWorkflow,
packages/contracts/src/orchestrationV2.ts
+52
@@ -3568,6 +3568,7 @@ export const ORCHESTRATION_V2_WS_METHODS = {
3568 getOlderSettledThreads: "orchestration.getOlderSettledThreads",
3569 getThreadProjection: "orchestration.getThreadProjection",
3570 getWorkflowScript: "orchestration.getWorkflowScript",
3571 + getNativeChildWork: "orchestration.getNativeChildWork",
3572 stopWorkflow: "orchestration.stopWorkflow",
3573 forceStopThread: "orchestration.forceStopThread",
3574 getTurnItem: "orchestration.getTurnItem",
@@ -4007,6 +4008,53 @@ export const OrchestrationV2GetWorkflowScriptResult = Schema.Struct({
4008 export type OrchestrationV2GetWorkflowScriptResult =
4009 typeof OrchestrationV2GetWorkflowScriptResult.Type;
4010
4011 +/** Names a provider-native subagent's child thread. */
4012 +export const OrchestrationV2GetNativeChildWorkInput = Schema.Struct({
4013 + threadId: ThreadId,
4014 +});
4015 +export type OrchestrationV2GetNativeChildWorkInput =
4016 + typeof OrchestrationV2GetNativeChildWorkInput.Type;
4017 +
4018 +export const OrchestrationV2NativeChildStep = Schema.Struct({
4019 + index: NonNegativeInt,
4020 + type: Schema.String,
4021 + status: Schema.NullOr(Schema.String),
4022 + text: Schema.NullOr(Schema.String),
4023 + toolCalls: Schema.Array(Schema.Struct({ name: Schema.String, input: Schema.String })),
4024 +});
4025 +export type OrchestrationV2NativeChildStep = typeof OrchestrationV2NativeChildStep.Type;
4026 +
4027 +/** Read-only: native children cannot take messages. */
4028 +export const OrchestrationV2NativeChildWork = Schema.Struct({
4029 + conversationId: TrimmedNonEmptyString,
4030 + role: Schema.String,
4031 + prompt: Schema.String,
4032 + /** Null when the provider has no readable transcript for this child. */
4033 + steps: Schema.NullOr(Schema.Array(OrchestrationV2NativeChildStep)),
4034 + /** Earlier steps were left out to keep the read bounded. */
4035 + truncated: Schema.Boolean,
4036 +});
4037 +export type OrchestrationV2NativeChildWork = typeof OrchestrationV2NativeChildWork.Type;
4038 +
4039 +/** Empty when the provider's records do not prove which children the subagent launched. */
4040 +export const OrchestrationV2GetNativeChildWorkResult = Schema.Struct({
4041 + children: Schema.Array(OrchestrationV2NativeChildWork),
4042 +});
4043 +export type OrchestrationV2GetNativeChildWorkResult =
4044 + typeof OrchestrationV2GetNativeChildWorkResult.Type;
4045 +
4046 +export class OrchestrationV2GetNativeChildWorkError extends Schema.TaggedError<OrchestrationV2GetNativeChildWorkError>()(
4047 + "OrchestrationV2GetNativeChildWorkError",
4048 + {
4049 + threadId: ThreadId,
4050 + cause: Schema.optional(Schema.Defect()),
4051 + },
4052 +) {
4053 + override get message(): string {
4054 + return "Failed to read the subagent's work.";
4055 + }
4056 +}
4057 +
4058 const WORKFLOW_FILE_ERROR_MESSAGES = {
4059 "invalid-path": "Workflow files must be absolute paths with the expected extension.",
4060 "root-unavailable": "Workflow file root unavailable.",
@@ -4186,6 +4234,10 @@ export const OrchestrationV2RpcSchemas = {
4234 input: OrchestrationV2GetWorkflowScriptInput,
4235 output: OrchestrationV2GetWorkflowScriptResult,
4236 },
4237 + getNativeChildWork: {
4238 + input: OrchestrationV2GetNativeChildWorkInput,
4239 + output: OrchestrationV2GetNativeChildWorkResult,
4240 + },
4241 getTurnItem: {
4242 input: OrchestrationV2GetTurnItemInput,
4243 output: OrchestrationV2GetTurnItemResult,
packages/contracts/src/rpc.ts
+11
@@ -221,6 +221,7 @@ import {
221 import {
222 ORCHESTRATION_V2_WS_METHODS,
223 OrchestrationGetWorkflowScriptError,
224 + OrchestrationV2GetNativeChildWorkError,
225 OrchestrationV2StopWorkflowError,
226 OrchestrationV2ForceStopThreadError,
227 OrchestrationV2DispatchCommandError,
@@ -1816,6 +1817,15 @@ const WsOrchestrationV2GetWorkflowScriptRpc = Rpc.make(
1817 },
1818 );
1819
1820 +const WsOrchestrationV2GetNativeChildWorkRpc = Rpc.make(
1821 + ORCHESTRATION_V2_WS_METHODS.getNativeChildWork,
1822 + {
1823 + payload: OrchestrationV2RpcSchemas.getNativeChildWork.input,
1824 + success: OrchestrationV2RpcSchemas.getNativeChildWork.output,
1825 + error: Schema.Union([OrchestrationV2GetNativeChildWorkError, EnvironmentAuthorizationError]),
1826 + },
1827 +);
1828 +
1829 const WsOrchestrationV2GetTurnItemRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.getTurnItem, {
1830 payload: OrchestrationV2RpcSchemas.getTurnItem.input,
1831 success: OrchestrationV2RpcSchemas.getTurnItem.output,
@@ -2161,6 +2171,7 @@ export const WsRpcGroup = RpcGroup.make(
2171 WsSubscribeResourceTelemetryRpc,
2172 WsOrchestrationV2DispatchCommandRpc,
2173 WsOrchestrationV2GetWorkflowScriptRpc,
2174 + WsOrchestrationV2GetNativeChildWorkRpc,
2175 WsOrchestrationV2StopWorkflowRpc,
2176 WsOrchestrationV2ForceStopThreadRpc,
2177 WsOrchestrationV2GetTurnItemRpc,
packages/provider-acp/src/server/AcpSessionRuntime.ts
+19 -3
@@ -123,7 +123,12 @@ export interface AcpSessionRuntimeOptions {
123 /** Authenticate before opening: Antigravity selects its credential source from the method. */
124 readonly authenticateEagerly?: boolean;
125 readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
126 + /** Sent on every session/new, load, resume and fork; omitting them clears an agent's stored roots. */
127 readonly additionalDirectories?: ReadonlyArray<string>;
128 + /** Session `_meta`, chosen from the negotiated agent before each session setup or activation. */
129 + readonly sessionMeta?: (
130 + initializeResult: EffectAcpSchema.InitializeResponse,
131 + ) => EffectAcpSchema.NewSessionRequest["_meta"] | undefined;
132 readonly transformStdout?: EffectAcpClient.AcpClientOptions["transformStdout"];
133 readonly transformSessionUpdate?: (
134 notification: EffectAcpSchema.SessionNotification,
@@ -2108,6 +2113,16 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2113 return activationOptions?.mcpServers ?? options.mcpServers ?? [];
2114 };
2115
2116 + const sessionSetupFields = (initializeResult: EffectAcpSchema.InitializeResponse) => {
2117 + const meta = options.sessionMeta?.(initializeResult);
2118 + return {
2119 + ...(options.additionalDirectories?.length
2120 + ? { additionalDirectories: options.additionalDirectories }
2121 + : {}),
2122 + ...(meta == null ? {} : { _meta: meta }),
2123 + };
2124 + };
2125 +
2126 const startOnce = Effect.gen(function* () {
2127 const initializeResult = yield* initialize;
2128
@@ -2163,9 +2178,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2178 | EffectAcpSchema.LoadSessionResponse
2179 | EffectAcpSchema.NewSessionResponse
2180 | EffectAcpSchema.ResumeSessionResponse;
2166 - const additionalDirectories = options.additionalDirectories?.length
2167 - ? { additionalDirectories: options.additionalDirectories }
2168 - : {};
2181 + const additionalDirectories = sessionSetupFields(initializeResult);
2182 if (options.resumeSessionId) {
2183 sessionId = options.resumeSessionId;
2184 if (
@@ -2400,6 +2413,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2413 const requestPayload = {
2414 sessionId,
2415 cwd: options.cwd,
2416 + ...sessionSetupFields(started.initializeResult),
2417 mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2418 } satisfies EffectAcpSchema.LoadSessionRequest;
2419 return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);
@@ -2412,6 +2426,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2426 const requestPayload = {
2427 sessionId,
2428 cwd: options.cwd,
2429 + ...sessionSetupFields(started.initializeResult),
2430 mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2431 } satisfies EffectAcpSchema.ResumeSessionRequest;
2432 return runLoggedRequest(
@@ -2428,6 +2443,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2443 const requestPayload = {
2444 sessionId,
2445 cwd: options.cwd,
2446 + ...sessionSetupFields(started.initializeResult),
2447 mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2448 } satisfies EffectAcpSchema.ForkSessionRequest;
2449 return runLoggedRequest(
packages/provider-acp/src/server/adapter.ts
+121 -17
@@ -235,28 +235,35 @@ export function acpPerTurnPromptUsage(
235 usage: EffectAcpSchema.Usage | null | undefined,
236 hasSubagents: boolean,
237 terminalStatus: OrchestrationV2ProviderTurn["status"],
238 + geminiUsage = false,
239 ): TurnTokenUsage {
240 if (usage == null) {
241 return { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents };
242 }
243 + const inputTokens = geminiUsage
244 + ? usage.inputTokens + (usage.cachedReadTokens ?? 0)
245 + : usage.inputTokens;
246 + const outputTokens = geminiUsage
247 + ? usage.outputTokens + (usage.thoughtTokens ?? 0)
248 + : usage.outputTokens;
249 // TurnTokenUsage contract: input includes cache read + write and reasoning
250 // is a subset of output, so clamp counters that exceed their parent and
251 // drop the ones the agent left unset. Cache writes are capped at whatever
252 // cache reads leave of input, so the pair cannot exceed it.
253 const clampSubset = (value: number | null | undefined, parent: number) =>
254 value == null ? undefined : Math.min(value, parent);
248 - const cachedInputTokens = clampSubset(usage.cachedReadTokens, usage.inputTokens);
255 + const cachedInputTokens = clampSubset(usage.cachedReadTokens, inputTokens);
256 const cacheCreationTokens = clampSubset(
257 usage.cachedWriteTokens,
251 - usage.inputTokens - (cachedInputTokens ?? 0),
258 + inputTokens - (cachedInputTokens ?? 0),
259 );
253 - const reasoningTokens = clampSubset(usage.thoughtTokens, usage.outputTokens);
260 + const reasoningTokens = clampSubset(usage.thoughtTokens, outputTokens);
261 return {
262 usageScope: "main_agent",
263 usageStatus: terminalStatus === "completed" ? "complete" : "partial",
264 hasSubagents,
258 - inputTokens: usage.inputTokens,
259 - outputTokens: usage.outputTokens,
265 + inputTokens,
266 + outputTokens,
267 ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
268 ...(cacheCreationTokens === undefined ? {} : { cacheCreationTokens }),
269 ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
@@ -267,9 +274,25 @@ export interface AcpAdapterV2Flavor {
274 readonly buildPrompt?: (input: {
275 readonly text: string;
276 readonly attachments: ReadonlyArray<ChatAttachment>;
277 + readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
278 readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
279 + readonly agentVersion: string | undefined;
280 + /** The session's model after selection, with its display name when the agent lists it. */
281 + readonly currentModel: { readonly id: string; readonly name: string | undefined } | undefined;
282 }) => Effect.Effect<ReadonlyArray<EffectAcpSchema.ContentBlock>, EffectAcpErrors.AcpError>;
283 readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
284 + /**
285 + * Runs before `session/prompt`. The returned check sees a prompt the agent ended
286 + * without an error or cancel, and reports a failure its stop reason hid. A reported
287 + * failure restarts the runtime before the next turn.
288 + */
289 + readonly watchPromptOutcome?: (
290 + sessionId: string,
291 + ) => Effect.Effect<
292 + (
293 + result: EffectAcpSchema.PromptResponse,
294 + ) => Effect.Effect<OrchestrationV2ProviderFailure | undefined>
295 + >;
296 readonly requiresSignIn?: (cause: unknown) => boolean;
297 /**
298 * Runs before attachment paths, T3 instructions and native slash-command detection,
@@ -412,6 +435,8 @@ export interface AcpAdapterV2Flavor {
435 * leaves usage semantics open, so this stays unset until proven live.
436 */
437 readonly reportsPerTurnPromptUsage?: boolean;
438 + /** Gemini-style usage: inputTokens leaves out cachedReadTokens, outputTokens leaves out thoughtTokens. */
439 + readonly geminiPromptUsage?: boolean;
440 /** Grok can retain task_already_running until process exit. */
441 readonly restartRuntimeAfterInterrupt?: boolean;
442 /** Prompt failures after which the agent process keeps failing until replaced. */
@@ -428,6 +453,13 @@ export interface AcpAdapterV2Flavor {
453 * fail before `session/prompt`.
454 */
455 readonly supportsImagePrompts?: boolean;
456 + /**
457 + * True when this session's native system prompt carries T3's PR-linking instructions, so
458 + * turns omit them. Must use the same negotiated check that sent them on session setup.
459 + */
460 + readonly sessionCarriesPullRequestLinking?: (
461 + initializeResult: EffectAcpSchema.InitializeResponse,
462 + ) => boolean;
463 }
464
465 function acpSupportsImagePrompts(input: {
@@ -909,12 +941,45 @@ function structuredFileChanges(toolCall: AcpToolCallState) {
941 // Bound diff search to protect the event loop; empty-sided diffs need no search.
942 const ACP_V1_DIFF_MAX_EDITS = 1_000;
943
912 -export function acpToolCallDiffPatch(content: unknown): string | undefined {
944 +/**
945 + * A `snippet` patch has no known location. Keep its recorded text, so no view numbers it
946 + * from line 1.
947 + */
948 +export function acpToolCallSnippetEdit(content: unknown) {
949 if (!Array.isArray(content)) return undefined;
950 const diffs = content.flatMap((entry) => {
951 const diff = unknownRecord(entry);
952 return diff?.type === "diff" ? [diff] : [];
953 });
954 + const diff = diffs.length === 1 ? diffs[0] : undefined;
955 + if (diff === undefined || unknownRecord(diff.patch)?.format !== "snippet") return undefined;
956 + return typeof diff.oldText === "string" && typeof diff.newText === "string"
957 + ? { oldStr: diff.oldText, newStr: diff.newText }
958 + : undefined;
959 +}
960 +
961 +/**
962 + * No preview when a flavor marked a diff `omitted` (too large) or `snippet` (line unknown);
963 + * the checkpoint diff shows it.
964 + */
965 +function acpToolCallDiffUnpreviewable(content: unknown): boolean {
966 + return (
967 + Array.isArray(content) &&
968 + content.some((entry) => {
969 + const format = unknownRecord(unknownRecord(entry)?.patch)?.format;
970 + return format === "omitted" || format === "snippet";
971 + })
972 + );
973 +}
974 +
975 +export function acpToolCallDiffPatch(content: unknown): string | undefined {
976 + if (!Array.isArray(content) || acpToolCallDiffUnpreviewable(content)) {
977 + return undefined;
978 + }
979 + const diffs = content.flatMap((entry) => {
980 + const diff = unknownRecord(entry);
981 + return diff?.type === "diff" ? [diff] : [];
982 + });
983 for (const diff of diffs) {
984 const patch = unknownRecord(diff.patch);
985 if (typeof patch?.text === "string") {
@@ -3916,14 +3981,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3981 }
3982 case "edit":
3983 case "delete":
3919 - case "move":
3984 + case "move": {
3985 + const snippet = acpToolCallSnippetEdit(toolCall.data.content);
3986 + const unpreviewable = acpToolCallDiffUnpreviewable(toolCall.data.content);
3987 turnItem = {
3988 ...base,
3989 type: "file_change",
3990 fileName: path ?? toolCall.title ?? "File change",
3924 - ...(diffText === undefined ? {} : { diffStr: diffText }),
3991 + ...(snippet ??
3992 + (unpreviewable || diffText === undefined ? {} : { diffStr: diffText })),
3993 };
3994 break;
3995 + }
3996 case "fetch": {
3997 // Grok rawOutput.Content is unreadable by textFromUnknown; bounded content blocks duplicate it.
3998 const snippet =
@@ -7092,6 +7161,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7161 context.promptUsage,
7162 context.subagents.size > 0,
7163 status,
7164 + flavor.geminiPromptUsage,
7165 ),
7166 }),
7167 });
@@ -7409,11 +7479,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7479 }
7480 if (flavor.buildPrompt) {
7481 const setup = yield* Ref.get(activeSessionSetup);
7482 + const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);
7483 + const currentModelId = modelOption?.currentValue;
7484 const blocks = yield* flavor
7485 .buildPrompt({
7486 text,
7487 attachments: turnInput.message.attachments,
7488 + resolveAttachmentPath: host.resolveAttachmentPath,
7489 promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities,
7490 + agentVersion: setup?.initializeResult.agentInfo?.version,
7491 + currentModel:
7492 + typeof currentModelId !== "string" || modelOption === undefined
7493 + ? undefined
7494 + : {
7495 + id: currentModelId,
7496 + name: flattenSelectChoices(modelOption.options).find(
7497 + (choice) => choice.value === currentModelId,
7498 + )?.name,
7499 + },
7500 })
7501 .pipe(
7502 Effect.mapError(
@@ -7459,11 +7542,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7542 });
7543 }
7544 if (!isNativeSlashCommand) {
7545 + const sessionSetup = yield* Ref.get(activeSessionSetup);
7546 prompt.push({
7547 type: "text",
7548 text: buildRuntimeInstructions({
7549 harness: flavor.runtimeHarness ?? driver,
7550 model: turnInput.modelSelection.model,
7551 + pullRequestLinking:
7552 + sessionSetup === null ||
7553 + flavor.sessionCarriesPullRequestLinking?.(sessionSetup.initializeResult) !== true,
7554 }),
7555 });
7556 }
@@ -7778,6 +7865,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7865 }
7866 return;
7867 }
7868 + const checkPromptOutcome =
7869 + flavor.watchPromptOutcome === undefined
7870 + ? undefined
7871 + : yield* flavor.watchPromptOutcome(requestedSessionId);
7872 const promptGeneration = yield* Ref.get(runtimeCallbackGeneration);
7873 yield* runtime.prompt({ prompt: promptParts!.prompt }).pipe(
7874 Effect.tap(() =>
@@ -7824,13 +7915,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7915 if (context.finalized || followsAgentWorkState) return;
7916 // ACP v2 reports a failed prompt as an idle `error`, not an RPC error.
7917 const idleError = result.stopReason === "error" && !context.interrupted;
7827 - const status = idleError
7828 - ? "failed"
7829 - : result.stopReason === "cancelled"
7830 - ? context.interrupted
7831 - ? "interrupted"
7832 - : "cancelled"
7833 - : "completed";
7918 + const hiddenFailure =
7919 + checkPromptOutcome === undefined ||
7920 + context.interrupted ||
7921 + result.stopReason === "error" ||
7922 + result.stopReason === "cancelled"
7923 + ? undefined
7924 + : yield* checkPromptOutcome(result);
7925 + if (hiddenFailure !== undefined) {
7926 + yield* Ref.set(runtimeRestartRequired, true);
7927 + }
7928 + const failure =
7929 + hiddenFailure ?? (idleError ? idleErrorFailure(result.error) : undefined);
7930 + const status =
7931 + failure !== undefined
7932 + ? "failed"
7933 + : result.stopReason === "cancelled"
7934 + ? context.interrupted
7935 + ? "interrupted"
7936 + : "cancelled"
7937 + : "completed";
7938 if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {
7939 context.promptSettled = true;
7940 context.promptSettledStatus = status;
@@ -7839,11 +7943,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7943 yield* finishRegisteredBackgroundTool({ taskId, ...completion });
7944 }
7945 }
7842 - if (idleError) {
7946 + if (failure !== undefined) {
7947 yield* terminalizeOpenForegroundTools(context, "failed");
7948 // Unlike an RPC failure, the agent survives an idle error, so its
7949 // background tools and subagents keep reporting to this run.
7846 - yield* finalizeTurn(context, "failed", idleErrorFailure(result.error), {
7950 + yield* finalizeTurn(context, "failed", failure, {
7951 childTurnsContinue: hasSurvivingBackgroundWork(context),
7952 });
7953 return;
packages/provider-core/src/server/runtimeInstructions.test.ts
+11
@@ -3,6 +3,17 @@ import { assert, describe, it } from "@effect/vitest";
3 import { buildRuntimeInstructions } from "./runtimeInstructions.ts";
4
5 describe("buildRuntimeInstructions", () => {
6 + it("leaves PR linking to a session that already carries it, and keeps runtime identity", () => {
7 + const instructions = buildRuntimeInstructions({
8 + harness: "Antigravity",
9 + model: "gemini-3.8-flash",
10 + pullRequestLinking: false,
11 + });
12 +
13 + assert.include(instructions, "through the Antigravity harness, as gemini-3.8-flash.");
14 + assert.notInclude(instructions, "<pull_request_linking>");
15 + });
16 +
17 it("links PRs the agent creates, takes over, or pushes to, and no others", () => {
18 const instructions = buildRuntimeInstructions({ harness: "Codex" });
19
packages/provider-core/src/server/runtimeInstructions.ts
+8 -2
@@ -1,4 +1,5 @@
1 -const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>
1 +/** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */
2 +export const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>
3 Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools do not link for you. If linking fails, say so. Skip PRs you only read or review, and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR <full URL>, head <SHA>, checks and reviews <state>. Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.
4 </pull_request_linking>`;
5
@@ -8,6 +9,8 @@ export function buildRuntimeInstructions(runtime: {
9 readonly model?: string | undefined;
10 readonly modelName?: string | undefined;
11 readonly reasoningEffort?: string | undefined;
12 + /** False when the session's system prompt already carries the linking instructions. */
13 + readonly pullRequestLinking?: boolean;
14 }): string {
15 const harness = toSingleLine(runtime.harness);
16 const model = toSingleLine(runtime.model ?? "");
@@ -17,7 +20,10 @@ export function buildRuntimeInstructions(runtime: {
20 modelName && modelName !== model ? `${modelName} (model slug: ${model})` : model;
21 const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : "";
22 const effortInfo = effort ? ` with ${effort} reasoning effort` : "";
20 - return `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio in your response using Markdown image syntax with absolute file paths. Link any other file you produce using its absolute path so the user can open it in T3 Code's files viewer.</runtime_info>\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`;
23 + const runtimeInfo = `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio in your response using Markdown image syntax with absolute file paths. Link any other file you produce using its absolute path so the user can open it in T3 Code's files viewer.</runtime_info>`;
24 + return runtime.pullRequestLinking === false
25 + ? runtimeInfo
26 + : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`;
27 }
28
29 function toSingleLine(value: string): string {