TypeScript
feat(antigravity): runtime 1.4.5 with real turn failures and subagent work (#28629)
Theo Browneab8e488e10d8
diff --git a/apps/mobile/src/features/threads/NativeChildWorkSheet.tsx b/apps/mobile/src/features/threads/NativeChildWorkSheet.tsxnew file mode 100644index 00000000000..1133b866014--- /dev/null+++ b/apps/mobile/src/features/threads/NativeChildWorkSheet.tsx@@ -0,0 +1,116 @@+import type {+ EnvironmentId,+ OrchestrationV2GetNativeChildWorkResult,+ OrchestrationV2NativeChildWork,+ ThreadId,+} from "@t3tools/contracts";+import { ScrollView, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AppText as Text } from "../../components/ui/AppText";+import { Button } from "../../components/ui/Button";+import { Sheet } from "../../components/ui/Sheet";+import { orchestrationEnvironment } from "../../state/orchestration";+import { useEnvironmentQuery } from "../../state/query";++const stepLabel = (type: string) => {+ const words = type.toLowerCase().replaceAll("_", " ");+ return words.charAt(0).toUpperCase() + words.slice(1);+};++/** Read-only view of what a provider-native subagent's children did. Mount only while open. */+export function NativeChildWorkSheet(props: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly onClose: () => void;+}) {+ const insets = useSafeAreaInsets();+ const query = useEnvironmentQuery<OrchestrationV2GetNativeChildWorkResult, unknown>(+ orchestrationEnvironment.nativeChildWork({+ environmentId: props.environmentId,+ input: { threadId: props.threadId },+ }),+ );+ const children = query.data?.children;+ return (+ <Sheet title="Subagent work" onClose={props.onClose}>+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ contentContainerStyle={{+ gap: 16,+ paddingHorizontal: 20,+ paddingTop: 12,+ paddingBottom: Math.max(20, insets.bottom),+ }}+ >+ <Text className="font-sans text-xs text-foreground-secondary">+ Read only. These subagents cannot take messages.+ </Text>+ {query.error !== null ? (+ <Text selectable className="font-sans text-sm text-danger-foreground">+ {query.error}+ </Text>+ ) : children === undefined ? (+ <Text className="font-sans text-sm text-foreground-secondary">Loading…</Text>+ ) : children.length === 0 ? (+ <Text className="font-sans text-sm text-foreground-secondary">+ The provider has no record of which subagents this call started.+ </Text>+ ) : (+ children.map((child) => <NativeChild key={child.conversationId} child={child} />)+ )}+ <View className="flex-row justify-end">+ <Button+ label="Refresh"+ tone="secondary"+ disabled={query.isPending}+ onPress={query.refresh}+ />+ </View>+ </ScrollView>+ </Sheet>+ );+}++function NativeChild(props: { readonly child: OrchestrationV2NativeChildWork }) {+ const { child } = props;+ return (+ <View className="gap-2">+ <Text className="font-t3-bold text-sm text-foreground">{child.role || "Subagent"}</Text>+ <Text selectable className="font-sans text-sm text-foreground-secondary">+ {child.prompt}+ </Text>+ {child.truncated ? (+ <Text className="font-sans text-xs text-foreground-secondary">+ Earlier steps are not shown.+ </Text>+ ) : null}+ {child.steps === null ? (+ <Text className="font-sans text-xs text-foreground-secondary">No transcript yet.</Text>+ ) : (+ <View className="gap-2 border-l border-border ps-3">+ {child.steps.map((step) => (+ <View key={step.index} className="gap-1">+ <Text className="font-t3-bold text-xs text-foreground-secondary">+ {stepLabel(step.type)}+ {step.status !== null && step.status !== "DONE"+ ? ` · ${stepLabel(step.status)}`+ : ""}+ </Text>+ {step.toolCalls.length === 0 ? null : (+ <Text selectable className="font-mono text-xs text-foreground">+ {step.toolCalls.map((call) => `${call.name} ${call.input}`).join("\n")}+ </Text>+ )}+ {step.text === null ? null : (+ <Text selectable className="font-mono text-xs text-foreground">+ {step.text}+ </Text>+ )}+ </View>+ ))}+ </View>+ )}+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/ProviderSubagentBar.tsx b/apps/mobile/src/features/threads/ProviderSubagentBar.tsxindex 16d16c219e0..ce026e85294 100644--- a/apps/mobile/src/features/threads/ProviderSubagentBar.tsx+++ b/apps/mobile/src/features/threads/ProviderSubagentBar.tsx@@ -2,12 +2,14 @@ import {formatProviderSubagentStatus,type ProviderSubagentStatus,} from "@t3tools/client-runtime/state/thread-execution";-import { isOrchestrationV2WorkActive } from "@t3tools/contracts";+import { isOrchestrationV2WorkActive, type EnvironmentId, type ThreadId } from "@t3tools/contracts";+import { useState } from "react";import { View } from "react-native";import { AppText as Text } from "../../components/ui/AppText";import { ProviderIcon } from "../../components/ProviderIcon";import { Button } from "../../components/ui/Button";+import { NativeChildWorkSheet } from "./NativeChildWorkSheet";import { useVisibleSecondClock } from "./use-visible-second-clock";export function ProviderSubagentBar(props: {@@ -16,7 +18,10 @@ export function ProviderSubagentBar(props: {readonly effortLabel: string | null;readonly status: ProviderSubagentStatus | null;readonly onOpenParent: (() => void) | null;+ /** Set for providers whose children T3 reads on demand instead of streaming. */+ readonly inspect: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null;}) {+ const [inspecting, setInspecting] = useState(false);const live = props.status !== null && isOrchestrationV2WorkActive(props.status.status);const nowMs = useVisibleSecondClock(live);const statusLabel = formatProviderSubagentStatus(props.status, nowMs);@@ -59,9 +64,15 @@ export function ProviderSubagentBar(props: {{statusLabel} · Runs on its own</Text></View>+ {props.inspect ? (+ <Button label="Work" tone="secondary" onPress={() => setInspecting(true)} />+ ) : null}{props.onOpenParent ? (<Button label="Open parent" tone="secondary" onPress={props.onOpenParent} />) : null}+ {props.inspect && inspecting ? (+ <NativeChildWorkSheet {...props.inspect} onClose={() => setInspecting(false)} />+ ) : null}</View>);}diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 0cc08fdb3fe..afceb0b78b6 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -1722,6 +1722,14 @@ function ThreadDetailBody(reportedModelSelection,)}status={props.providerSubagentStatus ?? null}+ inspect={+ providerSubagentProvider?.driver === "antigravity"+ ? {+ environmentId: props.environmentId,+ threadId: props.selectedThread.id,+ }+ : null+ }onOpenParent={props.selectedThread.lineage.parentThreadId === null? nulldiff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.tsindex ae07db783c9..de3fdb1a314 100644--- a/apps/server/scripts/acp-mock-agent.ts+++ b/apps/server/scripts/acp-mock-agent.ts@@ -512,7 +512,7 @@ const program = Effect.gen(function* () {parameterizedModelPicker = request.capabilities?._meta?.parameterizedModelPicker === true;return {protocolVersion: 2,- info: { name: "t3-acp-mock-agent", version: "0.0.0" },+ info: { name: "t3-acp-mock-agent", version: process.env.T3_ACP_AGENT_VERSION ?? "0.0.0" },...(omitInitializeModelState ? {} : { _meta: { modelState: modelState() } }),capabilities: {session: {diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 6049121b41a..f040dbc4594 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -41,6 +41,7 @@ export const RPC_REQUIRED_SCOPES = {...CLIENT_GUARDED_RPC_SCOPES,[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,+ [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 1e3388e4136..7bb8bf8a34c 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -13,6 +13,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];const RPC_AGGREGATES = {[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2",[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration",+ [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.forceStopThread]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration",diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.tsindex bb84c1a2c74..07c3bd73163 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts@@ -82,6 +82,7 @@ import {acpPostSettleContinuationOfferEvidence,acpPostSettleWakeEvidence,acpToolCallDiffPatch,+ acpToolCallSnippetEdit,makeAcpAdapterV2,type AcpAdapterV2ExtensionContext,type AcpAdapterV2Flavor,@@ -138,6 +139,32 @@ describe("acpPerTurnPromptUsage", () => {reasoningTokens: 3,},);+ // Antigravity 1.4.5: its harness reports prompt tokens without the 24 cached ones.+ assert.deepEqual(+ acpPerTurnPromptUsage(+ {+ inputTokens: 42,+ outputTokens: 3,+ totalTokens: 54,+ cachedReadTokens: 24,+ cachedWriteTokens: 0,+ thoughtTokens: 9,+ },+ false,+ "completed",+ true,+ ),+ {+ usageScope: "main_agent",+ usageStatus: "complete",+ hasSubagents: false,+ inputTokens: 66,+ outputTokens: 12,+ cachedInputTokens: 24,+ cacheCreationTokens: 0,+ reasoningTokens: 9,+ },+ );});it("clamps subsets that exceed their parents and drops unset counters", () => {@@ -231,6 +258,45 @@ describe("acpPerTurnPromptUsage", () => {});describe("acpToolCallDiffPatch", () => {+ it("keeps an unplaced snippet as recorded text instead of numbering it from line 1", () => {+ const content = [+ {+ type: "diff",+ path: "/repo/a.ts",+ oldText: "const target = 10;",+ newText: "const target = 100;",+ patch: { format: "snippet", text: "@@ -1,1 +1,1 @@ snippet, line unknown\n" },+ },+ ];+ assert.isUndefined(acpToolCallDiffPatch(content));+ // An omitted preview is not re-diffed from the bare snippets either.+ assert.isUndefined(acpToolCallDiffPatch([{ ...content[0], patch: { format: "omitted" } }]));+ // A status block beside the snippet must not hide it.+ for (const blocks of [+ content,+ [{ type: "content", content: { type: "text", text: "Edited." } }, ...content],+ ]) {+ assert.isUndefined(acpToolCallDiffPatch(blocks));+ assert.deepEqual(acpToolCallSnippetEdit(blocks), {+ oldStr: "const target = 10;",+ newStr: "const target = 100;",+ });+ }+ // Beside another diff, the snippet is neither a patch nor a placed edit.+ const twoDiffs = [+ ...content,+ {+ type: "diff",+ path: "/repo/b.ts",+ oldText: "b\n",+ newText: "B\n",+ patch: { text: "@@ -1 +1 @@\n-b\n+B\n" },+ },+ ];+ assert.isUndefined(acpToolCallDiffPatch(twoDiffs));+ assert.isUndefined(acpToolCallSnippetEdit(twoDiffs));+ });+it("builds per-file patches from ACP hunks and recorded old/new text", () => {for (const operation of ["add", "delete"]) {const text = operation === "add" ? "@@ -0,0 +1 @@\n+content\n" : "@@ -1 +0,0 @@\n-content\n";@@ -661,6 +727,97 @@ describe("AcpAdapterV2", () => {assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt");}).pipe(Effect.provide(layerTest), Effect.scoped),);+ it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome");+ const threadId = ThreadId.make("thread-acp-prompt-outcome");+ const quota = {+ class: "usage_limit",+ message: "Quota reached.",+ code: "RESOURCE_EXHAUSTED",+ retryable: true,+ resetAt: "2030-01-01T00:00:00.000Z",+ } as const;+ // The runtime ordinal of each prompt, and the session each check watched.+ const promptRuntimes: Array<number> = [];+ const watchedSessions: Array<string> = [];+ const adapter = yield* makeAcpAdapterV2({+ instanceId,+ selfInvocation: yield* resolveSelfInvocation(),+ flavor: {+ driver: ACP_TEST_DRIVER,+ capabilities: AcpProviderCapabilitiesV2,+ watchPromptOutcome: (sessionId) =>+ Effect.sync(() => {+ watchedSessions.push(sessionId);+ const failed = watchedSessions.length === 1;+ return () => Effect.succeed(failed ? quota : undefined);+ }),+ makeRuntime: makeMockRuntime({+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,+ mockAgentPath: yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ ),+ wrapRuntime: (runtime, runtimeOrdinal) => ({+ ...runtime,+ prompt: () =>+ Effect.sync(() => {+ promptRuntimes.push(runtimeOrdinal);+ return { stopReason: "end_turn" as const };+ }),+ }),+ }),+ },+ });+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const modelSelection = { instanceId, model: "default" } as const;+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ const runTurn = (ordinal: number) =>+ Effect.gen(function* () {+ yield* runtime.startTurn(+ makeTurnInput({+ threadId,+ providerThread,+ instanceId,+ runtimePolicy,+ now: yield* DateTime.now,+ ordinal,+ }),+ );+ const events = yield* runtime.events.pipe(+ Stream.takeUntil((event) => event.type === "turn.terminal"),+ Stream.runCollect,+ );+ return events.at(-1);+ });++ const failed = yield* runTurn(1);+ if (failed?.type !== "turn.terminal" || failed.status !== "failed") {+ return assert.fail("expected a failed terminal");+ }+ assert.deepEqual(failed.failure, quota);+ const completed = yield* runTurn(2);+ assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed");+ assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime");+ assert.equal(watchedSessions.length, 2);+ assert.equal(watchedSessions[0], watchedSessions[1]);+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );it.live("retains returned usage when Stop finalizes before the prompt callback", () =>Effect.gen(function* () {const path = yield* Path.Path;diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.tsindex 01936cb122a..63286a4bcea 100644--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts@@ -31,7 +31,6 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSimport * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";-import { resolveAttachmentPath } from "../../attachmentStore.ts";import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";@@ -78,6 +77,21 @@ describe("AntigravityAdapterV2 flavor", () => {assert.equal(batch?.prompt, "Started two agents.");assert.isNull(batch?.result);assert.isTrue(flavor.subagentsIdleOnTurnCompletion);++ // Permission prompts carry the launch; later updates for the same call do not.+ const launch = flavor.extractSubagentUpdate?.({+ toolCallId: "35bea692fa95447fbdae6333fec5515f",+ title: "Run invoke_subagent?",+ kind: "other",+ status: "pending",+ data: {+ rawInput: {+ Subagents: [{ TypeName: "research", Role: "Readme Reader", Prompt: "Read README.md" }],+ },+ },+ });+ assert.equal(launch?.title, "Readme Reader");+ assert.equal(launch?.prompt, "Read README.md");});it("routes interaction_* permission requests to the question card", () => {@@ -395,10 +409,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {mimeType: "application/pdf",sizeBytes: 9,});- const documentPath = resolveAttachmentPath({- attachmentsDir: host.paths.attachmentsDir,- attachment: document,- })!;+ const documentPath = host.resolveAttachmentPath(document)!;yield* fileSystem.writeFileString(documentPath, "%PDF-1.7");let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test");@@ -526,10 +537,11 @@ describe("AntigravityAdapterV2 workspace changes", () => {uri: (yield* path.toFileUrl(documentPath)).href,name: "diagram.pdf",mimeType: "application/pdf",+ size: 8,},],);- assert.include(JSON.stringify(sent.prompt), host.resolveAttachmentPath(document)!);+ assert.include(JSON.stringify(sent.prompt), documentPath);if (readTextFile === undefined) {return yield* Effect.die("Antigravity sessions must serve client file requests");}@@ -1104,3 +1116,135 @@ describe("AntigravityAdapterV2 runtime mode ceiling", () => {}),);});++describe("AntigravityAdapterV2 session system prompt", () => {+ it.effect.each(["1.4.5", "1.4.1"])(+ "carries PR linking once in the %s session setup or once per turn",+ (agentVersion) =>+ Effect.gen(function* () {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const crypto = yield* Crypto.Crypto;+ const mockAgentPath = yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ );+ const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-log-" });+ const requestLog = path.join(logs, "requests.ndjson");+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];+ const promptReceived = yield* Deferred.make<Parameters<RuntimeService["prompt"]>[0]>();+ const instanceId = ProviderInstanceId.make("antigravity-system-prompt-test");+ const adapter = yield* makeAntigravityAdapterV2({+ instanceId,+ selfInvocation: yield* resolveSelfInvocation(),+ makeRuntime: (input) =>+ makeAntigravityAcpRuntime({+ ...input,+ childProcessSpawner,+ spawn: {+ command: process.execPath,+ args: [mockAgentPath],+ cwd: input.cwd,+ env: {+ T3_ACP_ANTIGRAVITY: "1",+ T3_ACP_AGENT_VERSION: agentVersion,+ T3_ACP_REQUEST_LOG_PATH: requestLog,+ T3_ACP_HANG_PROMPT_FOREVER: "1",+ },+ },+ }).pipe(+ Effect.provideService(Crypto.Crypto, crypto),+ Effect.map((runtime): RuntimeService => ({+ ...runtime,+ prompt: (request) =>+ Deferred.succeed(promptReceived, request).pipe(+ Effect.andThen(runtime.prompt(request)),+ ),+ })),+ ),+ withProcess: (_stop, task) => task,+ // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.+ defaultModel: Effect.succeed(undefined),+ });+ const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-sp-" });+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: workspace,+ });+ const threadId = ThreadId.make("thread-antigravity-system-prompt");+ const modelSelection = { instanceId, model: "gemini-test-low" } as const;+ const session = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("provider-session-antigravity-system-prompt"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* session.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ const now = yield* DateTime.now;+ yield* session+ .startTurn({+ appThread: {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId: ProjectId.make("project-antigravity-system-prompt"),+ title: "Antigravity system prompt",+ providerInstanceId: instanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: providerThread.id,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ threadId,+ runId: RunId.make("run-antigravity-system-prompt"),+ runOrdinal: 1,+ providerTurnOrdinal: 1,+ attemptId: RunAttemptId.make("attempt-antigravity-system-prompt"),+ rootNodeId: NodeId.make("node-antigravity-system-prompt"),+ providerThread,+ message: {+ createdBy: "user",+ creationSource: "web",+ messageId: MessageId.make("message-antigravity-system-prompt"),+ text: "open a PR",+ attachments: [],+ },+ modelSelection,+ runtimePolicy,+ })+ .pipe(Effect.forkScoped);+ const sent = JSON.stringify((yield* Deferred.await(promptReceived)).prompt);+ const sessionNew = (yield* fileSystem.readFileString(requestLog))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as { method?: string; params?: { _meta?: unknown } })+ .find((request) => request.method === "session/new");+ const append = JSON.stringify(sessionNew?.params?._meta ?? null);+ // Identity stays per turn either way.+ assert.include(sent, "through the Antigravity harness, as gemini-test-low");+ if (agentVersion === "1.4.5") {+ assert.include(append, "pull_request_linking");+ assert.notInclude(sent, "<pull_request_linking>");+ } else {+ assert.notInclude(append, "systemPrompt");+ assert.include(sent, "<pull_request_linking>");+ }+ }).pipe(Effect.provide(layerSession), Effect.scoped),+ );+});diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.tsindex 9d29ef248b2..8c5ccb48b14 100644--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts@@ -16,16 +16,24 @@ import * as Scope from "effect/Scope";import * as EffectAcpErrors from "effect-acp/errors";import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";+import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions";import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";import {+ antigravityAppendsSystemPrompt,antigravityPermissionMode,antigravityRuntimeModeForSessionMode,applyAntigravityAcpModelSelection,buildAntigravityPrompt,type AntigravityAcpRuntimeInput,} from "../../provider/acp/AntigravityAcpSupport.ts";+import {+ ANTIGRAVITY_SUBAGENT_BATCH_TITLE,+ antigravitySubagentLaunches,+ describeAntigravitySubagentLaunches,+} from "../../provider/acp/AntigravityChildWork.ts";import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts";+import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts";import {antigravityApprovalOptions,antigravitySubagentOutput,@@ -81,9 +89,14 @@ export interface AntigravityAdapterV2Options {readonly onSessionEvent?: AcpAdapterV2Flavor["onSessionEvent"];readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];+ /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */+ readonly profileDirectory?: string;}-/** Native subagent tools report no child session ids. */+/**+ * Native subagent tools report no child session ids, so children stay read-only.+ * Only permission prompts carry the launch; NativeChildWorkQuery matches their ids by this text.+ */const extractAntigravitySubagentUpdate: NonNullable<AcpAdapterV2Flavor["extractSubagentUpdate"]> = (toolCall,) => {@@ -92,14 +105,17 @@ const extractAntigravitySubagentUpdate: NonNullable<AcpAdapterV2Flavor["extractS}const status =toolCall.status === "failed" ? "failed" : toolCall.status === "pending" ? "pending" : "running";+ const launches = antigravitySubagentLaunches(toolCall.data.rawInput);+ const launch = launches === undefined ? undefined : describeAntigravitySubagentLaunches(launches);return {nativeTaskId: toolCall.toolCallId,prompt:+ launch?.prompt ??antigravitySubagentOutput(toolCall) ??toolCall.detail ??toolCall.title ??- "Antigravity subagent batch",- title: "Antigravity subagent batch",+ ANTIGRAVITY_SUBAGENT_BATCH_TITLE,+ title: launch?.title ?? ANTIGRAVITY_SUBAGENT_BATCH_TITLE,model: null,status,childSessionId: null,@@ -117,6 +133,7 @@ interface AntigravityFlavorServices {export function makeAntigravityAcpAdapterFlavor(options: AntigravityAdapterV2Options & AntigravityFlavorServices,): AcpAdapterV2Flavor {+ const { profileDirectory } = options;const antigravityClientFileRoots = (cwd: string | null) =>cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")(@@ -128,6 +145,7 @@ export function makeAntigravityAcpAdapterFlavor(options.makeRuntime({...input,clientFileReads: true,+ sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS,additionalDirectories: [options.host.paths.attachmentsDir],}),)@@ -190,13 +208,25 @@ export function makeAntigravityAcpAdapterFlavor(driver: ANTIGRAVITY_PROVIDER,runtimeHarness: "Antigravity",capabilities: AntigravityProviderCapabilitiesV2,+ // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio.+ mcpOverHttp: true,+ sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt,makeRuntime,- buildPrompt: ({ text, attachments, promptCapabilities }) =>+ buildPrompt: ({+ text,+ attachments,+ resolveAttachmentPath,+ promptCapabilities,+ agentVersion,+ currentModel,+ }) =>buildAntigravityPrompt({input: text,attachments,- attachmentsDir: options.host.paths.attachmentsDir,+ resolveAttachmentPath,promptCapabilities,+ agentVersion,+ currentModel,}).pipe(Effect.provideService(FileSystem.FileSystem, options.fileSystem),Effect.provideService(Path.Path, options.path),@@ -243,6 +273,15 @@ export function makeAntigravityAcpAdapterFlavor(// ACP 1.3.0 treats /compact as ordinary model input.supportsCompaction: false,requiresSignIn: isAntigravitySignInRequiredError,+ // 1.4.5 returns the root trajectory's Gemini usageMetadata delta; 1.4.1 returns none.+ reportsPerTurnPromptUsage: true,+ geminiPromptUsage: true,+ ...(profileDirectory === undefined+ ? {}+ : {+ watchPromptOutcome: (sessionId: string) =>+ watchAntigravityPromptOutcome(profileDirectory, sessionId),+ }),};}diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.tsnew file mode 100644index 00000000000..84ba0ff90c9--- /dev/null+++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts@@ -0,0 +1,117 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import * as ServerConfig from "../config.ts";+import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";+import {+ ANTIGRAVITY_SUBAGENT_BATCH_TITLE,+ describeAntigravitySubagentLaunches,+} from "../provider/acp/AntigravityChildWork.ts";+import {+ CHILD,+ invokeStep,+ LAUNCH,+ makeProfile,+ ROOT,+} from "../provider/acp/AntigravityChildWork.testkit.ts";+import * as NativeChildWorkQuery from "./NativeChildWorkQuery.ts";+import * as ThreadManagement from "./ThreadManagementService.ts";++const instanceId = ProviderInstanceId.make("antigravity");+const childThreadId = ThreadId.make("thread-child");+const launch = describeAntigravitySubagentLaunches([LAUNCH]);++// A permission-prompt batch in session ROOT, plus an older batch with no launch text in `olderRun`.+const records = (olderRun: string) => ({+ thread: {+ id: childThreadId,+ creationSource: "provider",+ lineage: { parentThreadId: "thread-parent", relationshipToParent: "subagent" },+ forkedFrom: { type: "node", nodeId: "subagent-new" },+ },+ subagents: [+ {+ id: "subagent-new",+ childThreadId,+ driver: "antigravity",+ origin: "provider_native",+ providerInstanceId: instanceId,+ runId: "run-root",+ nativeTaskRef: { nativeId: "35bea692fa95447fbdae6333fec5515f" },+ ...launch,+ },+ {+ id: "subagent-old",+ childThreadId: "thread-old",+ driver: "antigravity",+ origin: "provider_native",+ providerInstanceId: instanceId,+ runId: olderRun,+ nativeTaskRef: { nativeId: "0ld" },+ title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE,+ prompt: "Running",+ },+ ],+ runs: [+ { id: "run-root", providerThreadId: "provider-root" },+ { id: "run-root-earlier", providerThreadId: "provider-root" },+ { id: "run-other", providerThreadId: "provider-other" },+ ],+ providerThreads: [+ { id: "provider-root", providerInstanceId: instanceId, nativeThreadRef: { nativeId: ROOT } },+ {+ id: "provider-other",+ providerInstanceId: instanceId,+ nativeThreadRef: { nativeId: "00000000-0000-4000-8000-000000000000" },+ },+ ],+});++const readChildren = (olderRun: string) =>+ Effect.gen(function* () {+ const query = yield* NativeChildWorkQuery.NativeChildWorkQuery;+ return (yield* query.getNativeChildWork({ threadId: childThreadId })).children;+ }).pipe(+ Effect.provide(+ NativeChildWorkQuery.layer.pipe(+ Layer.provide(+ Layer.mock(ThreadManagement.ThreadManagementService)({+ getThreadRecords: () => Effect.succeed(records(olderRun) as never),+ }),+ ),+ ),+ ),+ );++it.layer(+ Layer.mergeAll(+ NodeServices.layer,+ ServerConfig.layerTest(process.cwd(), { prefix: "native-child-work-" }).pipe(+ Layer.provide(NodeServices.layer),+ ),+ ),+)("NativeChildWorkQuery", (it) => {+ it.effect("weighs only batches from the same agent session", () =>+ Effect.gen(function* () {+ const { stateDir } = yield* ServerConfig.ServerConfig;+ const { profile } = yield* resolveAntigravityInstanceDirectories(stateDir, instanceId);+ yield* makeProfile({+ profile,+ steps: (logUri) => [+ [+ 2,+ 127,+ invokeStep({ callId: "x", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),+ ],+ ],+ });+ const fromOtherSession = yield* readChildren("run-other");+ expect(fromOtherSession.map((child) => child.conversationId)).toEqual([CHILD]);+ // An earlier run in the same session may own the only record.+ expect(yield* readChildren("run-root-earlier")).toEqual([]);+ }),+ );+});diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.tsnew file mode 100644index 00000000000..c3493f441c0--- /dev/null+++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts@@ -0,0 +1,116 @@+import {+ isProviderNativeSubagentThread,+ OrchestrationV2GetNativeChildWorkError,+ type OrchestrationV2GetNativeChildWorkInput,+ type OrchestrationV2GetNativeChildWorkResult,+} from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Crypto from "effect/Crypto";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Path from "effect/Path";++import * as ServerConfig from "../config.ts";+import { readAntigravityChildWork } from "../provider/acp/AntigravityChildWork.ts";+import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";+import * as ThreadManagement from "./ThreadManagementService.ts";++/** Reads what a provider-native subagent's children did, on demand. Other providers stream real child sessions. */+export class NativeChildWorkQuery extends Context.Service<+ NativeChildWorkQuery,+ {+ readonly getNativeChildWork: (+ input: OrchestrationV2GetNativeChildWorkInput,+ ) => Effect.Effect<+ OrchestrationV2GetNativeChildWorkResult,+ OrchestrationV2GetNativeChildWorkError+ >;+ }+>()("t3/orchestration-v2/NativeChildWorkQuery") {}++const NO_CHILDREN: OrchestrationV2GetNativeChildWorkResult = { children: [] };++const make = Effect.gen(function* () {+ const threads = yield* ThreadManagement.ThreadManagementService;+ const { stateDir } = yield* ServerConfig.ServerConfig;+ const crypto = yield* Crypto.Crypto;+ const path = yield* Path.Path;++ const getNativeChildWork = Effect.fn("NativeChildWorkQuery.getNativeChildWork")(+ function* (input: OrchestrationV2GetNativeChildWorkInput) {+ const { thread } = yield* threads.getThreadRecords(input.threadId, []);+ const parentThreadId = thread.lineage.parentThreadId;+ if (+ !isProviderNativeSubagentThread(thread) ||+ parentThreadId === null ||+ thread.forkedFrom?.type !== "node"+ ) {+ return NO_CHILDREN;+ }+ const subagentId = thread.forkedFrom.nodeId;+ const { subagents } = yield* threads.getThreadRecords(parentThreadId, ["subagents"]);+ const subagent = subagents.find(+ (candidate) => candidate.id === subagentId && candidate.childThreadId === thread.id,+ );+ const nativeTaskId = subagent?.nativeTaskRef?.nativeId;+ if (+ subagent?.driver !== "antigravity" ||+ subagent.origin !== "provider_native" ||+ subagent.runId === null ||+ !nativeTaskId+ ) {+ return NO_CHILDREN;+ }+ const others = subagents.filter(+ (candidate) =>+ candidate.id !== subagent.id &&+ candidate.driver === "antigravity" &&+ candidate.origin === "provider_native" &&+ candidate.providerInstanceId === subagent.providerInstanceId,+ );+ const { runs, providerThreads } = yield* threads.getThreadRecords(+ parentThreadId,+ ["runs", "providerThreads"],+ { runIds: [subagent.runId, ...others.flatMap((other) => other.runId ?? [])] },+ );+ const providerThreadOf = (runId: string | null) => {+ const providerThreadId = runs.find((run) => run.id === runId)?.providerThreadId;+ return providerThreads.find((candidate) => candidate.id === providerThreadId);+ };+ const providerThread = providerThreadOf(subagent.runId);+ const rootSessionId = providerThread?.nativeThreadRef?.nativeId;+ if (!rootSessionId || providerThread?.providerInstanceId !== subagent.providerInstanceId) {+ return NO_CHILDREN;+ }+ const directories = yield* resolveAntigravityInstanceDirectories(+ stateDir,+ subagent.providerInstanceId,+ ).pipe(Effect.provideService(Crypto.Crypto, crypto), Effect.provideService(Path.Path, path));+ const children = yield* readAntigravityChildWork({+ profileDirectory: directories.profile,+ rootSessionId,+ nativeTaskId,+ launch: { title: subagent.title, prompt: subagent.prompt },+ // Only batches from the same agent session can share its records.+ siblings: others.flatMap((other) => {+ const id = other.nativeTaskRef?.nativeId;+ return id && providerThreadOf(other.runId)?.nativeThreadRef?.nativeId === rootSessionId+ ? [{ nativeTaskId: id, title: other.title, prompt: other.prompt }]+ : [];+ }),+ });+ return { children };+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new OrchestrationV2GetNativeChildWorkError({ threadId: input.threadId, cause }),+ ),+ ),+ );++ return NativeChildWorkQuery.of({ getNativeChildWork });+});++export const layer = Layer.effect(NativeChildWorkQuery, make);diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.tsindex 349a44a7005..f4c249625f3 100644--- a/apps/server/src/provider/AntigravityProvider.test.ts+++ b/apps/server/src/provider/AntigravityProvider.test.ts@@ -24,6 +24,7 @@ import * as ServerSettings from "../serverSettings.ts";import * as ProviderHostLive from "./ProviderHostLive.ts";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";+import type { ServerProvider } from "@t3tools/contracts";import {buildAntigravityModelsFromSession,makeAntigravityProvider,@@ -167,6 +168,11 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (Effect.andThen(initialUpdate),Effect.asVoid,);+ // Subscribe before the trigger; yield the returned pull to await the publish.+ const nextPublish = (predicate: (snapshot: ServerProvider) => boolean) =>+ Stream.toPull(provider.snapshot.streamChanges.pipe(Stream.filter(predicate))).pipe(+ Effect.map((pull) => pull.pipe(Effect.map((snapshots) => snapshots[0]))),+ );return {provider,probe,@@ -176,6 +182,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (initialProbe,initialUpdate,initialize,+ nextPublish,};});@@ -687,15 +694,29 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {};const usage = yield* Ref.make(limits);const harness = yield* makeHarness({ probeUsage: Ref.get(usage) });+ const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);yield* harness.initialize;- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);- yield* Ref.set(harness.probe, Effect.succeed(initializeResult));+ expect((yield* published)?.usageLimits).toEqual(limits);+ // The second health check is the one the failed background read triggers.+ const checks = yield* Ref.make(0);+ const failedReadApplied = yield* Deferred.make<void>();+ yield* Ref.set(+ harness.probe,+ Ref.updateAndGet(checks, (count) => count + 1).pipe(+ Effect.tap((count) =>+ count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void,+ ),+ Effect.as(initializeResult),+ ),+ );yield* Ref.set(usage, {checkedAt: "2026-10-09T12:01:00.000Z",windows: [],unavailable: { reason: "probeFailed" },});- expect((yield* harness.provider.snapshot.refresh).usageLimits).toEqual(limits);+ yield* harness.provider.snapshot.refresh;+ yield* Deferred.await(failedReadApplied);+ expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);yield* harness.provider.onSignedOut;expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();yield* Ref.set(usage, {@@ -703,7 +724,11 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {windows: [],unavailable: { reason: "unsupported" },});- expect((yield* harness.provider.snapshot.refresh).usageLimits?.windows).toEqual([]);+ const unsupported = yield* harness.nextPublish(+ (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",+ );+ yield* harness.provider.snapshot.refresh;+ expect((yield* unsupported)?.usageLimits?.windows).toEqual([]);}),),);@@ -737,4 +762,74 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {}),),);++ it.effect("reports ready and starts sessions while one shared quota read is pending", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const reads = yield* Ref.make(0);+ const readStarted = yield* Deferred.make<void>();+ const readResult = yield* Deferred.make<ServerProviderUsageLimits>();+ const harness = yield* makeHarness({+ probeUsage: Ref.update(reads, (count) => count + 1).pipe(+ Effect.andThen(Deferred.succeed(readStarted, undefined)),+ Effect.andThen(Deferred.await(readResult)),+ ),+ });+ const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);+ yield* harness.initialize;+ yield* Deferred.await(readStarted);+ yield* harness.provider.onSessionStarted(started, "/workspace");+ yield* harness.provider.onSessionStarted(started, "/other");+ const ready = yield* harness.provider.snapshot.getSnapshot;+ expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } });+ expect(ready.usageLimits).toBeUndefined();+ expect(yield* Ref.get(reads)).toBe(1);+ const limits = {+ checkedAt: "2026-10-09T12:00:00.000Z",+ windows: [+ { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 },+ ],+ } satisfies ServerProviderUsageLimits;+ yield* Deferred.succeed(readResult, limits);+ expect((yield* published)?.usageLimits).toEqual(limits);+ }),+ ),+ );++ it.effect("a quota read for the previous account is dropped after a new sign-in", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const oldReadStarted = yield* Deferred.make<void>();+ const newLimits = {+ checkedAt: "2026-10-09T12:01:00.000Z",+ windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }],+ } satisfies ServerProviderUsageLimits;+ const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(+ Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)),+ );+ const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });+ const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);+ yield* harness.initialize;+ yield* Deferred.await(oldReadStarted);+ yield* Ref.set(usage, Effect.succeed(newLimits));+ yield* harness.provider.onSignedIn;+ yield* harness.provider.onSessionStarted(started);+ expect((yield* published)?.usageLimits).toEqual(newLimits);+ // Switching again must not republish the previous account's limits, even if the read fails.+ const failed = {+ checkedAt: "2026-10-09T12:02:00.000Z",+ windows: [],+ unavailable: { reason: "probeFailed" },+ } satisfies ServerProviderUsageLimits;+ yield* Ref.set(usage, Effect.succeed(failed));+ const republished = yield* harness.nextPublish(+ (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",+ );+ yield* harness.provider.onSignedIn;+ expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();+ yield* harness.provider.onSessionStarted(started);+ expect((yield* republished)?.usageLimits).toEqual(failed);+ }),+ ),+ );});diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.tsindex 6dcde50c532..ff8805f43b3 100644--- a/apps/server/src/provider/AntigravityProvider.ts+++ b/apps/server/src/provider/AntigravityProvider.ts@@ -9,8 +9,11 @@ import {type ServerProviderUsageLimits,} from "@t3tools/contracts";import { createModelCapabilities } from "@t3tools/shared/model";+import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";+import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";+import * as FiberHandle from "effect/FiberHandle";import * as Option from "effect/Option";import * as Predicate from "effect/Predicate";import * as Result from "effect/Result";@@ -41,6 +44,10 @@ const HEALTH_CHECK_TIMEOUT = "90 seconds";const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity.";const AUTH_UNCHECKED_MESSAGE ="Antigravity is installed. Google account access is not checked yet.";+// Set while a finished quota read republishes, so that health check does not read again.+const PublishingUsage = Context.Reference<boolean>("t3/provider/AntigravityPublishingUsage", {+ defaultValue: () => false,+});type SessionSetupResult = Pick<AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],@@ -215,6 +222,47 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(funcEffect.flatMap((state) => options.stampIdentity(state.draft)),);+ // The quota read can take 30 seconds, so it never blocks readiness or a session start.+ // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands.+ const usageRead = yield* FiberHandle.make();+ const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();+ const scope = yield* Effect.scope;+ const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {+ if (!options.probeUsage || (yield* PublishingUsage)) return;+ yield* FiberHandle.run(+ usageRead,+ options.probeUsage.pipe(+ Effect.flatMap((probed) =>+ SubscriptionRef.update(metadata, (state) => ({+ ...state,+ draft: {+ ...state.draft,+ usageLimits: resolveUsageLimitsAfterProbe({+ published: state.draft.usageLimits,+ probed,+ }),+ },+ })),+ ),+ // Enrichment cannot change published limits; a health check publishes them.+ Effect.andThen(+ Deferred.await(republish).pipe(+ Effect.flatten,+ Effect.provideService(PublishingUsage, true),+ Effect.ignoreCause({ log: true }),+ Effect.forkIn(scope),+ ),+ ),+ ),+ // Store the fiber before it runs, so a sign-out during the read can interrupt it.+ { onlyIfMissing: true, startImmediately: false },+ );+ });+ const resetUsage = Effect.gen(function* () {+ yield* FiberHandle.clear(usageRead);+ if (options.clearUsage) yield* options.clearUsage;+ });+const checkProvider = Effect.fn("checkAntigravityProvider")(function* () {if (!settings.enabled) return yield* getSnapshot;const before = yield* SubscriptionRef.get(metadata);@@ -239,8 +287,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func: `Antigravity did not respond to its local health check within ${HEALTH_CHECK_TIMEOUT}.`;const supportsTextGeneration =initialized !== undefined ? yield* options.supportsTextGeneration : false;- const usageLimits =- initialized !== undefined && options.probeUsage ? yield* options.probeUsage : undefined;const updatedAt = DateTime.formatIso(yield* DateTime.now);const next = yield* SubscriptionRef.updateAndGet(metadata, (state) => {if (state.authRevision !== before.authRevision) return state;@@ -262,12 +308,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(funcversion: version === "unknown" ? draft.version : version || draft.version,status: errorMessage ? "error" : authenticated ? "ready" : "warning",checkedAt: updatedAt,- usageLimits: missingInstallation- ? undefined- : resolveUsageLimitsAfterProbe({- published: draft.usageLimits,- probed: usageLimits ?? draft.usageLimits,- }),+ usageLimits: missingInstallation ? undefined : draft.usageLimits,...(missingInstallation? {models: [],@@ -287,6 +328,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func},} satisfies AntigravityProviderState;});+ if (initialized !== undefined) yield* refreshUsage();return yield* options.stampIdentity(next.draft);});@@ -310,6 +352,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func),),});+ yield* Deferred.succeed(republish, managed.refresh);const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (started: AcpSessionRuntime.AcpSessionRuntimeStartResult,@@ -319,10 +362,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(funcobserveThinkingLevels(started.sessionSetupResult.configOptions);const before = yield* SubscriptionRef.get(metadata);const supportsTextGeneration = yield* options.supportsTextGeneration;- const usageLimits =- options.probeUsage && (!before.draft.usageLimits || before.draft.usageLimits.unavailable)- ? yield* options.probeUsage- : before.draft.usageLimits;const updatedAt = DateTime.formatIso(yield* DateTime.now);yield* SubscriptionRef.update(metadata, (state) => {if (@@ -347,10 +386,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(funclabel: options.auth?.label ?? "Google account",},checkedAt: updatedAt,- usageLimits: resolveUsageLimitsAfterProbe({- published: draft.usageLimits,- probed: usageLimits ?? draft.usageLimits,- }),models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels),supportsTextGeneration,...(cwd@@ -369,6 +404,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func},} satisfies AntigravityProviderState;});+ if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage();});const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (@@ -418,7 +454,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func});const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {- if (options.clearUsage) yield* options.clearUsage;+ yield* resetUsage;if (!settings.enabled) return;const updatedAt = DateTime.formatIso(yield* DateTime.now);yield* SubscriptionRef.update(@@ -481,6 +517,23 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(funconSessionStarted,onConfigOptionsUpdated,onAvailableCommands,+ // The new sign-in may be another account. Clear and republish its limits so a failed read+ // cannot fall back to them; the session start then reads the new account's limits.+ onSignedIn: resetUsage.pipe(+ Effect.andThen(+ SubscriptionRef.update(metadata, (state) => {+ const { usageLimits: _previousAccount, ...draft } = state.draft;+ return { ...state, draft };+ }),+ ),+ Effect.andThen(+ Deferred.await(republish).pipe(+ Effect.flatten,+ Effect.provideService(PublishingUsage, true),+ ),+ ),+ Effect.asVoid,+ ),onSignedOut: clearAccountMetadata(),onAuthRequired: clearAccountMetadata(),snapshotForCwd,diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.tsindex e2a98835586..0131346e8d2 100644--- a/apps/server/src/provider/Drivers/AntigravityDriver.ts+++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts@@ -244,6 +244,7 @@ export const AntigravityDriver: ProviderDriver<);const runtime = yield* makeAntigravityAcpRuntime({...input,+ runtimeVersion: executable.version,authMethod: auth.authMethod,childProcessSpawner: spawner,spawn: buildAntigravityAcpSpawnInput({@@ -347,7 +348,11 @@ export const AntigravityDriver: ProviderDriver<const authFlow: AntigravityAuth = yield* makeAntigravityAuth({instanceId,makeRuntime: makeDisposableRuntime,- onAuthenticated: publishCatalog,+ // A new sign-in may be another account; drop any in-flight quota read first.+ onAuthenticated: (started, runtime) =>+ Effect.suspend(() => provider.onSignedIn).pipe(+ Effect.andThen(publishCatalog(started, runtime)),+ ),onSignedOut: Effect.suspend(() => provider.onSignedOut),usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),});@@ -429,6 +434,7 @@ export const AntigravityDriver: ProviderDriver<makeRuntime,withProcess: authFlow.withProcess,defaultModel,+ profileDirectory,onSessionStarted: provider.onSessionStarted,onSessionEvent: (event) => {if (event._tag === "ConfigOptionsUpdated") {diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.tsindex 9e2da61be2a..653fb1d9cbf 100644--- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts+++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts@@ -966,6 +966,16 @@ describe("AcpSessionRuntime", () => {"logout",]),);+ // Omitted roots clear an agent's stored ones, so every activation resends them.+ for (const method of ["session/new", "session/fork", "session/resume"]) {+ expect(+ requestEvents.find((event) => event.method === method && event.status === "started")+ ?.payload,+ ).toMatchObject({+ additionalDirectories: ["/tmp/t3-attachments"],+ _meta: { negotiated: "0.0.0" },+ });+ }}).pipe(Effect.provide(AcpSessionRuntime.layer({@@ -977,6 +987,10 @@ describe("AcpSessionRuntime", () => {T3_ACP_SESSION_LIFECYCLE: "1",},},+ additionalDirectories: ["/tmp/t3-attachments"],+ sessionMeta: (initializeResult) => ({+ negotiated: initializeResult.agentInfo?.version ?? "none",+ }),cwd: process.cwd(),clientInfo: { name: "t3-test", version: "0.0.0" },requestLogger: (event) =>diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.tsindex 8e0eed1371c..ea5efe230a2 100644--- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts+++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts@@ -5,6 +5,7 @@ import {PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,type ChatAttachment,} from "@t3tools/contracts";+import * as HostProcess from "@t3tools/shared/HostProcess";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";@@ -15,7 +16,9 @@ import type * as EffectAcpSchema from "effect-acp/compat";import { resolveAttachmentPath } from "../../attachmentStore.ts";import {applyAntigravityAcpModelSelection,+ antigravitySessionMeta,buildAntigravityPrompt,+ isQualifiedAntigravityRelease,} from "./AntigravityAcpSupport.ts";const modelConfig = {@@ -54,6 +57,39 @@ function makeModelRuntime(};}+describe("Antigravity release gates", () => {+ it.each([+ { version: "1.4.1", filter: false, native: false },+ { version: "1.4.2", filter: true, native: false },+ { version: "1.4.4", filter: true, native: false },+ { version: "1.4.5", filter: true, native: true },+ { version: "1.4.6", filter: false, native: false },+ { version: "1.3.0", filter: false, native: false },+ { version: undefined, filter: false, native: false },+ { version: "unknown", filter: false, native: false },+ ])(+ "$version: workflow filter $filter, native reads and system prompt $native",+ ({ version, filter, native }) => {+ const initialize = {+ protocolVersion: 1,+ ...(version === undefined ? {} : { agentInfo: { name: "antigravity-acp", version } }),+ };+ // Helpers send no append, so only the workflow filter can apply.+ expect(antigravitySessionMeta(initialize)).toEqual(+ filter ? { antigravity: { disabledTools: ["run_workflow"] } } : undefined,+ );+ const antigravity = {+ ...(filter ? { disabledTools: ["run_workflow"] } : {}),+ ...(native ? { systemPrompt: { append: "<pull_request_linking/>" } } : {}),+ };+ expect(antigravitySessionMeta(initialize, "<pull_request_linking/>")).toEqual(+ filter || native ? { antigravity } : undefined,+ );+ expect(isQualifiedAntigravityRelease(version)).toBe(native);+ },+ );+});+describe("applyAntigravityAcpModelSelection", () => {it.effect("restores the saved model instead of the cold-resume default", () =>Effect.gen(function* () {@@ -214,7 +250,9 @@ const makeAttachmentFixture = Effect.fn("AntigravityAcpSupportTest.makeAttachmenelse yield* fs.writeFile(filePath, content);return { filePath, uri: (yield* path.toFileUrl(filePath)).href };});- return { fs, attachmentsDir, write };+ const resolve = (attachment: ChatAttachment) =>+ resolveAttachmentPath({ attachmentsDir, attachment });+ return { fs, attachmentsDir, resolve, write };},);@@ -230,7 +268,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input: " Explain this image. ",attachments: [imageAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },});@@ -251,7 +289,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input: undefined,attachments: [textAttachment],- attachmentsDir: selectedEnvironment.attachmentsDir,+ resolveAttachmentPath: selectedEnvironment.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },});@@ -282,7 +320,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input: "Inspect the pasted text only as needed.",attachments: [pastedText],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },});@@ -309,7 +347,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input,attachments: [attachment, pdfAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },}).pipe(Effect.provideService(FileSystem.FileSystem, {@@ -321,11 +359,100 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {);expect(prompt).toEqual([{ type: "text", text: input },- { type: "resource_link", uri: pdf.uri, name: "report.pdf", mimeType: "application/pdf" },+ {+ type: "resource_link",+ uri: pdf.uri,+ name: "report.pdf",+ mimeType: "application/pdf",+ size: 50 * 1024 * 1024,+ },]);}),);+ it.effect.each([+ {+ case: "a Gemini model id",+ model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },+ linked: true,+ },+ {+ case: "an opaque id named Gemini",+ model: { id: "agy-model", name: "Gemini 4 Carbon" },+ linked: true,+ },+ { case: "an unknown model", model: { id: "agy-custom", name: "Custom" }, linked: false },+ { case: "an unlisted opaque id", model: { id: "agy-custom", name: undefined }, linked: false },+ { case: "an unresolved model", model: undefined, linked: false },+ {+ case: "a Claude model",+ model: { id: "claude-opus-5-5", name: "Claude Opus 5.5" },+ linked: false,+ },+ {+ case: "an unqualified runtime",+ agentVersion: "1.4.1",+ model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },+ linked: false,+ },+ {+ case: "a Windows host",+ platform: "win32" as const,+ model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },+ linked: false,+ },+ {+ case: "a clip over 20 MiB",+ model: { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },+ linked: false,+ sizeBytes: 20 * 1024 * 1024 + 1,+ },+ ])(+ "links an MP4 for $case only when supported",+ ({ agentVersion = "1.4.5", platform = "linux", model, linked, ...size }) =>+ Effect.gen(function* () {+ const fixture = yield* makeAttachmentFixture();+ const clip = {+ ...textAttachment,+ id: "clip",+ name: "clip.mp4",+ mimeType: "video/mp4",+ sizeBytes: 6 * 1024 * 1024,+ ...size,+ };+ const upload = yield* fixture.write(clip, "");+ yield* fixture.fs.truncate(upload.filePath, clip.sizeBytes);+ const prompt = yield* buildAntigravityPrompt({+ input: "What colors appear?",+ attachments: [clip],+ resolveAttachmentPath: fixture.resolve,+ promptCapabilities: { image: true, audio: true, embeddedContext: true },+ agentVersion,+ currentModel: model,+ }).pipe(+ Effect.provideService(HostProcess.Platform, platform),+ Effect.provideService(FileSystem.FileSystem, {+ ...fixture.fs,+ stream: () => Effect.die("Linked video is read by the agent").pipe(Stream.fromEffect),+ }),+ );+ expect(prompt).toEqual([+ { type: "text", text: "What colors appear?" },+ ...(linked+ ? [+ {+ type: "resource_link",+ uri: upload.uri,+ name: "clip.mp4",+ mimeType: "video/mp4",+ size: clip.sizeBytes,+ },+ ]+ : []),+ ]);+ }),+ );+it.effect.each([undefined, {}, { image: false, audio: false, embeddedContext: false }])("keeps attachments path-only when native prompt capabilities are absent: %s",(promptCapabilities) =>@@ -352,7 +479,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input,attachments: [imageAttachment, gifAttachment, pdfAttachment, textAttachment, audio],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities,}).pipe(Effect.provideService(FileSystem.FileSystem, {@@ -366,7 +493,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {yield* buildAntigravityPrompt({input: "Continue",attachments: [],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities,}),).toEqual([{ type: "text", text: "Continue" }]);@@ -387,7 +514,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input: "Transcribe this.",attachments: [audioAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },});@@ -409,7 +536,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const prompt = yield* buildAntigravityPrompt({input,attachments: [attachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities,}).pipe(Effect.provideService(FileSystem.FileSystem, {@@ -430,7 +557,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const error = yield* buildAntigravityPrompt({input: "Read this attachment.",attachments: [imageAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },}).pipe(Effect.flip);expect(error).toMatchObject({@@ -456,7 +583,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const input = {input: `Read ${first.filePath} and ${second.filePath}`,attachments: [pdfAttachment, secondAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },};const prompt = yield* buildAntigravityPrompt(input);@@ -467,12 +594,14 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {uri: first.uri,name: "report.pdf",mimeType: "application/pdf",+ size: (50 * 1024 * 1024) / 2,},{type: "resource_link",uri: second.uri,name: "second.pdf",mimeType: "application/pdf",+ size: (50 * 1024 * 1024) / 2,},]);@@ -484,6 +613,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {uri: first.uri,name: "report.pdf",mimeType: "application/pdf",+ size: (50 * 1024 * 1024) / 2,},]);}),@@ -498,7 +628,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const error = yield* buildAntigravityPrompt({input: "Inspect both attachments.",attachments: [pdfAttachment, imageAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },}).pipe(Effect.flip);expect(error).toMatchObject({@@ -517,7 +647,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const error = yield* buildAntigravityPrompt({input: undefined,attachments: [pdfAttachment, textAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },}).pipe(Effect.provideService(FileSystem.FileSystem, {@@ -551,7 +681,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const error = yield* buildAntigravityPrompt({input: undefined,attachments: [textAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },}).pipe(Effect.flip);@@ -569,7 +699,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {const error = yield* buildAntigravityPrompt({input: "Read this image.",attachments: [imageAttachment],- attachmentsDir: fixture.attachmentsDir,+ resolveAttachmentPath: fixture.resolve,promptCapabilities: { image: true, audio: true, embeddedContext: true },}).pipe(Effect.flip);diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.tsindex ed8fff03795..a2be5ccaa3f 100644--- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts+++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts@@ -6,6 +6,7 @@ import {type ProviderSendTurnInput,type RuntimeMode,} from "@t3tools/contracts";+import * as HostProcess from "@t3tools/shared/HostProcess";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -17,7 +18,6 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";import * as EffectAcpErrors from "effect-acp/errors";import type * as EffectAcpSchema from "effect-acp/compat";-import { resolveAttachmentPath } from "../../attachmentStore.ts";import {makeAntigravityStderrHandler,makeAntigravityStdoutTransform,@@ -34,15 +34,78 @@ export interface AntigravityAcpRuntimeInput extends Omit<| "clientInfo"| "onStderr"| "resumeMethod"+ | "sessionMeta"| "transformSessionUpdate"| "transformStdout"> {readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;+ /** Serve `fs/read_text_file` for runtimes whose native reader is not qualified. */readonly clientFileReads?: boolean;+ /** The installed version, known before `initialize`; it picks the file reader. */+ readonly runtimeVersion?: string | null;+ /** Conversational sessions only; helpers and probes leave the system prompt untouched. */+ readonly sessionSystemPromptAppend?: string;readonly authMethod?: AntigravityAuthMethod;}+function parseAntigravityVersion(version: string | null | undefined) {+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version?.trim() ?? "");+ return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];+}++function compareVersions(left: ReadonlyArray<number>, right: ReadonlyArray<number>) {+ for (let index = 0; index < 3; index++) {+ const difference = (left[index] ?? 0) - (right[index] ?? 0);+ if (difference !== 0) return difference;+ }+ return 0;+}++/**+ * 1.4.2 through 1.4.5 create or overwrite skills/system/run-workflow/SKILL.md in the workspace+ * unless `run_workflow` is disabled. Older builds offer the tool and leave the file alone.+ */+function antigravityWritesRunWorkflowSkill(version: string | null | undefined): boolean {+ const parsed = parseAntigravityVersion(version);+ return (+ parsed !== undefined &&+ compareVersions(parsed, [1, 4, 2]) >= 0 &&+ compareVersions(parsed, [1, 4, 5]) <= 0+ );+}++/**+ * Releases T3 qualified for native range reads and linked video. On 1.4.5 the client-read path+ * sends a whole file to serve one line, and the native reader keeps diff edits.+ */+export function isQualifiedAntigravityRelease(version: string | null | undefined): boolean {+ return version?.trim() === "1.4.5";+}++/**+ * 1.4.5 appends `systemPrompt.append` to its system instructions on new, load and resume, and+ * keeps none of it between processes, so every activation sends it again.+ */+export const antigravityAppendsSystemPrompt = (+ initializeResult: EffectAcpSchema.InitializeResponse,+) => isQualifiedAntigravityRelease(initializeResult.agentInfo?.version);++export function antigravitySessionMeta(+ initializeResult: EffectAcpSchema.InitializeResponse,+ systemPromptAppend?: string,+): EffectAcpSchema.NewSessionRequest["_meta"] | undefined {+ const antigravity = {+ ...(antigravityWritesRunWorkflowSkill(initializeResult.agentInfo?.version)+ ? { disabledTools: ["run_workflow"] }+ : {}),+ ...(systemPromptAppend !== undefined && antigravityAppendsSystemPrompt(initializeResult)+ ? { systemPrompt: { append: systemPromptAppend } }+ : {}),+ };+ return Object.keys(antigravity).length === 0 ? undefined : { antigravity };+}+export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(function* (input: AntigravityAcpRuntimeInput,): Effect.fn.Return<@@ -59,9 +122,15 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(cancelBehavior: "wait-for-prompt",// The agent offers non-Gemini models only to allowlisted clients such as Zed.clientInfo: { name: "zed", version: "0.0.0" },+ sessionMeta: (initializeResult) =>+ antigravitySessionMeta(initializeResult, input.sessionSystemPromptAppend),clientCapabilities: {// Advertising writes swaps the agent's diff edits for whole-file client_edit_file.- fs: { readTextFile: input.clientFileReads === true, writeTextFile: false },+ fs: {+ readTextFile:+ input.clientFileReads === true && !isQualifiedAntigravityRelease(input.runtimeVersion),+ writeTextFile: false,+ },terminal: false,},transformStdout: makeAntigravityStdoutTransform(@@ -212,6 +281,18 @@ const AUDIO_MIME_TYPES = new Set(["audio/webm",]);const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024;+// The agent inlines linked video bytes into one model request, so keep it under the inline limit.+const ANTIGRAVITY_MAX_VIDEO_ATTACHMENT_BYTES = 20 * 1024 * 1024;++/**+ * Only Gemini takes video. The evidence is the session's resolved model, so an account default+ * counts once the agent reports it; opaque ids such as `agy-model` need a Gemini display name.+ */+function antigravityModelAcceptsVideo(+ model: { readonly id: string; readonly name: string | undefined } | undefined,+): boolean {+ return model !== undefined && (/^gemini-/i.test(model.id) || /^gemini\b/i.test(model.name ?? ""));+}const TEXT_MIME_TYPES = new Set(["application/json","application/ld+json",@@ -277,8 +358,13 @@ const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {readonly input: ProviderSendTurnInput["input"];readonly attachments: ProviderSendTurnInput["attachments"];- readonly attachmentsDir: string;+ readonly resolveAttachmentPath: (+ attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number],+ ) => string | null;readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];+ /** Linked video needs a runtime whose `resource_link` handling is qualified and a Gemini model. */+ readonly agentVersion?: string | undefined;+ readonly currentModel?: { readonly id: string; readonly name: string | undefined } | undefined;}): Effect.fn.Return<ReadonlyArray<EffectAcpSchema.ContentBlock>,EffectAcpErrors.AcpError,@@ -286,6 +372,8 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi> {const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;+ // The agent runs on this host.+ const platform = yield* HostProcess.Platform;const blocks: Array<EffectAcpSchema.ContentBlock> = [];const text = input.input?.trim();if (text) blocks.push({ type: "text", text });@@ -301,6 +389,14 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functiconst image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);const pdf = attachment.type === "file" && mimeType === "application/pdf";+ const video =+ attachment.type === "file" &&+ mimeType === "video/mp4" &&+ isQualifiedAntigravityRelease(input.agentVersion) &&+ // The agent turns a file URI into a path with unquote(urlparse(uri).path), which drops+ // Windows drives and UNC hosts. Keep the saved path there until Google fixes it.+ platform !== "win32" &&+ antigravityModelAcceptsVideo(input.currentModel);const textFile =attachment.type === "file" &&(mimeType.startsWith("text/") ||@@ -314,11 +410,8 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi? input.promptCapabilities?.audio !== true: pdf || textFile? input.promptCapabilities?.embeddedContext !== true- : true)));- const attachmentPath = resolveAttachmentPath({- attachmentsDir: input.attachmentsDir,- attachment,- });+ : !video)));+ const attachmentPath = input.resolveAttachmentPath(attachment);if (!attachmentPath) {return yield* EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`,@@ -346,7 +439,9 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES? MAX_TOTAL_ATTACHMENT_BYTES- : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;+ : video+ ? ANTIGRAVITY_MAX_VIDEO_ATTACHMENT_BYTES+ : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;if (attachment.type === "file" &&(size > limit || totalBytes + size > MAX_TOTAL_ATTACHMENT_BYTES)@@ -365,8 +460,8 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functiEffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`),),);- if (pdf) {- blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType });+ if (pdf || video) {+ blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType, size });continue;}const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe(diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.tsnew file mode 100644index 00000000000..78927b09d74--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts@@ -0,0 +1,344 @@+// @effect-diagnostics nodeBuiltinImport:off -- fixtures name transcript files by URL.+import * as NodeURL from "node:url";++import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Path from "effect/Path";++import {+ ANTIGRAVITY_SUBAGENT_BATCH_TITLE,+ antigravitySubagentLaunches,+ describeAntigravitySubagentLaunches,+ readAntigravityChildWork,+} from "./AntigravityChildWork.ts";+import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts";+import {+ autoApproved,+ CHILD,+ invokeStep,+ LAUNCH,+ makeProfile,+ plannerStep,+ ROOT,+ transcriptLines,+} from "./AntigravityChildWork.testkit.ts";++const read = (+ profileDirectory: string,+ nativeTaskId: string,+ launch: { readonly title: string | null; readonly prompt: string } = {+ title: null,+ prompt: "Readme check",+ },+ siblings: ReadonlyArray<{+ readonly nativeTaskId: string;+ readonly title: string | null;+ readonly prompt: string;+ }> = [],+) =>+ readAntigravityChildWork({+ profileDirectory,+ rootSessionId: ROOT,+ nativeTaskId,+ launch,+ siblings,+ });++it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => {+ it.effect("follows an auto-approved call id through its planner step to the record", () =>+ Effect.gen(function* () {+ const { profile } = yield* makeProfile({ steps: autoApproved });+ const [child, ...rest] = yield* read(profile, `${ROOT}:1`);+ expect(rest).toEqual([]);+ expect(child).toMatchObject({+ conversationId: CHILD,+ role: LAUNCH.role,+ prompt: LAUNCH.prompt,+ truncated: false,+ });+ // The launch envelope repeats the prompt shown above, so the steps start with the child's work.+ expect(child?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([+ "view_file",+ "2: child read marker 4242",+ "marker 4242 found",+ ]);+ expect(child?.steps?.[0]?.toolCalls[0]?.input).toBe('{"AbsolutePath":"/project/README.md"}');+ }),+ );++ it.effect("needs proof that the call id belongs to the parent's record", () =>+ Effect.gen(function* () {+ const { profile } = yield* makeProfile({+ steps: (logUri) => [+ ...autoApproved(logUri),+ [5, 15, plannerStep(["call-b", "call-c"])],+ [+ 6,+ 127,+ invokeStep({ callId: "call-b", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),+ ],+ [+ 7,+ 127,+ invokeStep({ callId: "call-c", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),+ ],+ ],+ });+ // Another session's id, a step that is not the planner call, and parallel calls that share one id.+ expect(yield* read(profile, `00000000-0000-4000-8000-000000000000:1`)).toEqual([]);+ expect(yield* read(profile, `${ROOT}:2`)).toEqual([]);+ expect(yield* read(profile, `${ROOT}:5`)).toEqual([]);+ }),+ );++ it.effect("matches a permission-prompt call by its launch text, only when unique", () =>+ Effect.gen(function* () {+ const other = { role: "Test Runner", prompt: "Run the tests" };+ const long = { role: "Long Reader", prompt: `Read this:\n${"x".repeat(9_000)}` };+ // A role's leading byte order mark is part of its text.+ const marked = { role: "\uFEFFMarked", prompt: "Check the mark" };+ const { profile } = yield* makeProfile({+ steps: (logUri) => [+ [+ 2,+ 127,+ invokeStep({ callId: "x", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),+ ],+ [+ 8,+ 127,+ invokeStep({ callId: "w", launches: [long], children: [{ id: CHILD, logUri }] }),+ ],+ [+ 10,+ 127,+ invokeStep({ callId: "v", launches: [marked], children: [{ id: CHILD, logUri }] }),+ ],+ [+ 4,+ 127,+ invokeStep({ callId: "y", launches: [other], children: [{ id: CHILD, logUri }] }),+ ],+ [+ 6,+ 127,+ invokeStep({ callId: "z", launches: [other], children: [{ id: CHILD, logUri }] }),+ ],+ ],+ });+ const opaque = "35bea692fa95447fbdae6333fec5515f";+ const matched = yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]));+ expect(matched.map((child) => child.role)).toEqual([LAUNCH.role]);+ // T3 knows a second batch with this text that the agent has not recorded yet.+ const twin = { nativeTaskId: "f00d", ...describeAntigravitySubagentLaunches([LAUNCH]) };+ expect(+ yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]), [twin]),+ ).toEqual([]);+ // T3 stores the launch from the bounded tool payload, which keeps only a long prompt's tail.+ const stored = antigravitySubagentLaunches(+ sanitizeAntigravityToolPayload({ Subagents: [{ Role: long.role, Prompt: long.prompt }] }),+ );+ const longMatch = yield* read(profile, opaque, describeAntigravitySubagentLaunches(stored!));+ expect(longMatch.map((child) => child.prompt)).toEqual([long.prompt]);+ expect(+ yield* read(profile, opaque, describeAntigravitySubagentLaunches([marked])),+ ).toHaveLength(1);+ expect(yield* read(profile, opaque, { title: "Marked", prompt: marked.prompt })).toEqual([]);+ expect(yield* read(profile, opaque, describeAntigravitySubagentLaunches([other]))).toEqual(+ [],+ );+ expect(yield* read(profile, opaque, { title: null, prompt: "Readme check" })).toEqual([]);+ }),+ );++ it.effect("leaves an auto-approved batch's record out of a launch-text match", () =>+ Effect.gen(function* () {+ const { profile } = yield* makeProfile({ steps: autoApproved });+ const launch = describeAntigravitySubagentLaunches([LAUNCH]);+ const opaque = "35bea692fa95447fbdae6333fec5515f";+ expect(yield* read(profile, opaque, launch)).toHaveLength(1);+ // An earlier auto-approved batch stored no launch text, but its planner step claims the record.+ const auto = {+ nativeTaskId: `${ROOT}:1`,+ title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE,+ prompt: "",+ };+ expect(yield* read(profile, opaque, launch, [auto])).toEqual([]);+ // A sibling that cannot be ruled out refuses the match: its planner step is unreadable,+ // or it is a permission batch whose launch text is missing or cut.+ for (const sibling of [+ { ...auto, nativeTaskId: `${ROOT}:99` },+ { nativeTaskId: "0ld", title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE, prompt: "Running" },+ // Its stored launch was cut, so it may be this same launch.+ { nativeTaskId: "cut", title: LAUNCH.role, prompt: "[Earlier output truncated]\n\nmarker" },+ { nativeTaskId: "cut", title: "[Earlier output truncated]\n\nReader", prompt: "x" },+ { nativeTaskId: "cut", title: null, prompt: "[Earlier output truncated]\n\nx" },+ ]) {+ expect(yield* read(profile, opaque, launch, [sibling])).toEqual([]);+ }+ // A cut prompt under different roles is another launch.+ const other = {+ nativeTaskId: "cut",+ title: "Test Runner",+ prompt: "[Earlier output truncated]\n\nx",+ };+ expect(yield* read(profile, opaque, launch, [other])).toHaveLength(1);+ }),+ );++ it.effect("reads no transcript outside the child's own profile path", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });+ const secret = path.join(outside, "transcript.jsonl");+ yield* fs.writeFileString(secret, JSON.stringify(transcriptLines[3]) + "\n");+ const named = yield* makeProfile({+ steps: () => autoApproved(NodeURL.pathToFileURL(secret).href),+ });+ const [namedChild] = yield* read(named.profile, `${ROOT}:1`);+ expect(namedChild?.role).toBe(LAUNCH.role);+ expect(namedChild?.steps).toBeNull();++ const linked = yield* makeProfile({ steps: autoApproved });+ yield* fs.remove(linked.transcriptPath);+ yield* fs.symlink(secret, linked.transcriptPath);+ const [linkedChild] = yield* read(linked.profile, `${ROOT}:1`);+ expect(linkedChild?.steps).toBeNull();+ }),+ );++ it.effect("reads only the tail of a large transcript", () =>+ Effect.gen(function* () {+ const filler = JSON.stringify({+ step_index: 0,+ type: "VIEW_FILE",+ status: "DONE",+ content: "x".repeat(10_000),+ });+ const { profile } = yield* makeProfile({+ steps: autoApproved,+ transcript: `${Array.from({ length: 40 }, () => filler).join("\n")}\n${JSON.stringify(transcriptLines[3])}\n`,+ });+ const [child] = yield* read(profile, `${ROOT}:1`);+ expect(child?.truncated).toBe(true);+ expect(child?.steps?.length).toBeLessThan(40);+ expect(child?.steps?.at(-1)?.text).toBe("marker 4242 found");+ expect(child?.steps?.[0]?.text?.length).toBeLessThanOrEqual(4_001);+ }),+ );++ it.effect("refuses links between children and sessions inside the same profile", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const sibling = "b468c0e1d2f34a5b6c7d8e9f0a1b2c3d";+ // The record names this child's literal path, but the child directory links to a sibling.+ const linked = yield* makeProfile({ steps: autoApproved });+ const brain = path.join(linked.profile, "antigravity-acp", "brain");+ yield* fs.rename(path.join(brain, CHILD), path.join(brain, sibling));+ yield* fs.symlink(path.join(brain, sibling), path.join(brain, CHILD));+ const [child] = yield* read(linked.profile, `${ROOT}:1`);+ expect(child?.role).toBe(LAUNCH.role);+ expect(child?.steps).toBeNull();++ // This session's database links to another session's records.+ const other = yield* makeProfile({ steps: autoApproved });+ const conversations = path.join(other.profile, "antigravity-acp", "conversations");+ const peer = path.join(conversations, "00000000-0000-4000-8000-000000000000.db");+ yield* fs.rename(path.join(conversations, `${ROOT}.db`), peer);+ yield* fs.symlink(peer, path.join(conversations, `${ROOT}.db`));+ expect(yield* read(other.profile, `${ROOT}:1`)).toEqual([]);+ }),+ );++ it.effect("declines a launch-text match it cannot prove unique within its scan bounds", () =>+ Effect.gen(function* () {+ const record = (callId: string, logUri: string) =>+ invokeStep({ callId, launches: [LAUNCH], children: [{ id: CHILD, logUri }] });+ const other = { role: "Test Runner", prompt: "Run the tests" };+ const filler = (idx: number, logUri: string) =>+ [+ idx,+ 127,+ invokeStep({ callId: `f${idx}`, launches: [other], children: [{ id: CHILD, logUri }] }),+ ] as const;+ const opaque = "35bea692fa95447fbdae6333fec5515f";+ const launch = describeAntigravitySubagentLaunches([LAUNCH]);+ const cases = [+ // More records than one open may scan.+ (logUri: string) => [+ [1, 127, record("x", logUri)] as const,+ ...Array.from({ length: 200 }, (_, index) => filler(index + 2, logUri)),+ ],+ // An oversized record could hold an identical launch.+ (logUri: string) => [+ [1, 127, record("x", logUri)] as const,+ [2, 127, new Uint8Array(1024 * 1024 + 1)] as const,+ ],+ // So could one this reader cannot decode.+ (logUri: string) => [+ [1, 127, record("x", logUri)] as const,+ [2, 127, Uint8Array.from([0xff, 0xff])] as const,+ ],+ ];+ for (const steps of cases) {+ const { profile } = yield* makeProfile({ steps });+ expect(yield* read(profile, opaque, launch)).toEqual([]);+ }+ }),+ );++ it.effect("keeps the batch view for a batch over the child limit", () =>+ Effect.gen(function* () {+ const { profile } = yield* makeProfile({+ steps: (logUri) => [+ [1, 15, plannerStep(["call-a"])],+ [+ 2,+ 127,+ invokeStep({+ callId: "call-a",+ launches: Array.from({ length: 17 }, () => LAUNCH),+ children: Array.from({ length: 17 }, () => ({ id: CHILD, logUri })),+ }),+ ],+ ],+ });+ expect(yield* read(profile, `${ROOT}:1`)).toEqual([]);+ }),+ );++ it.effect("shares one transcript budget across the batch", () =>+ Effect.gen(function* () {+ const filler = JSON.stringify({+ step_index: 0,+ type: "VIEW_FILE",+ status: "DONE",+ content: "x".repeat(1_000),+ });+ const transcript = `${Array.from({ length: 300 }, () => filler).join("\n")}\n`;+ const { profile } = yield* makeProfile({+ transcript,+ steps: (logUri) => [+ [1, 15, plannerStep(["call-a"])],+ [+ 2,+ 127,+ invokeStep({+ callId: "call-a",+ launches: Array.from({ length: 16 }, () => LAUNCH),+ children: Array.from({ length: 16 }, () => ({ id: CHILD, logUri })),+ }),+ ],+ ],+ });+ const children = yield* read(profile, `${ROOT}:1`);+ expect(children).toHaveLength(16);+ expect(children.every((child) => child.truncated)).toBe(true);+ expect(JSON.stringify(children).length).toBeLessThan(600 * 1024);+ }),+ );+});diff --git a/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts b/apps/server/src/provider/acp/AntigravityChildWork.testkit.tsnew file mode 100644index 00000000000..82a2befbf66--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts@@ -0,0 +1,111 @@+// @effect-diagnostics nodeBuiltinImport:off -- fixtures write a native session database.+import * as NodeSqlite from "node:sqlite";+import * as NodeURL from "node:url";++import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Path from "effect/Path";++export const ROOT = "7d40e54d-5977-4239-940b-246cdd81a12b";+export const CHILD = "a357bf2720914589dd1ec49f7a816115";+export const LAUNCH = { role: "Readme Reader", prompt: "Read README.md and report the marker" };++// Mirrors the 1.4.5 runtime: Step{5: metadata{4: tool call{1 id, 2 name}}, 20: planner{7: calls},+// 143: invoke_subagent{9: specs{2 role, 3 prompt}, 10: results{1 conversation, 2 log uri}}}.+const varint = (value: number): number[] => {+ const bytes: number[] = [];+ while (value >= 0x80) {+ bytes.push((value & 0x7f) | 0x80);+ value = Math.floor(value / 0x80);+ }+ return [...bytes, value];+};+const field = (number: number, value: string | Uint8Array) => {+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;+ return [...varint(number * 8 + 2), ...varint(bytes.length), ...bytes];+};+const proto = (...parts: number[][]) => Uint8Array.from(parts.flat());+const toolCall = (id: string) => proto(field(1, id), field(2, "invoke_subagent"));++export const invokeStep = (input: {+ readonly callId: string;+ readonly launches: ReadonlyArray<typeof LAUNCH>;+ readonly children: ReadonlyArray<{ readonly id: string; readonly logUri: string }>;+}) =>+ proto(+ [...varint(1 * 8), ...varint(127)],+ field(5, proto(field(4, toolCall(input.callId)))),+ field(+ 143,+ proto(+ ...input.launches.map((launch) =>+ field(9, proto(field(1, "research"), field(2, launch.role), field(3, launch.prompt))),+ ),+ ...input.children.map((child) =>+ field(10, proto(field(1, child.id), field(2, child.logUri))),+ ),+ ),+ ),+ );+export const plannerStep = (callIds: ReadonlyArray<string>) =>+ proto(field(20, proto(...callIds.map((id) => field(7, toolCall(id))))));++export const transcriptLines = [+ // Trimmed from 1.4.5: the launch envelope around the prompt the parent record already holds.+ {+ step_index: 0,+ type: "SYSTEM_MESSAGE",+ status: "DONE",+ content: `<USER_REQUEST sender="7d40e54d-5977-4239-940b-246cdd81a12b" timestamp="2026-10-31T18:00:00Z">\n${LAUNCH.prompt}\n</USER_REQUEST>`,+ },+ {+ step_index: 1,+ type: "PLANNER_RESPONSE",+ status: "DONE",+ // The runtime stores each argument value as JSON text.+ tool_calls: [{ name: "view_file", args: { AbsolutePath: '"/project/README.md"' } }],+ },+ { step_index: 2, type: "VIEW_FILE", status: "DONE", content: "2: child read marker 4242" },+ { step_index: 3, type: "PLANNER_RESPONSE", status: "DONE", content: "marker 4242 found" },+];++export const makeProfile = Effect.fn("makeProfile")(function* (input: {+ /** Defaults to a scoped temp directory. */+ readonly profile?: string;+ readonly steps: (logUri: string) => ReadonlyArray<readonly [number, number, Uint8Array]>;+ readonly transcript?: string;+}) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const profile = input.profile ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-child-" }));+ const acp = path.join(profile, "antigravity-acp");+ const logs = path.join(acp, "brain", CHILD, ".system_generated", "logs");+ yield* fs.makeDirectory(path.join(acp, "conversations"), { recursive: true });+ yield* fs.makeDirectory(logs, { recursive: true });+ const transcriptPath = path.join(logs, "transcript.jsonl");+ yield* fs.writeFileString(+ transcriptPath,+ input.transcript ?? transcriptLines.map((line) => JSON.stringify(line)).join("\n") + "\n",+ );+ const logUri = NodeURL.pathToFileURL(transcriptPath).href;+ const database = new NodeSqlite.DatabaseSync(path.join(acp, "conversations", `${ROOT}.db`));+ database.exec(+ "CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer NOT NULL DEFAULT 0, step_format integer NOT NULL DEFAULT 0, step_payload blob)",+ );+ const insert = database.prepare(+ "INSERT INTO steps (idx, step_type, step_payload) VALUES (?, ?, ?)",+ );+ for (const [idx, type, payload] of input.steps(logUri)) insert.run(idx, type, payload);+ database.close();+ return { profile, transcriptPath, logUri };+});++export const autoApproved = (logUri: string) =>+ [+ [1, 15, plannerStep(["call-a"])],+ [+ 2,+ 127,+ invokeStep({ callId: "call-a", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),+ ],+ ] as const;diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.tsnew file mode 100644index 00000000000..ea12e0e2b20--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityChildWork.ts@@ -0,0 +1,478 @@+// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only.+import * as NodeFS from "node:fs";+import * as NodeFSP from "node:fs/promises";+import * as NodeSqlite from "node:sqlite";+import * as NodeURL from "node:url";++import type {+ OrchestrationV2NativeChildStep,+ OrchestrationV2NativeChildWork,+} from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as Predicate from "effect/Predicate";+import * as Schema from "effect/Schema";++import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";+import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts";++// Field numbers from the runtime's trajectory protos (exa.cortex_pb).+const STEP_METADATA = 5;+const METADATA_TOOL_CALL = 4;+const STEP_PLANNER_RESPONSE = 20;+const PLANNER_TOOL_CALLS = 7;+const STEP_INVOKE_SUBAGENT = 143;+const INVOKE_SPECS = 9;+const INVOKE_RESULTS = 10;+const INVOKE_SUBAGENT_STEP_TYPE = 127;++// One open reads at most this much; past any bound the batch view stays as it was.+const MAX_STEP_BYTES = 1024 * 1024;+const MAX_INVOKE_ROWS = 200;+const MAX_SCAN_BYTES = 8 * 1024 * 1024;+const MAX_CHILDREN = 16;+const TRANSCRIPT_BYTE_CAP = 256 * 1024;+const BATCH_TRANSCRIPT_BYTES = 512 * 1024;+const STEP_TEXT_CAP = 4_000;+const TOOL_INPUT_CAP = 1_000;++/** T3's title for a batch whose launch text it never saw. */+export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch";++interface AntigravityChildLaunch {+ readonly role: string;+ readonly prompt: string;+}++const decodeLaunchInput = Schema.decodeUnknownOption(+ Schema.Struct({+ Subagents: Schema.NonEmptyArray(Schema.Struct({ Role: Schema.String, Prompt: Schema.String })),+ }),+);++/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */+export function antigravitySubagentLaunches(+ input: unknown,+): ReadonlyArray<AntigravityChildLaunch> | undefined {+ return Option.getOrUndefined(+ Option.map(decodeLaunchInput(input), (decoded) =>+ decoded.Subagents.map((entry) => ({ role: entry.Role, prompt: entry.Prompt })),+ ),+ );+}++/** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */+export function describeAntigravitySubagentLaunches(+ launches: ReadonlyArray<AntigravityChildLaunch>,+) {+ const [only] = launches;+ return launches.length === 1 && only !== undefined+ ? { title: only.role, prompt: only.prompt }+ : {+ title: launches.map((launch) => launch.role).join(", "),+ prompt: launches.map((launch) => `${launch.role}\n${launch.prompt}`).join("\n\n"),+ };+}++/** Length-delimited fields only; varints and fixed values are skipped. */+function protoFields(bytes: Uint8Array): ReadonlyArray<readonly [number, Uint8Array]> {+ const fields: Array<readonly [number, Uint8Array]> = [];+ let offset = 0;+ const varint = () => {+ let value = 0;+ for (let shift = 0; shift < 64; shift += 7) {+ const byte = bytes[offset++];+ if (byte === undefined) throw new Error("Truncated varint");+ value += (byte & 0x7f) * 2 ** shift;+ if (byte < 0x80) return value;+ }+ throw new Error("Overlong varint");+ };+ while (offset < bytes.length) {+ const key = varint();+ const wire = key % 8;+ const field = Math.floor(key / 8);+ if (wire === 0) varint();+ else if (wire === 1) offset += 8;+ else if (wire === 5) offset += 4;+ else if (wire === 2) {+ const length = varint();+ if (offset + length > bytes.length) throw new Error("Truncated field");+ fields.push([field, bytes.subarray(offset, offset + length)]);+ offset += length;+ } else throw new Error("Unsupported wire type");+ }+ if (offset > bytes.length) throw new Error("Truncated field");+ return fields;+}++// Keep a leading byte order mark: T3 stores launch text with it.+const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });+const messages = (bytes: Uint8Array, field: number) =>+ protoFields(bytes).flatMap(([number, value]) => (number === field ? [value] : []));+const message = (bytes: Uint8Array | undefined, field: number) =>+ bytes === undefined ? undefined : messages(bytes, field)[0];+const text = (bytes: Uint8Array | undefined, field: number) => {+ const value = message(bytes, field);+ return value === undefined ? undefined : textDecoder.decode(value);+};++interface InvokeRecord {+ readonly toolCallId: string | undefined;+ readonly launches: ReadonlyArray<AntigravityChildLaunch>;+ readonly children: ReadonlyArray<{ readonly conversationId: string; readonly logUri: string }>;+}++const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/;++/** Undefined for steps this reader cannot decode, so they never count as proof. */+const safely =+ <A>(decode: (payload: Uint8Array) => A) =>+ (payload: Uint8Array): A | undefined => {+ try {+ return decode(payload);+ } catch {+ return undefined;+ }+ };++const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => {+ const invoke = message(payload, STEP_INVOKE_SUBAGENT);+ if (invoke === undefined) return undefined;+ const children = messages(invoke, INVOKE_RESULTS).map((result) => ({+ conversationId: text(result, 1) ?? "",+ logUri: text(result, 2) ?? "",+ }));+ if (!children.every((child) => NATIVE_ID.test(child.conversationId))) return undefined;+ return {+ toolCallId: text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1),+ launches: messages(invoke, INVOKE_SPECS).map((spec) => ({+ role: text(spec, 2) ?? "",+ prompt: text(spec, 3) ?? "",+ })),+ children,+ };+});++const plannerInvokeCallIds = safely((payload): ReadonlyArray<string> => {+ const planner = message(payload, STEP_PLANNER_RESPONSE);+ if (planner === undefined) return [];+ return messages(planner, PLANNER_TOOL_CALLS).flatMap((call) => {+ const id = text(call, 1);+ return text(call, 2) === "invoke_subagent" && id !== undefined ? [id] : [];+ });+});++const payloadOf = (row: unknown) =>+ row !== null &&+ typeof row === "object" &&+ "step_payload" in row &&+ row.step_payload instanceof Uint8Array+ ? row.step_payload+ : undefined;++interface BatchLaunch {+ readonly title: string | null;+ readonly prompt: string;+}++const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => {+ const planner = payloadOf(+ database+ .prepare(+ "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?",+ )+ .get(plannerIdx, MAX_STEP_BYTES),+ );+ return planner === undefined ? undefined : plannerInvokeCallIds(planner);+};++/**+ * Auto-approved calls carry `<sessionId>:<plannerStep>`; the record with that planner call's id+ * is the proof. Permission prompts carry a random id, so the launch text must match one record+ * no auto-approved sibling claims, and no sibling may share the text.+ */+function findInvokeRecord(+ database: NodeSqlite.DatabaseSync,+ input: {+ readonly rootSessionId: string;+ readonly nativeTaskId: string;+ readonly launch: BatchLaunch;+ readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;+ },+): InvokeRecord | undefined {+ const plannerIdxOf = (nativeTaskId: string) => {+ const stepId = /^(.+):(\d+)$/.exec(nativeTaskId);+ return stepId === null ? undefined : stepId[1] === input.rootSessionId ? Number(stepId[2]) : -1;+ };+ const plannerIdx = plannerIdxOf(input.nativeTaskId);+ if (plannerIdx !== undefined) {+ if (plannerIdx < 0) return undefined;+ const callIds = plannerCallIdsAt(database, plannerIdx) ?? [];+ const [callId] = callIds;+ if (callIds.length !== 1) return undefined;+ // The record follows the planner step that issued the call.+ let rows = 0;+ let bytes = 0;+ for (const row of database+ .prepare(+ // SQLite returns only in-bound payloads, so an oversized row never reaches this process.+ "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",+ )+ .iterate(MAX_STEP_BYTES, INVOKE_SUBAGENT_STEP_TYPE, plannerIdx)) {+ const size = row !== null && typeof row === "object" && "size" in row ? Number(row.size) : 0;+ rows += 1;+ bytes += size;+ if (rows > MAX_INVOKE_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES)+ return undefined;+ const payload = payloadOf(row);+ const record = payload === undefined ? undefined : decodeInvokeRecord(payload);+ if (record !== undefined && record.toolCallId === callId) return complete(record);+ }+ return undefined;+ }+ const totals = database+ .prepare(+ "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 = ?",+ )+ .get(INVOKE_SUBAGENT_STEP_TYPE);+ const total = (key: string) =>+ totals !== undefined && key in totals ? Number(totals[key as keyof typeof totals] ?? 0) : 0;+ const sameText = (launch: BatchLaunch) =>+ launch.title === input.launch.title && launch.prompt === input.launch.prompt;+ if (+ input.siblings.some(sameText) ||+ total("rows") > MAX_INVOKE_ROWS ||+ total("bytes") > MAX_SCAN_BYTES ||+ total("largest") > MAX_STEP_BYTES ||+ total("other") > 0+ ) {+ return undefined;+ }+ const claimed = new Set<string>();+ for (const sibling of input.siblings) {+ const idx = plannerIdxOf(sibling.nativeTaskId);+ // A sibling whose launch text is missing, or cut under the same roles, or whose planner step+ // is unreadable, cannot be ruled out.+ if (idx === undefined) {+ if (+ sibling.title === ANTIGRAVITY_SUBAGENT_BATCH_TITLE ||+ (sibling.title !== null && isCutAntigravityToolText(sibling.title)) ||+ (isCutAntigravityToolText(sibling.prompt) &&+ (sibling.title === null || sibling.title === input.launch.title))+ )+ return undefined;+ continue;+ }+ if (idx < 0) continue;+ const callIds = plannerCallIdsAt(database, idx);+ if (callIds === undefined || callIds.length === 0) return undefined;+ for (const callId of callIds) claimed.add(callId);+ }+ const matches: Array<InvokeRecord> = [];+ for (const row of database+ .prepare("SELECT step_payload FROM steps WHERE step_type = ? ORDER BY idx")+ .iterate(INVOKE_SUBAGENT_STEP_TYPE)) {+ const payload = payloadOf(row);+ const record = payload === undefined ? undefined : decodeInvokeRecord(payload);+ // An unreadable record could be an identical launch, so uniqueness is unproven.+ if (record === undefined) return undefined;+ if (record.toolCallId !== undefined && claimed.has(record.toolCallId)) continue;+ // T3 stored the launch from the bounded tool payload, so bound the record the same way.+ const described = describeAntigravitySubagentLaunches(+ record.launches.map((launch) => ({+ role: boundAntigravityToolText(launch.role),+ prompt: boundAntigravityToolText(launch.prompt),+ })),+ );+ if (sameText(described)) {+ matches.push(record);+ }+ }+ const [match] = matches;+ return matches.length === 1 && match !== undefined ? complete(match) : undefined;+}++const complete = (record: InvokeRecord) =>+ record.launches.length === record.children.length && record.children.length <= MAX_CHILDREN+ ? record+ : undefined;++const TranscriptLine = Schema.Struct({+ step_index: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),+ type: Schema.String,+ status: Schema.optional(Schema.String),+ content: Schema.optional(Schema.String),+ error: Schema.optional(Schema.String),+ tool_calls: Schema.optional(+ Schema.Array(Schema.Struct({ name: Schema.String, args: Schema.optional(Schema.Unknown) })),+ ),+});+const decodeTranscriptLine = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptLine));++// The runtime records each tool argument value as JSON text.+const decodeArgument = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));+const toolArguments = (args: unknown) =>+ Predicate.isObject(args)+ ? Object.fromEntries(+ Object.entries(args).map(([key, value]) => [+ key,+ typeof value === "string" ? Option.getOrElse(decodeArgument(value), () => value) : value,+ ]),+ )+ : (args ?? {});++const capText = (value: string, limit: number) =>+ value.length <= limit ? value : `${value.slice(0, limit)}…`;++/** Skips the runtime's opening envelope around the launch prompt the view already shows. */+function transcriptSteps(+ contents: string,+ prompt: string,+): ReadonlyArray<OrchestrationV2NativeChildStep> {+ const launchPrompt = prompt.trim();+ return contents.split("\n").flatMap((line) =>+ Option.match(decodeTranscriptLine(line), {+ onNone: () => [],+ onSome: (step) =>+ step.step_index === 0 &&+ step.type === "SYSTEM_MESSAGE" &&+ launchPrompt !== "" &&+ step.content?.includes(launchPrompt) === true+ ? []+ : [+ {+ index: step.step_index,+ type: step.type,+ status: step.status ?? null,+ text:+ step.content !== undefined || step.error !== undefined+ ? capText(step.content ?? step.error ?? "", STEP_TEXT_CAP)+ : null,+ toolCalls: (step.tool_calls ?? []).map((call) => ({+ name: call.name,+ input: capText(JSON.stringify(toolArguments(call.args)), TOOL_INPUT_CAP),+ })),+ },+ ],+ }),+ );+}++/** Reads the tail of the transcript at the named child's own unlinked profile path. */+async function readChildTranscript(+ profileRoot: string,+ child: InvokeRecord["children"][number],+ prompt: string,+ byteCap: number,+) {+ const expected = (+ await antigravityManagedPath(+ profileRoot,+ [+ "antigravity-acp",+ "brain",+ child.conversationId,+ ".system_generated",+ "logs",+ "transcript.jsonl",+ ],+ "file",+ )+ )?.path;+ if (expected === undefined) return undefined;+ let named: string;+ try {+ named = NodeURL.fileURLToPath(child.logUri);+ } catch {+ return undefined;+ }+ if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined;+ const handle = await NodeFSP.open(+ expected,+ NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0),+ );+ try {+ const stat = await handle.stat();+ if (!stat.isFile()) return undefined;+ const length = Math.min(stat.size, byteCap);+ const buffer = Buffer.alloc(length);+ const { bytesRead } = await handle.read(buffer, 0, length, stat.size - length);+ const truncated = stat.size > length;+ let contents = buffer.subarray(0, bytesRead).toString("utf8");+ // A tail read starts mid-line.+ if (truncated) contents = contents.slice(contents.indexOf("\n") + 1);+ return { steps: transcriptSteps(contents, prompt), truncated };+ } finally {+ await handle.close();+ }+}++class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()(+ "AntigravityChildWorkReadError",+ { cause: Schema.Defect() },+) {+ override get message(): string {+ return "Could not read Antigravity subagent records.";+ }+}++/** Children a subagent tool call launched, proven by the parent's own session record. */+export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: {+ readonly profileDirectory: string;+ readonly rootSessionId: string;+ readonly nativeTaskId: string;+ readonly launch: BatchLaunch;+ /** The thread's other Antigravity batches from this instance. */+ readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;+}) {+ if (!NATIVE_ID.test(input.rootSessionId)) return [];+ return yield* Effect.tryPromise({+ try: async (): Promise<ReadonlyArray<OrchestrationV2NativeChildWork>> => {+ const profileRoot = await antigravityProfileRoot(input.profileDirectory);+ const databasePath =+ profileRoot === undefined+ ? undefined+ : (+ await antigravityManagedPath(+ profileRoot,+ ["antigravity-acp", "conversations", `${input.rootSessionId}.db`],+ "file",+ )+ )?.path;+ if (profileRoot === undefined || databasePath === undefined) return [];+ const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });+ let record: InvokeRecord | undefined;+ try {+ record = findInvokeRecord(database, input);+ } finally {+ database.close();+ }+ if (record === undefined) return [];+ const { launches, children } = record;+ // One budget for the whole batch, so the response stays small however many children ran.+ const byteCap = Math.min(+ TRANSCRIPT_BYTE_CAP,+ Math.floor(BATCH_TRANSCRIPT_BYTES / Math.max(1, children.length)),+ );+ return Promise.all(+ children.map(async (child, index) => {+ const transcript = await readChildTranscript(+ profileRoot,+ child,+ launches[index]?.prompt ?? "",+ byteCap,+ ).catch(() => undefined);+ return {+ conversationId: child.conversationId,+ role: launches[index]?.role ?? "",+ prompt: launches[index]?.prompt ?? "",+ steps: transcript?.steps ?? null,+ truncated: transcript?.truncated ?? false,+ };+ }),+ );+ },+ catch: (cause) => new AntigravityChildWorkReadError({ cause }),+ });+});diff --git a/apps/server/src/provider/acp/AntigravityEditLocation.test.ts b/apps/server/src/provider/acp/AntigravityEditLocation.test.tsnew file mode 100644index 00000000000..23f04f011fd--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityEditLocation.test.ts@@ -0,0 +1,245 @@+import { describe, expect, it } from "vite-plus/test";++import { ANTIGRAVITY_EDIT_DIFF_OMITTED, antigravityEditPatch } from "./AntigravityEditLocation.ts";++const path = "/workspace/app.ts";+const file = Array.from({ length: 20 }, (_, i) =>+ i === 9+ ? "const target = 10;"+ : i === 14+ ? "const other = 15;"+ : `const line${i + 1} = ${i + 1};`,+).join("\n");+const replace = { TargetContent: "const target = 10;", ReplacementContent: "const target = 100;" };+const header = `--- ${path}\n+++ ${path}\n`;++describe("antigravityEditPatch", () => {+ it("finds the target inside the announced search range, in either argument casing", () => {+ const expected = `${header}@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`;+ const readPreEditFile = () => file;+ for (const rawInput of [+ { ...replace, StartLine: 5, EndLine: 20 },+ {+ target_content: replace.TargetContent,+ replacement_content: replace.ReplacementContent,+ start_line: 5,+ end_line: 20,+ },+ {+ replacement_chunks: [+ {+ target_content: replace.TargetContent,+ replacement_content: replace.ReplacementContent,+ start_line: 5,+ end_line: 20,+ },+ ],+ },+ // Like the runtime, a present PascalCase value wins, and a 0 line means unspecified.+ { ...replace, target_content: "const other = 15;", StartLine: 5, EndLine: 0 },+ ]) {+ expect(antigravityEditPatch({ path, rawInput, readPreEditFile })).toBe(expected);+ }+ for (const rawInput of [replace, { ReplacementChunks: [replace] }]) {+ expect(+ antigravityEditPatch({ path, rawInput, locations: [{ path, line: 5 }], readPreEditFile }),+ ).toBe(expected);+ }+ // A hunk replaces whole lines, so a match inside a line is not a placement.+ expect(+ antigravityEditPatch({+ path,+ rawInput: { TargetContent: "10", ReplacementContent: "100" },+ readPreEditFile,+ }),+ ).toMatch(/ snippet, line unknown$/m);+ // The range start is not the target's line: without the file, or outside the range, it stays unplaced.+ const snippet = `${header}@@ -1,1 +1,1 @@ snippet, line unknown\n-const target = 10;\n+const target = 100;\n`;+ expect(+ antigravityEditPatch({ path, rawInput: { ...replace, StartLine: 5, EndLine: 20 } }),+ ).toBe(snippet);+ expect(+ antigravityEditPatch({+ path,+ rawInput: { ...replace, StartLine: 11, EndLine: 20 },+ readPreEditFile,+ }),+ ).toBe(snippet);+ });++ it("finds an unannounced snippet in the pre-edit file", () => {+ const expected = `${header}@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`;+ expect(antigravityEditPatch({ path, rawInput: replace, readPreEditFile: () => file })).toBe(+ expected,+ );+ const crlf = file.replaceAll("\n", "\r\n");+ expect(antigravityEditPatch({ path, rawInput: replace, readPreEditFile: () => crlf })).toBe(+ expected,+ );+ // A target written with CRLF previews the same lines, without carriage returns.+ expect(+ antigravityEditPatch({+ path,+ rawInput: {+ TargetContent: "const target = 10;\r\n",+ ReplacementContent: "const target = 100;\r\n",+ },+ readPreEditFile: () => crlf,+ }),+ ).toBe(expected);+ // A change to the line ending alone has no LF hunk to place.+ const endingOnly = {+ TargetContent: "const target = 10;\r\n",+ ReplacementContent: "const target = 10;\n",+ };+ for (const readPreEditFile of [() => crlf, undefined]) {+ expect(antigravityEditPatch({ path, rawInput: endingOnly, readPreEditFile })).toBe(+ ANTIGRAVITY_EDIT_DIFF_OMITTED,+ );+ }+ // A multi-line target written with LF still finds its lines in a CRLF file.+ expect(+ antigravityEditPatch({+ path,+ rawInput: {+ TargetContent: "const line9 = 9;\nconst target = 10;",+ ReplacementContent: "const line9 = 9;\nconst target = 100;",+ },+ readPreEditFile: () => crlf,+ }),+ ).toMatch(/^@@ -9,2 \+9,2 @@$/m);+ });++ it("omits the preview when a chunk adds or removes a line break at its end", () => {+ // Whether that splits or joins lines depends on what follows the match.+ for (const [TargetContent, ReplacementContent] of [+ ["const line3 = 3;", "x\n"],+ ["const line3 = 3;\n", "x"],+ ["const line20 = 20;", "x\n"],+ // Clearing the last line of a file with no final newline removes the line.+ ["const line20 = 20;", ""],+ ]) {+ expect(+ antigravityEditPatch({+ path,+ rawInput: { TargetContent, ReplacementContent },+ readPreEditFile: () => file,+ }),+ ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);+ }+ });++ it("labels repeated or unmatched snippets instead of placing them at line 1", () => {+ const snippet = `${header}@@ -1,1 +1,1 @@ snippet, line unknown\n-const target = 10;\n+const target = 100;\n`;+ for (const readPreEditFile of [+ () => `${file}\n${file}`,+ () => "unrelated\n",+ () => undefined,+ undefined,+ ]) {+ expect(antigravityEditPatch({ path, rawInput: replace, readPreEditFile })).toBe(snippet);+ }+ });++ it("places each replacement chunk and shifts later chunks by earlier line changes", () => {+ const patch = antigravityEditPatch({+ path,+ rawInput: {+ ReplacementChunks: [+ {+ TargetContent: "const other = 15;\n",+ ReplacementContent: "const other = 150;\n",+ StartLine: 15,+ EndLine: 15,+ },+ {+ TargetContent: "const target = 10;\n",+ ReplacementContent: "const target = 100;\nconst added = 1;\n",+ StartLine: 10,+ EndLine: 10,+ },+ ],+ },+ readPreEditFile: () => file,+ });+ expect(patch).toBe(+ [+ header.trimEnd(),+ "@@ -10,1 +10,2 @@",+ "-const target = 10;",+ "+const target = 100;",+ "+const added = 1;",+ "@@ -15,1 +16,1 @@",+ "-const other = 15;",+ "+const other = 150;",+ "",+ ].join("\n"),+ );+ });++ it("omits the preview when only some chunks can be placed", () => {+ const patch = antigravityEditPatch({+ path,+ rawInput: {+ ReplacementChunks: [+ {+ TargetContent: "const target = 10;\n",+ ReplacementContent: "const target = 100;\n",+ StartLine: 10,+ EndLine: 10,+ },+ { TargetContent: "missing", ReplacementContent: "still missing" },+ ],+ },+ readPreEditFile: () => file,+ });+ expect(patch).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);+ });++ it("leaves whole-file writes and unknown inputs to the generic diff", () => {+ expect(antigravityEditPatch({ path, rawInput: { CodeContent: "x" } })).toBeUndefined();+ expect(antigravityEditPatch({ path, rawInput: undefined })).toBeUndefined();+ });++ it("omits the preview once an edit exceeds the shared diff budget", () => {+ const lines = (prefix: string, count: number) =>+ Array.from({ length: count }, (_, index) => `${prefix} ${index} ${"x".repeat(8)}`).join("\n");+ // A 7,000-line wholesale replacement, as one chunk.+ expect(+ antigravityEditPatch({+ path,+ rawInput: {+ TargetContent: lines("old", 7_000),+ ReplacementContent: lines("new", 7_000),+ StartLine: 1,+ },+ }),+ ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);+ // Chunks that each fit, but not together.+ const chunk = (start: number) => ({+ TargetContent: lines(`old-${start}`, 300),+ ReplacementContent: lines(`new-${start}`, 300),+ StartLine: start,+ });+ expect(+ antigravityEditPatch({+ path,+ rawInput: { ReplacementChunks: [chunk(1), chunk(1_000)] },+ }),+ ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);+ // Text over the size limit is not diffed at all.+ expect(+ antigravityEditPatch({+ path,+ rawInput: {+ TargetContent: "a".repeat(200_000),+ ReplacementContent: "b".repeat(100_000),+ StartLine: 1,+ },+ }),+ ).toBe(ANTIGRAVITY_EDIT_DIFF_OMITTED);+ expect(antigravityEditPatch({ path, rawInput: { ReplacementChunks: [chunk(1)] } })).toMatch(+ /^@@ -1,300 \+1,300 @@/m,+ );+ });+});diff --git a/apps/server/src/provider/acp/AntigravityEditLocation.ts b/apps/server/src/provider/acp/AntigravityEditLocation.tsnew file mode 100644index 00000000000..ff16dd014c9--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityEditLocation.ts@@ -0,0 +1,226 @@+// @effect-diagnostics nodeBuiltinImport:off - the tool-call normalizer is synchronous+import * as NodeFS from "node:fs";++import { PositiveInt } from "@t3tools/contracts";+import { FILE_HEADERS_ONLY, formatPatch, structuredPatch, type StructuredPatchHunk } from "diff";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";++const PRE_EDIT_FILE_LIMIT = 1024 * 1024;+// The live preview runs synchronously. One budget covers every chunk in a call: the generic+// ACP formatter's edit-distance limit, plus a size limit that skips diffing entirely.+const EDIT_DIFF_BUDGET = 1_000;+const EDIT_TEXT_BUDGET = 256 * 1024;++/** The edit is too large to preview cheaply; the turn's checkpoint diff still shows it. */+export const ANTIGRAVITY_EDIT_DIFF_OMITTED = Symbol("AntigravityEditDiffOmitted");+const SNIPPET_LABEL = " snippet, line unknown";++/** True when no chunk could be placed; a patch never mixes placed and unplaced chunks. */+export function isAntigravitySnippetPatch(patch: string): boolean {+ return /^@@ .* @@.*$/m.exec(patch)?.[0].endsWith(SNIPPET_LABEL) === true;+}++// The runtime reads a missing, 0 or invalid line as unspecified.+const Line = Schema.optional(Schema.Unknown);+const decodeLine = Schema.decodeUnknownOption(PositiveInt);+const lineOf = (value: unknown) => Option.getOrUndefined(decodeLine(value));+const ReplacementChunk = Schema.Struct({+ TargetContent: Schema.String,+ ReplacementContent: Schema.String,+ StartLine: Line,+ EndLine: Line,+});+// replace_file_content sends one chunk at the top level; multi_replace_file_content sends a list.+const decodeEditInput = Schema.decodeUnknownOption(+ Schema.Union([+ Schema.Struct({ ReplacementChunks: Schema.NonEmptyArray(ReplacementChunk) }),+ ReplacementChunk,+ ]),+);+const decodeLocations = Schema.decodeUnknownOption(Schema.Array(Schema.Struct({ line: Line })));+// The runtime accepts edit arguments in either casing.+const PASCAL_KEYS: Readonly<Record<string, string>> = {+ replacement_chunks: "ReplacementChunks",+ target_content: "TargetContent",+ replacement_content: "ReplacementContent",+ start_line: "StartLine",+ end_line: "EndLine",+};+const pascalKeys = (value: unknown): unknown => {+ if (Array.isArray(value)) return value.map(pascalKeys);+ if (typeof value !== "object" || value === null) return value;+ const fields: Record<string, unknown> = value as Record<string, unknown>;+ const result: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(fields)) {+ const pascal = PASCAL_KEYS[key];+ // Like the runtime, a present PascalCase value wins over its snake_case alias.+ if (pascal === undefined) result[key] ??= pascalKeys(entry);+ else if (fields[pascal] == null) result[pascal] = pascalKeys(entry);+ }+ return result;+};++/** Reads a small file for snippet matching; edits to large or unreadable files stay unlocated. */+export function readAntigravityPreEditFile(path: string): string | undefined {+ try {+ const stat = NodeFS.statSync(path);+ return stat.isFile() && stat.size <= PRE_EDIT_FILE_LIMIT+ ? NodeFS.readFileSync(path, "utf8")+ : undefined;+ } catch {+ return undefined;+ }+}++/** The line of the snippet's only match starting within `from`..`to`, if it spans whole lines. */+function uniqueStartLine(+ text: string | undefined,+ snippet: string,+ from = 1,+ to = Number.POSITIVE_INFINITY,+): number | undefined {+ if (text === undefined || snippet === "") return undefined;+ let found: { readonly line: number; readonly whole: boolean } | undefined;+ let line = 1;+ let lineStart = 0;+ let nextBreak = text.indexOf("\n");+ for (let index = text.indexOf(snippet); index !== -1; index = text.indexOf(snippet, index + 1)) {+ while (nextBreak !== -1 && nextBreak < index) {+ line++;+ lineStart = nextBreak + 1;+ nextBreak = text.indexOf("\n", lineStart);+ }+ if (line > to) break;+ if (line < from) continue;+ if (found !== undefined) return undefined;+ const end = index + snippet.length;+ // A hunk replaces whole lines.+ const whole =+ index === lineStart && (end === text.length || snippet.endsWith("\n") || text[end] === "\n");+ found = { line, whole };+ }+ return found?.whole === true ? found.line : undefined;+}++function snippetHunks(+ oldText: string,+ newText: string,+ maxEditLength: number,+): StructuredPatchHunk[] | undefined {+ const before = oldText.replaceAll("\r\n", "\n");+ const after = newText.replaceAll("\r\n", "\n");+ // A target without its newline keeps the line's own newline, on both sides.+ const eol = before.endsWith("\n") ? "" : "\n";+ return structuredPatch("", "", before + eol, after + eol, undefined, undefined, {+ maxEditLength,+ })?.hunks;+}++const changedLines = (hunks: ReadonlyArray<StructuredPatchHunk>) =>+ hunks.reduce(+ (total, hunk) =>+ total + hunk.lines.filter((line) => line.startsWith("+") || line.startsWith("-")).length,+ 0,+ );++/**+ * Antigravity reports replacements as bare old/new snippets. `StartLine` only starts the+ * runtime's search range, so a chunk is placed at its unique match in the pre-edit file within+ * that range. All-unplaced chunks get hunks labeled as snippets; a mix is omitted.+ */+export function antigravityEditPatch(input: {+ readonly path: string;+ readonly rawInput: unknown;+ readonly locations?: unknown;+ /** Pass only while the edit is pending, when the file still holds the old text. */+ readonly readPreEditFile?: ((path: string) => string | undefined) | undefined;+}): string | typeof ANTIGRAVITY_EDIT_DIFF_OMITTED | undefined {+ const edit = Option.getOrUndefined(decodeEditInput(pascalKeys(input.rawInput)));+ if (edit === undefined) return undefined;+ const announced = lineOf(Option.getOrUndefined(decodeLocations(input.locations))?.[0]?.line);+ const listed = "ReplacementChunks" in edit ? edit.ReplacementChunks : [edit];+ const chunks = listed.map((chunk) => ({+ ...chunk,+ StartLine: lineOf(chunk.StartLine) ?? (listed.length === 1 ? announced : undefined),+ EndLine: lineOf(chunk.EndLine),+ }));+ let file: string | undefined;+ let fileRead = false;+ const textSize = chunks.reduce(+ (total, chunk) => total + chunk.TargetContent.length + chunk.ReplacementContent.length,+ 0,+ );+ if (textSize > EDIT_TEXT_BUDGET) return ANTIGRAVITY_EDIT_DIFF_OMITTED;+ let budget = EDIT_DIFF_BUDGET;+ const placed: Array<{ readonly start: number; readonly hunks: StructuredPatchHunk[] }> = [];+ const snippets: StructuredPatchHunk[] = [];+ for (const chunk of chunks) {+ // Whether a changed final line break, or a cleared line, splits, joins or removes lines+ // depends on what follows the match. Only a whole-line delete is certain.+ const targetEndsLine = chunk.TargetContent.endsWith("\n");+ if (+ chunk.ReplacementContent === ""+ ? !targetEndsLine+ : targetEndsLine !== chunk.ReplacementContent.endsWith("\n")+ )+ return ANTIGRAVITY_EDIT_DIFF_OMITTED;+ const hunks = snippetHunks(chunk.TargetContent, chunk.ReplacementContent, budget);+ // A change to the line ending alone leaves no LF hunk to show.+ if (+ hunks === undefined ||+ (hunks.length === 0 && chunk.TargetContent !== chunk.ReplacementContent)+ )+ return ANTIGRAVITY_EDIT_DIFF_OMITTED;+ budget -= changedLines(hunks);+ if (budget < 0) return ANTIGRAVITY_EDIT_DIFF_OMITTED;+ let start: number | undefined;+ if (input.readPreEditFile !== undefined) {+ // Line numbers do not depend on CRLF, so search with LF on both sides.+ if (!fileRead) file = input.readPreEditFile(input.path)?.replaceAll("\r\n", "\n");+ fileRead = true;+ start = uniqueStartLine(+ file,+ chunk.TargetContent.replaceAll("\r\n", "\n"),+ chunk.StartLine,+ chunk.EndLine,+ );+ }+ if (start === undefined) snippets.push(...hunks);+ else placed.push({ start, hunks });+ }+ // A placed hunk beside an unplaced one would still number the unplaced one from line 1.+ if (placed.length > 0 && snippets.length > 0) return ANTIGRAVITY_EDIT_DIFF_OMITTED;+ let shift = 0;+ const placedHunks = placed+ .toSorted((left, right) => left.start - right.start)+ .flatMap(({ start, hunks }) => {+ const shifted = hunks.map((hunk) => ({+ ...hunk,+ oldStart: hunk.oldStart + start - 1,+ newStart: hunk.newStart + start - 1 + shift,+ }));+ for (const hunk of hunks) shift += hunk.newLines - hunk.oldLines;+ return shifted;+ });+ const section = (hunks: StructuredPatchHunk[]) =>+ hunks.length === 0+ ? ""+ : formatPatch(+ {+ oldFileName: input.path,+ newFileName: input.path,+ oldHeader: undefined,+ newHeader: undefined,+ hunks,+ },+ FILE_HEADERS_ONLY,+ );+ const patch = [+ section(placedHunks),+ section(snippets).replace(/^@@ .* @@$/gm, `$&${SNIPPET_LABEL}`),+ ]+ .filter(Boolean)+ .join("\n");+ return patch || undefined;+}diff --git a/apps/server/src/provider/acp/AntigravityProfilePaths.ts b/apps/server/src/provider/acp/AntigravityProfilePaths.tsnew file mode 100644index 00000000000..eb5ef1fcac2--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityProfilePaths.ts@@ -0,0 +1,37 @@+// @effect-diagnostics nodeBuiltinImport:off -- lstat proves no managed component is a link.+import type * as NodeFS from "node:fs";+import * as NodeFSP from "node:fs/promises";+import * as NodePath from "node:path";++/**+ * Proves a native runtime entry is at its literal path below the canonical profile: every+ * component exists with the expected type and none is a link. A link could point at another+ * child's transcript or another session's database under the same profile.+ */+export async function antigravityManagedPath(+ profileRoot: string,+ segments: ReadonlyArray<string>,+ kind: "file" | "directory",+): Promise<{ readonly path: string; readonly info: NodeFS.Stats } | undefined> {+ let current = profileRoot;+ let info: NodeFS.Stats | undefined;+ for (const [index, segment] of segments.entries()) {+ current = NodePath.join(current, segment);+ info = await NodeFSP.lstat(current).catch(() => undefined);+ const expectFile = kind === "file" && index === segments.length - 1;+ if (+ info === undefined ||+ info.isSymbolicLink() ||+ (expectFile ? !info.isFile() : !info.isDirectory())+ ) {+ return undefined;+ }+ }+ if (info === undefined) return undefined;+ return (await NodeFSP.realpath(current).catch(() => undefined)) === current+ ? { path: current, info }+ : undefined;+}++export const antigravityProfileRoot = (profileDirectory: string) =>+ NodeFSP.realpath(profileDirectory).catch(() => undefined);diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.tsindex 909de58cb75..a2d7c86f4c2 100644--- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts+++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts@@ -19,6 +19,7 @@ import {mergeToolCallState,parseSessionUpdateEvent,} from "@t3tools/provider-acp/server/runtimeModel";+import { acpToolCallDiffPatch } from "@t3tools/provider-acp/server/adapter";const isSessionNotification = Schema.is(AcpWireSchema.SessionNotification);@@ -291,6 +292,135 @@ describe("Antigravity tool results", () => {expect(commandCompleted.update.rawOutput.formatted_output).toBe("after\n");});+ it("keeps the captured edit location through approval and completion", () => {+ const path = "/workspace/app.ts";+ const replace = {+ TargetContent: "const target = 10;",+ ReplacementContent: "const target = 100;",+ TargetFile: path,+ };+ const frame = (rawInput: Record<string, unknown>, line?: number) =>+ ({+ sessionId: "session-1",+ update: {+ sessionUpdate: "tool_call",+ toolCallId: "edit-1",+ title: "Run edit_file?",+ kind: "edit",+ status: "pending",+ content: [+ {+ type: "diff",+ path,+ oldText: replace.TargetContent,+ newText: replace.ReplacementContent,+ },+ ],+ locations: [line === undefined ? { path } : { path, line }],+ rawInput,+ },+ }) satisfies EffectAcpSchema.SessionNotification;+ const running = parseToolUpdate({+ sessionId: "session-1",+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "edit-1",+ kind: "edit",+ status: "in_progress",+ title: "Running edit_file",+ locations: [{ path }],+ rawInput: { file_path: path },+ },+ }).toolCall;+ const completed = parseToolUpdate({+ sessionId: "session-1",+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "edit-1",+ status: "completed",+ rawOutput: "Tool execution",+ },+ }).toolCall;+ const preEdit = Array.from({ length: 12 }, (_, i) =>+ i === 9 ? replace.TargetContent : `line ${i + 1}`,+ ).join("\n");+ const postEdit = preEdit.replace(replace.TargetContent, replace.ReplacementContent);+ for (const [pending, readFile] of [+ [frame({ ...replace, StartLine: 5, EndLine: 12 }, 5), () => preEdit],+ [frame(replace), () => preEdit],+ ] as const) {+ let toolCall = normalizeAntigravityToolCall(parseToolUpdate(pending).toolCall, readFile);+ for (const next of [running, completed]) {+ toolCall = normalizeAntigravityToolCall(mergeToolCallState(toolCall, next), () => postEdit);+ }+ expect(toolCall.status).toBe("completed");+ expect(acpToolCallDiffPatch(toolCall.data.content)).toBe(+ `--- ${path}\n+++ ${path}\n@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`,+ );+ }+ // Full-access edits arrive path-only; no hunk is offered instead of the tool's status text.+ let pathOnly = normalizeAntigravityToolCall(+ parseToolUpdate({+ sessionId: "session-1",+ update: {+ sessionUpdate: "tool_call",+ toolCallId: "edit-2",+ kind: "edit",+ status: "in_progress",+ title: "Running edit_file",+ locations: [{ path }],+ rawInput: { file_path: path },+ },+ }).toolCall,+ );+ pathOnly = normalizeAntigravityToolCall(mergeToolCallState(pathOnly, completed));+ expect(pathOnly.data.content).toEqual([{ type: "diff", patch: { format: "omitted" } }]);+ expect(acpToolCallDiffPatch(pathOnly.data.content)).toBeUndefined();+ // A captured patch that a later update's shared text budget cut or dropped is omitted.+ for (const patch of [{ text: "[Earlier output truncated]\n\n@@ -80,1 +80,1 @@" }, {}]) {+ const kept = normalizeAntigravityToolCall({+ toolCallId: "edit-cut",+ kind: "edit",+ status: "completed",+ data: { content: [{ type: "diff", path, patch }] },+ });+ expect(kept.data.content).toEqual([{ type: "diff", path, patch: { format: "omitted" } }]);+ }+ // A whole-file write whose old text was cut to its tail must not show the cut as deletions.+ const overwrite = normalizeAntigravityToolCall({+ toolCallId: "edit-overwrite",+ kind: "edit",+ status: "completed",+ data: {+ rawInput: { TargetFile: path, CodeContent: "one line\n" },+ content: [+ {+ type: "diff",+ path,+ oldText: "[Earlier output truncated]\n\nrow 999\n",+ newText: "one line\n",+ },+ ],+ },+ });+ expect(acpToolCallDiffPatch(overwrite.data.content)).toBeUndefined();+ // A patch too long to keep, or input cut to its tail, must not fall back to line-1 snippets.+ for (const width of [60, 120]) {+ const block = (value: string) =>+ Array.from({ length: 120 }, (_, i) => `${value} ${i} `.padEnd(width, "x")).join("\n");+ const long = {+ TargetContent: block("old"),+ ReplacementContent: block("new"),+ TargetFile: path,+ };+ const toolCall = normalizeAntigravityToolCall(+ parseToolUpdate(frame({ ...long, StartLine: 80, EndLine: 199 }, 80)).toolCall,+ );+ expect(toolCall.data.content).toMatchObject([{ patch: { format: "omitted" } }]);+ expect(acpToolCallDiffPatch(toolCall.data.content)).toBeUndefined();+ }+ });+it.each([{ CommandLine: "pwd", Cwd: "/one" },{ CommandLine: "pwd", WorkingDirectory: "/one" },diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.tsindex a91d45164ca..5b74756a1de 100644--- a/apps/server/src/provider/acp/AntigravityProtocol.ts+++ b/apps/server/src/provider/acp/AntigravityProtocol.ts@@ -12,6 +12,13 @@ import * as AcpWireSchema from "effect-acp/schema-v1";import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";+import {+ ANTIGRAVITY_EDIT_DIFF_OMITTED,+ antigravityEditPatch,+ isAntigravitySnippetPatch,+ readAntigravityPreEditFile,+} from "./AntigravityEditLocation.ts";+const TOOL_TEXT_LIMIT = 8_000;const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n";const QUESTION_LABEL_LIMIT = 512;@@ -163,6 +170,12 @@ function boundText(text: string, limit = TOOL_TEXT_LIMIT): string {: copyBoundedText(`${TOOL_TEXT_TRUNCATED}${text.slice(-limit)}`);}+/** Keeps the tail of long tool text, as every bounded tool payload does. */+export { boundText as boundAntigravityToolText };++/** True when bounding cut some of this text. */+export const isCutAntigravityToolText = (text: string) => text.includes(TOOL_TEXT_TRUNCATED);+interface ToolPayloadBudget {nodes: number;text: number;@@ -350,7 +363,58 @@ function localImagePath(imagePath: string | undefined): string | undefined {return /^[a-z][a-z\d+.-]*:/i.test(path) && !/^[a-z]:[\\/]/i.test(path) ? undefined : path;}-export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState {+function hasTruncatedText(value: unknown): boolean {+ if (typeof value === "string") return value.startsWith(TOOL_TEXT_TRUNCATED);+ return Predicate.isObject(value) && Object.values(value).some(hasTruncatedText);+}++/** The ACP adapter renders a diff's `patch.text` ahead of its bare old/new snippets. */+function withAntigravityEditPatches(+ content: ReadonlyArray<unknown>,+ data: Record<string, unknown>,+ readPreEditFile: ((path: string) => string | undefined) | undefined,+) {+ return content.map((entry) => {+ if (!Predicate.isObject(entry) || entry.type !== "diff" || typeof entry.path !== "string")+ return entry;+ // Keep the first patch: once the edit runs, the file no longer holds the old text. A later+ // update's shared text budget can cut or drop it, and a cut patch would misplace the hunk.+ if (entry.patch !== undefined) {+ const patch: unknown = entry.patch;+ const cut =+ Predicate.isObject(patch) &&+ patch.format !== "omitted" &&+ (typeof patch.text !== "string" || patch.text.startsWith(TOOL_TEXT_TRUNCATED));+ return cut ? { ...entry, patch: { format: "omitted" } } : entry;+ }+ // Bounding keeps only the tail of long text, so a cut snippet cannot be located and a cut+ // old or new text would render the cut as file content.+ if ([data.rawInput, entry.oldText, entry.newText].some(hasTruncatedText))+ return { ...entry, patch: { format: "omitted" } };+ const text = antigravityEditPatch({+ path: entry.path,+ rawInput: data.rawInput,+ locations: data.locations,+ readPreEditFile,+ });+ // A truncated patch would no longer parse, and bare snippets would render at line 1.+ if (+ text === ANTIGRAVITY_EDIT_DIFF_OMITTED ||+ (text !== undefined && text.length > TOOL_TEXT_LIMIT)+ )+ return { ...entry, patch: { format: "omitted" } };+ if (text === undefined) return entry;+ return {+ ...entry,+ patch: isAntigravitySnippetPatch(text) ? { format: "snippet", text } : { text },+ };+ });+}++export function normalizeAntigravityToolCall(+ toolCall: AcpToolCallState,+ readPreEditFile = readAntigravityPreEditFile,+): AcpToolCallState {const input = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawInput));const output = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawOutput));const nativeCommand =@@ -382,6 +446,17 @@ export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpTooif (command !== undefined) data.command = command;if (cwd !== undefined) data.cwd = cwd;if (imagePath !== undefined) data.imagePath = imagePath;+ if (kind === "edit") {+ const content = Array.isArray(data.content) ? data.content : [];+ // Full-access edits report only a path; without a hunk the checkpoint diff is the review.+ data.content = content.some((entry) => Predicate.isObject(entry) && entry.type === "diff")+ ? withAntigravityEditPatches(+ content,+ data,+ toolCall.status === "pending" ? readPreEditFile : undefined,+ )+ : [...content, { type: "diff", patch: { format: "omitted" } }];+ }if (kind === "execute") {data.item = {...(Predicate.isObject(data.item) ? data.item : {}),diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.tsnew file mode 100644index 00000000000..d3ca431c507--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts@@ -0,0 +1,195 @@+import * as NodeSqlite from "node:sqlite";++import * as NodeServices from "@effect/platform-node/NodeServices";+import { assert, describe, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Path from "effect/Path";+import type * as EffectAcpSchema from "effect-acp/compat";++import { watchAntigravityPromptOutcome } from "./AntigravityTurnOutcome.ts";++const USER_INPUT = 14;+const PLANNER_RESPONSE = 15;+const TOOL = 8;+const ERROR_MESSAGE = 17;++// Error-step payloads trimmed from Antigravity 1.4.5 against a local Gemini endpoint.+const errorPayload = (error: string) =>+ Buffer.concat([+ Buffer.from([0x0a, 0x24]),+ Buffer.from(+ `Agent execution terminated due to error.\u0012agent executor error: ${error}: ${error}\n(1) attached stack trace\n -- stack trace:`,+ ),+ ]);+// An unparsable reset timestamp must not hide the reset delay.+const QUOTA_ERROR = errorPayload(+ "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]]",+);+const INVALID_ARGUMENT_ERROR = errorPayload(+ "Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []",+);+// The model's reply quoting the agent's quota notice is an ordinary planner response.+const QUOTED_NOTICE = Buffer.from(+ "Usage Limit Reached\n\nYou have reached your current quota for this period. Your limit will reset in 1 hour.",+);++describe("watchAntigravityPromptOutcome", () => {+ it.effect("fails only turns whose own steps end in an upstream error", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const profileDirectory = yield* fs.makeTempDirectoryScoped();+ const sessionId = "e6aba774-5472-4277-b6ee-27b2e05570a7";+ const conversations = path.join(profileDirectory, "antigravity-acp", "conversations");+ yield* fs.makeDirectory(conversations, { recursive: true });+ let nextIndex = 0;+ const appendSteps = (steps: ReadonlyArray<readonly [number, Uint8Array]>) => {+ const database = new NodeSqlite.DatabaseSync(path.join(conversations, `${sessionId}.db`));+ try {+ database.exec(+ "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)",+ );+ const insert = database.prepare("INSERT INTO steps VALUES (?, ?, ?)");+ for (const [type, payload] of steps) insert.run(nextIndex++, type, payload);+ } finally {+ database.close();+ }+ };+ const turn = (+ steps: ReadonlyArray<readonly [number, Uint8Array]>,+ result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" },+ ) =>+ Effect.gen(function* () {+ const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId);+ appendSteps(steps);+ return yield* check(result);+ });+ const input = Buffer.from("Run the fixture.");+ const reply = Buffer.from("FIXTURE_OK");++ // The first prompt creates the session log.+ assert.isUndefined(+ yield* turn([+ [USER_INPUT, input],+ [PLANNER_RESPONSE, reply],+ ]),+ );+ assert.deepEqual(+ yield* turn([+ [USER_INPUT, input],+ [ERROR_MESSAGE, QUOTA_ERROR],+ ]),+ {+ class: "usage_limit",+ message: "You have reached your Antigravity quota for this period.",+ code: "RESOURCE_EXHAUSTED",+ retryable: true,+ resetAt: "1970-01-01T01:00:00.000Z",+ },+ );+ // The earlier error step is outside this turn.+ assert.isUndefined(+ yield* turn(+ [+ [USER_INPUT, input],+ [PLANNER_RESPONSE, QUOTED_NOTICE],+ ],+ {+ stopReason: "end_turn",+ usage: { inputTokens: 42, outputTokens: 3, totalTokens: 54 },+ },+ ),+ );+ assert.deepEqual(+ yield* turn([+ [USER_INPUT, input],+ [ERROR_MESSAGE, INVALID_ARGUMENT_ERROR],+ ]),+ {+ class: "provider_error",+ message: "Request contains an invalid argument.",+ code: "INVALID_ARGUMENT",+ retryable: false,+ },+ );+ // A completed tool keeps its usage, and the turn still fails.+ assert.equal(+ (yield* turn(+ [+ [USER_INPUT, input],+ [PLANNER_RESPONSE, reply],+ [TOOL, reply],+ [ERROR_MESSAGE, QUOTA_ERROR],+ ],+ {+ stopReason: "end_turn",+ usage: { inputTokens: 40, outputTokens: 5, totalTokens: 45 },+ },+ ))?.class,+ "usage_limit",+ );+ assert.isUndefined(+ yield* turn([+ [USER_INPUT, input],+ [PLANNER_RESPONSE, reply],+ ]),+ );+ // The agent maps the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.+ assert.deepEqual(yield* turn([], { stopReason: "refusal" }), {+ class: "usage_limit",+ message: "You have reached your Antigravity quota for this period.",+ code: "QUOTA_EXHAUSTED",+ retryable: true,+ });+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),+ );++ it.effect("reads only this session's own unlinked log, and keeps a typed refusal", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const profileDirectory = yield* fs.makeTempDirectoryScoped();+ const conversations = path.join(profileDirectory, "antigravity-acp", "conversations");+ yield* fs.makeDirectory(conversations, { recursive: true });+ const own = "e6aba774-5472-4277-b6ee-27b2e05570a7";+ const peer = "0d9c2b4e-1111-4222-8333-944455556666";+ const append = (sessionId: string, type: number, payload: Uint8Array) => {+ const database = new NodeSqlite.DatabaseSync(path.join(conversations, `${sessionId}.db`));+ try {+ database.exec(+ "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)",+ );+ database+ .prepare("INSERT INTO steps (step_type, step_payload) VALUES (?, ?)")+ .run(type, payload);+ } finally {+ database.close();+ }+ };++ // own.db links to a peer session; the peer's new error step is not this turn's.+ append(peer, USER_INPUT, Buffer.from("peer"));+ yield* fs.symlink(+ path.join(conversations, `${peer}.db`),+ path.join(conversations, `${own}.db`),+ );+ const linked = yield* watchAntigravityPromptOutcome(profileDirectory, own);+ append(peer, ERROR_MESSAGE, QUOTA_ERROR);+ assert.isUndefined(yield* linked({ stopReason: "end_turn" }));+ assert.equal((yield* linked({ stopReason: "refusal" }))?.class, "usage_limit");++ // An unreadable log gives no evidence, but the agent's typed refusal still fails the turn.+ yield* fs.remove(path.join(conversations, `${own}.db`));+ yield* fs.writeFileString(path.join(conversations, `${own}.db`), "not a database");+ const corrupt = yield* watchAntigravityPromptOutcome(profileDirectory, own);+ assert.isUndefined(yield* corrupt({ stopReason: "end_turn" }));+ assert.deepEqual(yield* corrupt({ stopReason: "refusal" }), {+ class: "usage_limit",+ message: "You have reached your Antigravity quota for this period.",+ code: "QUOTA_EXHAUSTED",+ retryable: true,+ });+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),+ );+});diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.tsnew file mode 100644index 00000000000..874c28eeb15--- /dev/null+++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts@@ -0,0 +1,194 @@+// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and lstat read the native session log.+import * as NodeFSP from "node:fs/promises";+import * as NodePath from "node:path";+import * as NodeSqlite from "node:sqlite";++import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts";+import { makeProviderFailure } from "@t3tools/provider-core/server/failure";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import type * as EffectAcpSchema from "effect-acp/compat";++import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";++// CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory.+const ERROR_STEP_TYPE = 17;+// The harness error text leads the payload; a Go stack trace follows it.+const MAX_ERROR_PAYLOAD_BYTES = 16_384;+// The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.+const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;+const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;+const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;+const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;+const GO_DURATION_PART = /(\d+(?:\.\d+)?)(ns|us|µs|μs|ms|h|m|s)/g;+const GO_DURATION_UNIT_MS: Record<string, number> = {+ ns: 1e-6,+ us: 1e-3,+ µs: 1e-3,+ μs: 1e-3,+ ms: 1,+ s: 1_000,+ m: 60_000,+ h: 3_600_000,+};+const NATIVE_SESSION_ID = /^[\w-]+$/;++interface LastStep {+ readonly type: number;+ readonly payload: Uint8Array | null;+}++const readSteps = <A>(file: string, read: (database: NodeSqlite.DatabaseSync) => A) =>+ Effect.try(() => {+ const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });+ try {+ database.exec("PRAGMA busy_timeout = 100");+ const hasSteps =+ database+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")+ .get() !== undefined;+ return hasSteps ? read(database) : undefined;+ } finally {+ database.close();+ }+ });++const lastStepIndex = (database: NodeSqlite.DatabaseSync) => {+ const index = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx;+ return typeof index === "number" ? index : -1;+};++const lastStepAfter =+ (index: number) =>+ (database: NodeSqlite.DatabaseSync): LastStep | undefined => {+ const row = database+ .prepare(+ `SELECT step_type AS type, substr(step_payload, 1, ?) AS payload+ FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1`,+ )+ .get(MAX_ERROR_PAYLOAD_BYTES, index);+ if (typeof row?.type !== "number") return undefined;+ return { type: row.type, payload: row.payload instanceof Uint8Array ? row.payload : null };+ };++function resetAtFrom(text: string, now: DateTime.Utc): string | undefined {+ // makeProviderFailure drops a timestamp that does not parse, so fall back to the delay.+ const timestamp = RESET_TIMESTAMP.exec(text)?.[1];+ if (timestamp !== undefined && Option.isSome(DateTime.make(timestamp))) return timestamp;+ const delay = RESET_DELAY.exec(text)?.[1];+ if (delay === undefined) return undefined;+ let delayMs = 0;+ for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) {+ delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0);+ }+ return delayMs > 0 ? DateTime.formatIso(DateTime.add(now, { milliseconds: delayMs })) : undefined;+}++function turnFailure(+ stopReason: EffectAcpSchema.StopReason,+ step: LastStep | undefined,+ now: DateTime.Utc,+): OrchestrationV2ProviderFailure | undefined {+ const errorText =+ step?.type === ERROR_STEP_TYPE+ ? new TextDecoder().decode(step.payload ?? new Uint8Array())+ : undefined;+ // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.+ if (errorText === undefined && stopReason !== "refusal") return undefined;+ const text = errorText ?? "";+ const apiError = API_ERROR.exec(text);+ if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) {+ return makeProviderFailure({+ class: "usage_limit",+ message: "You have reached your Antigravity quota for this period.",+ code: apiError?.[3] ?? "QUOTA_EXHAUSTED",+ retryable: true,+ resetAt: resetAtFrom(text, now) ?? null,+ });+ }+ if (apiError === null) {+ return makeProviderFailure({+ class: "provider_error",+ message: "Antigravity stopped this turn because of an error.",+ });+ }+ const [, httpStatus, message, status] = apiError;+ const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED";+ return makeProviderFailure({+ class: rateLimited ? "usage_limit" : "provider_error",+ message: message!.trim(),+ code: status ?? null,+ retryable: rateLimited || Number(httpStatus) >= 500,+ });+}++const conversationSegments = ["antigravity-acp", "conversations"];++/**+ * Antigravity reports an upstream API failure as a chat message and `end_turn`. Its+ * session log ends that turn with an error step, so the check reads only steps the+ * current prompt added, read-only, from this session's own unlinked database. Without+ * that evidence a typed `refusal` still fails the turn.+ */+export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.watch")(function* (+ profileDirectory: string,+ sessionId: string,+) {+ const typedOnly = (result: EffectAcpSchema.PromptResponse) =>+ DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now)));+ if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;+ const segments = [...conversationSegments, `${sessionId}.db`];+ const before = yield* Effect.tryPromise(async () => {+ const root = await antigravityProfileRoot(profileDirectory);+ if (root === undefined) return undefined;+ if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {+ return undefined;+ }+ const database = await antigravityManagedPath(root, segments, "file");+ // A path that exists but fails the proof is a link or other foreign entry.+ if (database === undefined) {+ const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(+ () => true,+ () => false,+ );+ return present ? undefined : { root, identity: undefined, startIndex: -1 };+ }+ return { root, identity: database.info, startIndex: undefined };+ }).pipe(Effect.orElseSucceed(() => undefined));+ if (before === undefined) {+ yield* Effect.logWarning("The Antigravity session log is not this session's own file.");+ return typedOnly;+ }+ const startIndex =+ before.startIndex ??+ (yield* readSteps(NodePath.join(before.root, ...segments), lastStepIndex).pipe(+ Effect.map((index) => index ?? -1),+ Effect.orElseSucceed(() => undefined),+ ));+ if (startIndex === undefined) {+ yield* Effect.logWarning("Could not read the Antigravity session log before the prompt.");+ return typedOnly;+ }+ return Effect.fn("AntigravityTurnOutcome.check")(function* (+ result: EffectAcpSchema.PromptResponse,+ ) {+ // The same file as before the prompt, or one this prompt created, still unlinked.+ const after = yield* Effect.tryPromise(() =>+ antigravityManagedPath(before.root, segments, "file"),+ ).pipe(Effect.orElseSucceed(() => undefined));+ const sameFile =+ after !== undefined &&+ (before.identity === undefined ||+ (after.info.dev === before.identity.dev && after.info.ino === before.identity.ino));+ const step = sameFile+ ? yield* readSteps(after.path, lastStepAfter(startIndex)).pipe(+ Effect.tapError(() =>+ Effect.logWarning("Could not read the Antigravity session log after the prompt."),+ ),+ Effect.orElseSucceed(() => undefined),+ )+ : undefined;+ return turnFailure(result.stopReason, step, yield* DateTime.now);+ });+});diff --git a/apps/server/src/provider/antigravityRelease.ts b/apps/server/src/provider/antigravityRelease.tsindex 17173760d5e..255a9276199 100644--- a/apps/server/src/provider/antigravityRelease.ts+++ b/apps/server/src/provider/antigravityRelease.ts@@ -1,5 +1,6 @@-// 1.4.2 through 1.4.4 write skills/system/run-workflow/SKILL.md into every session workspace.-const ANTIGRAVITY_RELEASE_VERSION = "1.4.1";+// Hashes and sizes match the official ACP registry release. Like 1.4.2 through 1.4.4, it writes a+// run-workflow skill into the workspace unless T3 disables the tool (antigravitySessionMeta).+const ANTIGRAVITY_RELEASE_VERSION = "1.4.5";export interface AntigravityReleaseAsset {readonly version: string;@@ -21,66 +22,66 @@ const releaseAssets = new Map<string, AntigravityReleaseAsset>(["darwin-arm64",{version: ANTIGRAVITY_RELEASE_VERSION,- url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.1-darwin-arm64.zip",- sha256: "f9bdd68291ae78c38d2141e63bc86b84e6cc7b9f60f71652c68435a7943deb17",- archiveBytes: 112_737_434,- executable: { name: "agy_acp_server.par", bytes: 280_996_576 },- harness: { name: "localharness_external", bytes: 120_246_928 },+ url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-arm64.zip",+ sha256: "886fff7767d08994ca39eb02c3d01a7532c7325a94aa33aaf52d52068733284f",+ archiveBytes: 97_923_855,+ executable: { name: "agy_acp_server.par", bytes: 178_915_920 },+ harness: { name: "localharness_external", bytes: 122_957_936 },},],["darwin-x64",{version: ANTIGRAVITY_RELEASE_VERSION,- url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.1-darwin-x86_64.zip",- sha256: "27e31f096874704f14167b07ef9e84cc77134615ee41d024f7b1c957add85307",- archiveBytes: 118_349_036,- executable: { name: "agy_acp_server.par", bytes: 285_186_624 },- harness: { name: "localharness_external", bytes: 124_910_048 },+ url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-x86_64.zip",+ sha256: "b39f3573c03b9acb9df028853f647527f1f3133f32bd77e78b796e48a205114a",+ archiveBytes: 103_577_295,+ executable: { name: "agy_acp_server.par", bytes: 183_127_600 },+ harness: { name: "localharness_external", bytes: 127_612_208 },},],["linux-x64",{version: ANTIGRAVITY_RELEASE_VERSION,- url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.1-linux-x86_64.zip",- sha256: "2e37012ceb2a5c7fc7309b6e6596234fb637ee3c62a5199f65d4cbe777871384",- archiveBytes: 336_170_339,- executable: { name: "agy_acp_server.par", bytes: 930_826_753 },- harness: { name: "localharness_external", bytes: 131_187_512 },+ url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-x86_64.zip",+ sha256: "923923a0d7dc8073f66cc6f78647a3107e3a7ee2b7e1a24df8b3927b5188013b",+ archiveBytes: 321_783_181,+ executable: { name: "agy_acp_server.par", bytes: 826_226_766 },+ harness: { name: "localharness_external", bytes: 133_926_136 },},],["linux-arm64",{version: ANTIGRAVITY_RELEASE_VERSION,- url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.1-linux-arm64.zip",- sha256: "609336a1c97545487e3ddd55dbd153dc0f40f4e6534486cc1c5f4c0ebb85c2da",- archiveBytes: 321_922_507,- executable: { name: "agy_acp_server.par", bytes: 933_416_796 },- harness: { name: "localharness_external", bytes: 124_895_000 },+ url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-arm64.zip",+ sha256: "7d64246633ae094f67e3bbcd2d679e89048f91346d5339313336e7483f40f056",+ archiveBytes: 307_829_008,+ executable: { name: "agy_acp_server.par", bytes: 831_194_025 },+ harness: { name: "localharness_external", bytes: 127_512_832 },},],["win32-x64",{version: ANTIGRAVITY_RELEASE_VERSION,- url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.1-windows-x86_64.zip",- sha256: "5f5b7d0328df17c128b2be338d4567b0d24e56ace8196e88794fec37d1372554",- archiveBytes: 129_599_308,- executable: { name: "agy_acp_server.exe", bytes: 86_098_784 },- harness: { name: "localharness_external.exe", bytes: 146_036_888 },+ url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-x86_64.zip",+ sha256: "d24f4c73c9f96d4f44384e281c855a56c72d8eaa9c5b0fad7ccb1635c6b63f50",+ archiveBytes: 100_423_655,+ executable: { name: "agy_acp_server.exe", bytes: 55_839_864 },+ harness: { name: "localharness_external.exe", bytes: 147_843_736 },},],["win32-arm64",{version: ANTIGRAVITY_RELEASE_VERSION,- url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.1-windows-arm64.zip",- sha256: "24c52bbc12aae20f55eb53d373669412d95a9c44fd59be4ea4e355918b91fbf7",- archiveBytes: 132_507_344,- executable: { name: "agy_acp_server.exe", bytes: 93_197_744 },- harness: { name: "localharness_external.exe", bytes: 136_970_904 },+ url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-arm64.zip",+ sha256: "ab0a9aac8349e08ef289be6d16da8f89e3abe60eba5158032ef78c4a1220261c",+ archiveBytes: 102_703_121,+ executable: { name: "agy_acp_server.exe", bytes: 62_293_488 },+ harness: { name: "localharness_external.exe", bytes: 139_322_008 },},],]);diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.jsonindex 87ed61776ea..59753c7f514 100644--- a/apps/server/src/provider/model-manifest.json+++ b/apps/server/src/provider/model-manifest.json@@ -75,8 +75,9 @@{"driver": "antigravity","t3CodeRange": ">=0.0.42",- "recommendedRange": "=1.4.1",+ "recommendedRange": "=1.4.5 || =1.4.1","ranges": [+ { "range": "=1.4.5", "status": "supported" },{ "range": "=1.4.1", "status": "supported" },{ "range": "=1.3.0", "status": "supported" },{ "range": "=1.1.1", "status": "supported" }diff --git a/apps/server/src/provider/providerCompatibility.test.ts b/apps/server/src/provider/providerCompatibility.test.tsindex 8575a73230f..928acfb4807 100644--- a/apps/server/src/provider/providerCompatibility.test.ts+++ b/apps/server/src/provider/providerCompatibility.test.ts@@ -133,18 +133,24 @@ describe("provider compatibility", () => {}});- it("supports the managed Antigravity runtime in the bundled manifest", () => {- const policies = decodeCompatibilityPolicies(bundledManifest.compatibility);- const release = resolveAntigravityReleaseAsset("darwin", "arm64");- assert.strictEqual(- resolveProviderCompatibility(- policies,- ProviderDriverKind.make("antigravity"),- `agy_acp_server_${release?.version}`,- )?.status,- "supported",- );- });+ it.each([+ ["darwin", "arm64"],+ ["win32", "x64"],+ ] as const)(+ "supports the managed Antigravity runtime for %s-%s in the bundled manifest",+ (platform, arch) => {+ const policies = decodeCompatibilityPolicies(bundledManifest.compatibility);+ const release = resolveAntigravityReleaseAsset(platform, arch);+ assert.strictEqual(+ resolveProviderCompatibility(+ policies,+ ProviderDriverKind.make("antigravity"),+ `agy_acp_server_${release?.version}`,+ )?.status,+ "supported",+ );+ },+ );it("classifies boundaries and treats unlisted versions and release tags as unknown", () => {for (const [version, expected] of [diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 9d7dc2f27b1..67418010e38 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -59,6 +59,7 @@ import * as ProviderHostLive from "./provider/ProviderHostLive.ts";import * as DocumentText from "./provider/DocumentText.ts";import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";+import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";@@ -570,10 +571,10 @@ const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe(),);-const layerOrchestrationApplication = CheckpointDiffQuery.layer.pipe(- Layer.provideMerge(layerCheckpointStore),- Layer.provideMerge(layerOrchestrationV2Runtime),-);+const layerOrchestrationApplication = Layer.merge(+ CheckpointDiffQuery.layer,+ NativeChildWorkQuery.layer,+).pipe(Layer.provideMerge(layerCheckpointStore), Layer.provideMerge(layerOrchestrationV2Runtime));const layerThreadSettlementWorker = Layer.effectDiscard(ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())),diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex 97ed92fe21b..40eebbf4825 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -41,6 +41,7 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";+import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";import * as CodexInstallation from "./provider/CodexInstallation.ts";import * as DeviceService from "./device/DeviceService.ts";@@ -541,6 +542,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }),Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}),+ Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}),Layer.mock(CommandOutputHub.CommandOutputHub)({}),Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }),Layer.mock(DeviceService.DeviceService)({}),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex cc06273187a..e880551e65c 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -109,6 +109,7 @@ import {import { RpcGroup, RpcSerialization, RpcServer } from "effect/rpc";import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";+import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";import * as ServerConfig from "./config.ts";import * as EnvironmentTheme from "./environmentTheme.ts";import * as Keybindings from "./keybindings.ts";@@ -1350,6 +1351,7 @@ export const layerWsRpc = (const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter;const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;+ const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery;const keybindings = yield* Keybindings.Keybindings;const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;const externalLauncher = yield* ExternalLauncher.ExternalLauncher;@@ -1965,6 +1967,8 @@ export const layerWsRpc = (threadManagement.forceStopThread(input),[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) =>readWorkflowScript({ scriptPath: input.scriptPath }),+ [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: (input) =>+ nativeChildWork.getNativeChildWork(input),[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) =>threadManagement.getTurnItem(input).pipe(Effect.mapError(diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 6cd1c7775d9..6fd54db6bd5 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -270,6 +270,7 @@ import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";import { useCitedHistory } from "./chat/citationProcedure";import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";import { ThreadTimeline } from "./chat/ThreadTimeline";+import { NativeChildWorkDialog } from "./chat/NativeChildWorkDialog";import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";import { getTriggerDisplayModelName } from "./chat/providerIconUtils";import { resolveScrollToEndClearance } from "./composerFooterLayout";@@ -3560,6 +3561,14 @@ export default function ChatView(props: ChatViewProps) {effortLabel={providerSubagentEffortLabel}status={providerSubagentStatus}onOpenParent={parentThreadLink?.open ?? null}+ actions={+ selectedProviderEntry?.driverKind === "antigravity" ? (+ <NativeChildWorkDialog+ environmentId={environmentId}+ threadId={threadId}+ />+ ) : null+ }/>) : null}{!composerMounted ? null : (diff --git a/apps/web/src/components/chat/NativeChildWorkDialog.tsx b/apps/web/src/components/chat/NativeChildWorkDialog.tsxnew file mode 100644index 00000000000..7695a0e38c6--- /dev/null+++ b/apps/web/src/components/chat/NativeChildWorkDialog.tsx@@ -0,0 +1,131 @@+import type {+ EnvironmentId,+ OrchestrationV2GetNativeChildWorkResult,+ OrchestrationV2NativeChildStep,+ OrchestrationV2NativeChildWork,+ ThreadId,+} from "@t3tools/contracts";+import { ListTreeIcon } from "lucide-react";+import { useState } from "react";++import { orchestrationEnvironment } from "../../state/orchestration";+import { useEnvironmentQuery } from "../../state/query";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";++const stepLabel = (type: string) => {+ const words = type.toLowerCase().replaceAll("_", " ");+ return words.charAt(0).toUpperCase() + words.slice(1);+};++/** Read-only view of what a provider-native subagent's children did. Loads only while open. */+export function NativeChildWorkDialog(props: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+}) {+ const [open, setOpen] = useState(false);+ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <Button size="sm" variant="ghost" onClick={() => setOpen(true)}>+ <ListTreeIcon />+ <span className="@max-[420px]/composer-surface:sr-only">Subagent work</span>+ </Button>+ <DialogPopup className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Subagent work</DialogTitle>+ <DialogDescription>Read only. These subagents cannot take messages.</DialogDescription>+ </DialogHeader>+ {open ? <NativeChildWorkContent {...props} /> : null}+ </DialogPopup>+ </Dialog>+ );+}++function NativeChildWorkContent(props: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+}) {+ const query = useEnvironmentQuery<OrchestrationV2GetNativeChildWorkResult, unknown>(+ orchestrationEnvironment.nativeChildWork({+ environmentId: props.environmentId,+ input: { threadId: props.threadId },+ }),+ );+ const children = query.data?.children;+ return (+ <>+ <DialogPanel>+ {query.error !== null ? (+ <p className="text-sm text-destructive-foreground">{query.error}</p>+ ) : children === undefined ? (+ <p className="text-sm text-muted-foreground">Loading…</p>+ ) : children.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ The provider has no record of which subagents this call started.+ </p>+ ) : (+ children.map((child) => <NativeChild key={child.conversationId} child={child} />)+ )}+ </DialogPanel>+ <DialogFooter variant="bare">+ <Button size="sm" variant="outline" disabled={query.isPending} onClick={query.refresh}>+ Refresh+ </Button>+ </DialogFooter>+ </>+ );+}++function NativeChild(props: { readonly child: OrchestrationV2NativeChildWork }) {+ const { child } = props;+ return (+ <section aria-label={child.role || "Subagent"} className="flex min-w-0 flex-col gap-2">+ <h3 className="text-sm font-medium text-foreground">{child.role || "Subagent"}</h3>+ <p className="whitespace-pre-wrap break-words text-sm text-muted-foreground">+ {child.prompt}+ </p>+ {child.truncated ? (+ <p className="text-xs text-muted-foreground">Earlier steps are not shown.</p>+ ) : null}+ {child.steps === null ? (+ <p className="text-xs text-muted-foreground">No transcript yet.</p>+ ) : (+ <ol className="m-0 flex list-none flex-col gap-2 border-s ps-3">+ {child.steps.map((step) => (+ <NativeChildStep key={step.index} step={step} />+ ))}+ </ol>+ )}+ </section>+ );+}++function NativeChildStep(props: { readonly step: OrchestrationV2NativeChildStep }) {+ const { step } = props;+ return (+ <li className="flex min-w-0 flex-col gap-1">+ <span className="text-xs font-medium text-muted-foreground">+ {stepLabel(step.type)}+ {step.status !== null && step.status !== "DONE" ? ` · ${stepLabel(step.status)}` : ""}+ </span>+ {step.toolCalls.length === 0 ? null : (+ <code className="whitespace-pre-wrap break-all text-xs text-foreground">+ {step.toolCalls.map((call) => `${call.name} ${call.input}`).join("\n")}+ </code>+ )}+ {step.text === null ? null : (+ <pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground">+ {step.text}+ </pre>+ )}+ </li>+ );+}diff --git a/apps/web/src/components/chat/ProviderSubagentBar.tsx b/apps/web/src/components/chat/ProviderSubagentBar.tsxindex 6aa8799c70b..1b74e43284f 100644--- a/apps/web/src/components/chat/ProviderSubagentBar.tsx+++ b/apps/web/src/components/chat/ProviderSubagentBar.tsx@@ -4,6 +4,7 @@ import {} from "@t3tools/client-runtime/state/thread-execution";import { isOrchestrationV2WorkActive } from "@t3tools/contracts";import { ArrowUpLeftIcon } from "lucide-react";+import type { ReactNode } from "react";import { tickTextContent } from "~/lib/tickTextContent";import type { ProviderInstanceEntry } from "../../providerInstances";@@ -17,6 +18,7 @@ export function ProviderSubagentBar(props: {readonly effortLabel: string | null;readonly status: ProviderSubagentStatus | null;readonly onOpenParent: (() => void) | null;+ readonly actions?: ReactNode;}) {const { status } = props;const live = status !== null && isOrchestrationV2WorkActive(status.status);@@ -64,6 +66,7 @@ export function ProviderSubagentBar(props: {<span className="shrink-0 text-muted-foreground @max-[640px]/composer-surface:sr-only">Runs on its own</span>+ {props.actions}{props.onOpenParent ? (<Button size="sm" variant="ghost" onClick={props.onOpenParent}><ArrowUpLeftIcon />diff --git a/docs/user/composer.md b/docs/user/composer.mdindex e0c8e69bab6..a3e06c9aed6 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -37,7 +37,8 @@ Attach up to 100 files per message. Each image can be up to 10 MiB, with at most50 MiB each, subject to the environment's upload support and limit. The agentreceives them on the environment's machine. Provider and model limits stillapply, including images already in the conversation. A video attachment gives-the agent a file path; it does not enable native video input.+the agent a file path; only [Antigravity](./providers-antigravity.md#skills-and-attachments)+sends supported videos to Gemini models as video.Uploads begin when you add an attachment. All uploads must finish before themessage can send. Retry or remove a failed upload. On web and desktop, reloadingdiff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.mdindex b951695ba10..9a62a65efdc 100644--- a/docs/user/providers-antigravity.md+++ b/docs/user/providers-antigravity.md@@ -101,16 +101,20 @@ Skills for every project go in `~/.gemini/config/skills` or`~/.gemini/antigravity-cli/skills`. Antigravity does not read `~/.agents/skills`,so a skill there only appears when the project itself is your home directory.-Antigravity receives images directly. Every other attachment, including PDFs,-text, audio, archives, and videos, is passed as a saved file path for the agent-to inspect with its tools. A video path does not enable native video input.+Antigravity receives images and audio directly, and reads PDFs and text files as+documents. With the managed runtime on macOS and Linux, an MP4 video up to 20 MiB+is sent as video to Gemini models. Other attachments, and videos for other models, are passed as a+saved file path for the agent to inspect with its tools.### Subagents-Antigravity groups subagent activity into batches. You cannot open or control-individual subagents, and an idle batch does not confirm that every child-succeeded. See [agent work](./thread-sidebar.md#inspect-agent-work) for where to-inspect activity.+Antigravity groups subagent activity into batches. Open a batch and select+**Subagent work** (**Work** on mobile) to read each child's role, prompt, and recent steps. This view+is read only: you cannot message or control individual subagents, and an idle+batch does not confirm that every child succeeded. If Antigravity did not record+which children a batch started, the view says so. See+[agent work](./thread-sidebar.md#inspect-agent-work) for where to inspect+activity.## Accounts and removaldiff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex 5f5c2ce3020..94dc18582a5 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -103,6 +103,13 @@ export function createOrchestrationEnvironmentAtoms<R, E>(staleTimeMs: 300_000,idleTtlMs: 300_000,}),+ // Mounted only while a subagent inspector is open; running children change between opens.+ nativeChildWork: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:orchestration:native-child-work",+ tag: ORCHESTRATION_V2_WS_METHODS.getNativeChildWork,+ staleTimeMs: 0,+ idleTtlMs: 0,+ }),stopWorkflow: createEnvironmentRpcCommand(runtime, {label: "environment-data:orchestration:stop-workflow",tag: ORCHESTRATION_V2_WS_METHODS.stopWorkflow,diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 6734e9d55f2..837721aa7f6 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -3568,6 +3568,7 @@ export const ORCHESTRATION_V2_WS_METHODS = {getOlderSettledThreads: "orchestration.getOlderSettledThreads",getThreadProjection: "orchestration.getThreadProjection",getWorkflowScript: "orchestration.getWorkflowScript",+ getNativeChildWork: "orchestration.getNativeChildWork",stopWorkflow: "orchestration.stopWorkflow",forceStopThread: "orchestration.forceStopThread",getTurnItem: "orchestration.getTurnItem",@@ -4007,6 +4008,53 @@ export const OrchestrationV2GetWorkflowScriptResult = Schema.Struct({export type OrchestrationV2GetWorkflowScriptResult =typeof OrchestrationV2GetWorkflowScriptResult.Type;+/** Names a provider-native subagent's child thread. */+export const OrchestrationV2GetNativeChildWorkInput = Schema.Struct({+ threadId: ThreadId,+});+export type OrchestrationV2GetNativeChildWorkInput =+ typeof OrchestrationV2GetNativeChildWorkInput.Type;++export const OrchestrationV2NativeChildStep = Schema.Struct({+ index: NonNegativeInt,+ type: Schema.String,+ status: Schema.NullOr(Schema.String),+ text: Schema.NullOr(Schema.String),+ toolCalls: Schema.Array(Schema.Struct({ name: Schema.String, input: Schema.String })),+});+export type OrchestrationV2NativeChildStep = typeof OrchestrationV2NativeChildStep.Type;++/** Read-only: native children cannot take messages. */+export const OrchestrationV2NativeChildWork = Schema.Struct({+ conversationId: TrimmedNonEmptyString,+ role: Schema.String,+ prompt: Schema.String,+ /** Null when the provider has no readable transcript for this child. */+ steps: Schema.NullOr(Schema.Array(OrchestrationV2NativeChildStep)),+ /** Earlier steps were left out to keep the read bounded. */+ truncated: Schema.Boolean,+});+export type OrchestrationV2NativeChildWork = typeof OrchestrationV2NativeChildWork.Type;++/** Empty when the provider's records do not prove which children the subagent launched. */+export const OrchestrationV2GetNativeChildWorkResult = Schema.Struct({+ children: Schema.Array(OrchestrationV2NativeChildWork),+});+export type OrchestrationV2GetNativeChildWorkResult =+ typeof OrchestrationV2GetNativeChildWorkResult.Type;++export class OrchestrationV2GetNativeChildWorkError extends Schema.TaggedError<OrchestrationV2GetNativeChildWorkError>()(+ "OrchestrationV2GetNativeChildWorkError",+ {+ threadId: ThreadId,+ cause: Schema.optional(Schema.Defect()),+ },+) {+ override get message(): string {+ return "Failed to read the subagent's work.";+ }+}+const WORKFLOW_FILE_ERROR_MESSAGES = {"invalid-path": "Workflow files must be absolute paths with the expected extension.","root-unavailable": "Workflow file root unavailable.",@@ -4186,6 +4234,10 @@ export const OrchestrationV2RpcSchemas = {input: OrchestrationV2GetWorkflowScriptInput,output: OrchestrationV2GetWorkflowScriptResult,},+ getNativeChildWork: {+ input: OrchestrationV2GetNativeChildWorkInput,+ output: OrchestrationV2GetNativeChildWorkResult,+ },getTurnItem: {input: OrchestrationV2GetTurnItemInput,output: OrchestrationV2GetTurnItemResult,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 37ea5866ae7..01989ff8a47 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -221,6 +221,7 @@ import {import {ORCHESTRATION_V2_WS_METHODS,OrchestrationGetWorkflowScriptError,+ OrchestrationV2GetNativeChildWorkError,OrchestrationV2StopWorkflowError,OrchestrationV2ForceStopThreadError,OrchestrationV2DispatchCommandError,@@ -1816,6 +1817,15 @@ const WsOrchestrationV2GetWorkflowScriptRpc = Rpc.make(},);+const WsOrchestrationV2GetNativeChildWorkRpc = Rpc.make(+ ORCHESTRATION_V2_WS_METHODS.getNativeChildWork,+ {+ payload: OrchestrationV2RpcSchemas.getNativeChildWork.input,+ success: OrchestrationV2RpcSchemas.getNativeChildWork.output,+ error: Schema.Union([OrchestrationV2GetNativeChildWorkError, EnvironmentAuthorizationError]),+ },+);+const WsOrchestrationV2GetTurnItemRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.getTurnItem, {payload: OrchestrationV2RpcSchemas.getTurnItem.input,success: OrchestrationV2RpcSchemas.getTurnItem.output,@@ -2161,6 +2171,7 @@ export const WsRpcGroup = RpcGroup.make(WsSubscribeResourceTelemetryRpc,WsOrchestrationV2DispatchCommandRpc,WsOrchestrationV2GetWorkflowScriptRpc,+ WsOrchestrationV2GetNativeChildWorkRpc,WsOrchestrationV2StopWorkflowRpc,WsOrchestrationV2ForceStopThreadRpc,WsOrchestrationV2GetTurnItemRpc,diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.tsindex 71e6f93b49f..4544a4ac5ce 100644--- a/packages/provider-acp/src/server/AcpSessionRuntime.ts+++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts@@ -123,7 +123,12 @@ export interface AcpSessionRuntimeOptions {/** Authenticate before opening: Antigravity selects its credential source from the method. */readonly authenticateEagerly?: boolean;readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;+ /** Sent on every session/new, load, resume and fork; omitting them clears an agent's stored roots. */readonly additionalDirectories?: ReadonlyArray<string>;+ /** Session `_meta`, chosen from the negotiated agent before each session setup or activation. */+ readonly sessionMeta?: (+ initializeResult: EffectAcpSchema.InitializeResponse,+ ) => EffectAcpSchema.NewSessionRequest["_meta"] | undefined;readonly transformStdout?: EffectAcpClient.AcpClientOptions["transformStdout"];readonly transformSessionUpdate?: (notification: EffectAcpSchema.SessionNotification,@@ -2108,6 +2113,16 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (return activationOptions?.mcpServers ?? options.mcpServers ?? [];};+ const sessionSetupFields = (initializeResult: EffectAcpSchema.InitializeResponse) => {+ const meta = options.sessionMeta?.(initializeResult);+ return {+ ...(options.additionalDirectories?.length+ ? { additionalDirectories: options.additionalDirectories }+ : {}),+ ...(meta == null ? {} : { _meta: meta }),+ };+ };+const startOnce = Effect.gen(function* () {const initializeResult = yield* initialize;@@ -2163,9 +2178,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (| EffectAcpSchema.LoadSessionResponse| EffectAcpSchema.NewSessionResponse| EffectAcpSchema.ResumeSessionResponse;- const additionalDirectories = options.additionalDirectories?.length- ? { additionalDirectories: options.additionalDirectories }- : {};+ const additionalDirectories = sessionSetupFields(initializeResult);if (options.resumeSessionId) {sessionId = options.resumeSessionId;if (@@ -2400,6 +2413,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (const requestPayload = {sessionId,cwd: options.cwd,+ ...sessionSetupFields(started.initializeResult),mcpServers: sessionMcpServers(started.initializeResult, activationOptions),} satisfies EffectAcpSchema.LoadSessionRequest;return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);@@ -2412,6 +2426,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (const requestPayload = {sessionId,cwd: options.cwd,+ ...sessionSetupFields(started.initializeResult),mcpServers: sessionMcpServers(started.initializeResult, activationOptions),} satisfies EffectAcpSchema.ResumeSessionRequest;return runLoggedRequest(@@ -2428,6 +2443,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (const requestPayload = {sessionId,cwd: options.cwd,+ ...sessionSetupFields(started.initializeResult),mcpServers: sessionMcpServers(started.initializeResult, activationOptions),} satisfies EffectAcpSchema.ForkSessionRequest;return runLoggedRequest(diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex 7b24d9ef09a..b7c77c40495 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -235,28 +235,35 @@ export function acpPerTurnPromptUsage(usage: EffectAcpSchema.Usage | null | undefined,hasSubagents: boolean,terminalStatus: OrchestrationV2ProviderTurn["status"],+ geminiUsage = false,): TurnTokenUsage {if (usage == null) {return { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents };}+ const inputTokens = geminiUsage+ ? usage.inputTokens + (usage.cachedReadTokens ?? 0)+ : usage.inputTokens;+ const outputTokens = geminiUsage+ ? usage.outputTokens + (usage.thoughtTokens ?? 0)+ : usage.outputTokens;// TurnTokenUsage contract: input includes cache read + write and reasoning// is a subset of output, so clamp counters that exceed their parent and// drop the ones the agent left unset. Cache writes are capped at whatever// cache reads leave of input, so the pair cannot exceed it.const clampSubset = (value: number | null | undefined, parent: number) =>value == null ? undefined : Math.min(value, parent);- const cachedInputTokens = clampSubset(usage.cachedReadTokens, usage.inputTokens);+ const cachedInputTokens = clampSubset(usage.cachedReadTokens, inputTokens);const cacheCreationTokens = clampSubset(usage.cachedWriteTokens,- usage.inputTokens - (cachedInputTokens ?? 0),+ inputTokens - (cachedInputTokens ?? 0),);- const reasoningTokens = clampSubset(usage.thoughtTokens, usage.outputTokens);+ const reasoningTokens = clampSubset(usage.thoughtTokens, outputTokens);return {usageScope: "main_agent",usageStatus: terminalStatus === "completed" ? "complete" : "partial",hasSubagents,- inputTokens: usage.inputTokens,- outputTokens: usage.outputTokens,+ inputTokens,+ outputTokens,...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),...(cacheCreationTokens === undefined ? {} : { cacheCreationTokens }),...(reasoningTokens === undefined ? {} : { reasoningTokens }),@@ -267,9 +274,25 @@ export interface AcpAdapterV2Flavor {readonly buildPrompt?: (input: {readonly text: string;readonly attachments: ReadonlyArray<ChatAttachment>;+ readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];+ readonly agentVersion: string | undefined;+ /** The session's model after selection, with its display name when the agent lists it. */+ readonly currentModel: { readonly id: string; readonly name: string | undefined } | undefined;}) => Effect.Effect<ReadonlyArray<EffectAcpSchema.ContentBlock>, EffectAcpErrors.AcpError>;readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;+ /**+ * Runs before `session/prompt`. The returned check sees a prompt the agent ended+ * without an error or cancel, and reports a failure its stop reason hid. A reported+ * failure restarts the runtime before the next turn.+ */+ readonly watchPromptOutcome?: (+ sessionId: string,+ ) => Effect.Effect<+ (+ result: EffectAcpSchema.PromptResponse,+ ) => Effect.Effect<OrchestrationV2ProviderFailure | undefined>+ >;readonly requiresSignIn?: (cause: unknown) => boolean;/*** Runs before attachment paths, T3 instructions and native slash-command detection,@@ -412,6 +435,8 @@ export interface AcpAdapterV2Flavor {* leaves usage semantics open, so this stays unset until proven live.*/readonly reportsPerTurnPromptUsage?: boolean;+ /** Gemini-style usage: inputTokens leaves out cachedReadTokens, outputTokens leaves out thoughtTokens. */+ readonly geminiPromptUsage?: boolean;/** Grok can retain task_already_running until process exit. */readonly restartRuntimeAfterInterrupt?: boolean;/** Prompt failures after which the agent process keeps failing until replaced. */@@ -428,6 +453,13 @@ export interface AcpAdapterV2Flavor {* fail before `session/prompt`.*/readonly supportsImagePrompts?: boolean;+ /**+ * True when this session's native system prompt carries T3's PR-linking instructions, so+ * turns omit them. Must use the same negotiated check that sent them on session setup.+ */+ readonly sessionCarriesPullRequestLinking?: (+ initializeResult: EffectAcpSchema.InitializeResponse,+ ) => boolean;}function acpSupportsImagePrompts(input: {@@ -909,12 +941,45 @@ function structuredFileChanges(toolCall: AcpToolCallState) {// Bound diff search to protect the event loop; empty-sided diffs need no search.const ACP_V1_DIFF_MAX_EDITS = 1_000;-export function acpToolCallDiffPatch(content: unknown): string | undefined {+/**+ * A `snippet` patch has no known location. Keep its recorded text, so no view numbers it+ * from line 1.+ */+export function acpToolCallSnippetEdit(content: unknown) {if (!Array.isArray(content)) return undefined;const diffs = content.flatMap((entry) => {const diff = unknownRecord(entry);return diff?.type === "diff" ? [diff] : [];});+ const diff = diffs.length === 1 ? diffs[0] : undefined;+ if (diff === undefined || unknownRecord(diff.patch)?.format !== "snippet") return undefined;+ return typeof diff.oldText === "string" && typeof diff.newText === "string"+ ? { oldStr: diff.oldText, newStr: diff.newText }+ : undefined;+}++/**+ * No preview when a flavor marked a diff `omitted` (too large) or `snippet` (line unknown);+ * the checkpoint diff shows it.+ */+function acpToolCallDiffUnpreviewable(content: unknown): boolean {+ return (+ Array.isArray(content) &&+ content.some((entry) => {+ const format = unknownRecord(unknownRecord(entry)?.patch)?.format;+ return format === "omitted" || format === "snippet";+ })+ );+}++export function acpToolCallDiffPatch(content: unknown): string | undefined {+ if (!Array.isArray(content) || acpToolCallDiffUnpreviewable(content)) {+ return undefined;+ }+ const diffs = content.flatMap((entry) => {+ const diff = unknownRecord(entry);+ return diff?.type === "diff" ? [diff] : [];+ });for (const diff of diffs) {const patch = unknownRecord(diff.patch);if (typeof patch?.text === "string") {@@ -3916,14 +3981,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}case "edit":case "delete":- case "move":+ case "move": {+ const snippet = acpToolCallSnippetEdit(toolCall.data.content);+ const unpreviewable = acpToolCallDiffUnpreviewable(toolCall.data.content);turnItem = {...base,type: "file_change",fileName: path ?? toolCall.title ?? "File change",- ...(diffText === undefined ? {} : { diffStr: diffText }),+ ...(snippet ??+ (unpreviewable || diffText === undefined ? {} : { diffStr: diffText })),};break;+ }case "fetch": {// Grok rawOutput.Content is unreadable by textFromUnknown; bounded content blocks duplicate it.const snippet =@@ -7092,6 +7161,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (context.promptUsage,context.subagents.size > 0,status,+ flavor.geminiPromptUsage,),}),});@@ -7409,11 +7479,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}if (flavor.buildPrompt) {const setup = yield* Ref.get(activeSessionSetup);+ const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);+ const currentModelId = modelOption?.currentValue;const blocks = yield* flavor.buildPrompt({text,attachments: turnInput.message.attachments,+ resolveAttachmentPath: host.resolveAttachmentPath,promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities,+ agentVersion: setup?.initializeResult.agentInfo?.version,+ currentModel:+ typeof currentModelId !== "string" || modelOption === undefined+ ? undefined+ : {+ id: currentModelId,+ name: flattenSelectChoices(modelOption.options).find(+ (choice) => choice.value === currentModelId,+ )?.name,+ },}).pipe(Effect.mapError(@@ -7459,11 +7542,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (});}if (!isNativeSlashCommand) {+ const sessionSetup = yield* Ref.get(activeSessionSetup);prompt.push({type: "text",text: buildRuntimeInstructions({harness: flavor.runtimeHarness ?? driver,model: turnInput.modelSelection.model,+ pullRequestLinking:+ sessionSetup === null ||+ flavor.sessionCarriesPullRequestLinking?.(sessionSetup.initializeResult) !== true,}),});}@@ -7778,6 +7865,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}return;}+ const checkPromptOutcome =+ flavor.watchPromptOutcome === undefined+ ? undefined+ : yield* flavor.watchPromptOutcome(requestedSessionId);const promptGeneration = yield* Ref.get(runtimeCallbackGeneration);yield* runtime.prompt({ prompt: promptParts!.prompt }).pipe(Effect.tap(() =>@@ -7824,13 +7915,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (if (context.finalized || followsAgentWorkState) return;// ACP v2 reports a failed prompt as an idle `error`, not an RPC error.const idleError = result.stopReason === "error" && !context.interrupted;- const status = idleError- ? "failed"- : result.stopReason === "cancelled"- ? context.interrupted- ? "interrupted"- : "cancelled"- : "completed";+ const hiddenFailure =+ checkPromptOutcome === undefined ||+ context.interrupted ||+ result.stopReason === "error" ||+ result.stopReason === "cancelled"+ ? undefined+ : yield* checkPromptOutcome(result);+ if (hiddenFailure !== undefined) {+ yield* Ref.set(runtimeRestartRequired, true);+ }+ const failure =+ hiddenFailure ?? (idleError ? idleErrorFailure(result.error) : undefined);+ const status =+ failure !== undefined+ ? "failed"+ : result.stopReason === "cancelled"+ ? context.interrupted+ ? "interrupted"+ : "cancelled"+ : "completed";if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {context.promptSettled = true;context.promptSettledStatus = status;@@ -7839,11 +7943,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (yield* finishRegisteredBackgroundTool({ taskId, ...completion });}}- if (idleError) {+ if (failure !== undefined) {yield* terminalizeOpenForegroundTools(context, "failed");// Unlike an RPC failure, the agent survives an idle error, so its// background tools and subagents keep reporting to this run.- yield* finalizeTurn(context, "failed", idleErrorFailure(result.error), {+ yield* finalizeTurn(context, "failed", failure, {childTurnsContinue: hasSurvivingBackgroundWork(context),});return;diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.tsindex 7e1edeb2ac0..bbc4aadb23f 100644--- a/packages/provider-core/src/server/runtimeInstructions.test.ts+++ b/packages/provider-core/src/server/runtimeInstructions.test.ts@@ -3,6 +3,17 @@ import { assert, describe, it } from "@effect/vitest";import { buildRuntimeInstructions } from "./runtimeInstructions.ts";describe("buildRuntimeInstructions", () => {+ it("leaves PR linking to a session that already carries it, and keeps runtime identity", () => {+ const instructions = buildRuntimeInstructions({+ harness: "Antigravity",+ model: "gemini-3.8-flash",+ pullRequestLinking: false,+ });++ assert.include(instructions, "through the Antigravity harness, as gemini-3.8-flash.");+ assert.notInclude(instructions, "<pull_request_linking>");+ });+it("links PRs the agent creates, takes over, or pushes to, and no others", () => {const instructions = buildRuntimeInstructions({ harness: "Codex" });diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.tsindex 7f7dba43c2b..3a65db1f950 100644--- a/packages/provider-core/src/server/runtimeInstructions.ts+++ b/packages/provider-core/src/server/runtimeInstructions.ts@@ -1,4 +1,5 @@-const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>+/** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */+export const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>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.</pull_request_linking>`;@@ -8,6 +9,8 @@ export function buildRuntimeInstructions(runtime: {readonly model?: string | undefined;readonly modelName?: string | undefined;readonly reasoningEffort?: string | undefined;+ /** False when the session's system prompt already carries the linking instructions. */+ readonly pullRequestLinking?: boolean;}): string {const harness = toSingleLine(runtime.harness);const model = toSingleLine(runtime.model ?? "");@@ -17,7 +20,10 @@ export function buildRuntimeInstructions(runtime: {modelName && modelName !== model ? `${modelName} (model slug: ${model})` : model;const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : "";const effortInfo = effort ? ` with ${effort} reasoning effort` : "";- 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}`;+ 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>`;+ return runtime.pullRequestLinking === false+ ? runtimeInfo+ : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`;}function toSingleLine(value: string): string {