Open History to see the last commit
1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 type AntigravityAuthMethod,
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
6 type ProviderSendTurnInput,
7 type RuntimeMode,
8} from "@t3tools/contracts";
9import * as SecureRandom from "effect/crypto/SecureRandom";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Predicate from "effect/Predicate";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import * as EffectAcpErrors from "effect-acp/errors";
19import type * as EffectAcpSchema from "effect-acp/compat";
20
21import {
22 makeAntigravityStderrHandler,
23 makeAntigravityStdoutTransform,
24} from "../antigravityAuthSupport.ts";
25import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
26import {
27 acpPermissionDisposition,
28 unknownRecord,
29 type AcpRuntimePolicy,
30} from "@t3tools/provider-acp/server/clientPolicy";
31import type { AcpSessionModeState } from "@t3tools/provider-acp/server/runtimeModel";
32import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation";
33import packageJson from "../../../package.json" with { type: "json" };
34import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts";
35
36export interface AntigravityAcpRuntimeInput extends Omit<
37 AcpSessionRuntime.AcpSessionRuntimeOptions,
38 | "authMethodId"
39 | "authenticateEagerly"
40 | "cancelBehavior"
41 | "clientCapabilities"
42 | "clientInfo"
43 | "onStderr"
44 | "resumeMethod"
45 | "sessionMeta"
46 | "transformSessionUpdate"
47 | "transformStdout"
48> {
49 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
50 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
51 /** Serve `fs/read_text_file` from T3 instead of the agent's native reader. */
52 readonly clientFileReads?: boolean;
53 readonly clientCapabilities?: AcpSessionRuntime.AcpSessionRuntimeOptions["clientCapabilities"];
54 /** The installed version, known before `initialize`; it picks the client name. */
55 readonly runtimeVersion?: string | null;
56 /** Conversational sessions only; helpers and probes leave the system prompt untouched. */
57 readonly sessionSystemPromptAppend?: string;
58 readonly authMethod?: AntigravityAuthMethod;
59}
60
61function parseAntigravityVersion(version: string | null | undefined) {
62 const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version?.trim() ?? "");
63 return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
64}
65
66function compareVersions(left: ReadonlyArray<number>, right: ReadonlyArray<number>) {
67 for (let index = 0; index < 3; index++) {
68 const difference = (left[index] ?? 0) - (right[index] ?? 0);
69 if (difference !== 0) return difference;
70 }
71 return 0;
72}
73
74// `agy acp` 1.5.1 offers every model to every ACP client; older runtimes allowlist editors.
75const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const;
76// `agy acp` 1.5.0 steers a running turn with the next prompt; the 1.4 harness queues it.
77const PROMPT_STEERING_RELEASE = [1, 5, 0] as const;
78
79export const antigravitySteersWithPrompt = (
80 initializeResult: EffectAcpSchema.InitializeResponse,
81) => {
82 const parsed = parseAntigravityVersion(initializeResult.agentInfo?.version);
83 return parsed !== undefined && compareVersions(parsed, PROMPT_STEERING_RELEASE) >= 0;
84};
85
86export const antigravityAppendsSystemPrompt = (
87 initializeResult: EffectAcpSchema.InitializeResponse,
88) => {
89 const extension = initializeResult.agentCapabilities?._meta?.antigravity;
90 return (
91 Predicate.isObject(extension) &&
92 Predicate.isObject(extension.systemPrompt) &&
93 extension.systemPrompt.append === true
94 );
95};
96
97export function antigravitySessionMeta(
98 initializeResult: EffectAcpSchema.InitializeResponse,
99 systemPromptAppend?: string,
100): EffectAcpSchema.NewSessionRequest["_meta"] | undefined {
101 return systemPromptAppend !== undefined && antigravityAppendsSystemPrompt(initializeResult)
102 ? { antigravity: { systemPrompt: { append: systemPromptAppend } } }
103 : undefined;
104}
105
106/** Older releases offer non-Gemini models only to allowlisted clients such as Zed. */
107export function antigravityClientInfo(version: string | null | undefined) {
108 const parsed = parseAntigravityVersion(version);
109 return parsed !== undefined && compareVersions(parsed, OPEN_MODEL_ACCESS_RELEASE) >= 0
110 ? { name: "t3-code", title: "T3 Code", version: packageJson.version }
111 : { name: "zed", version: "0.0.0" };
112}
113
114export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(function* (
115 input: AntigravityAcpRuntimeInput,
116): Effect.fn.Return<
117 AcpSessionRuntime.AcpSessionRuntime["Service"],
118 EffectAcpErrors.AcpError,
119 SecureRandom.SecureRandom | Scope.Scope
120> {
121 const context = yield* Layer.build(
122 AcpSessionRuntime.layer({
123 ...input,
124 authMethodId: input.authMethod ?? "oauth-personal",
125 authenticateEagerly: true,
126 resumeMethod: "resume",
127 cancelBehavior: "wait-for-prompt",
128 clientInfo: antigravityClientInfo(input.runtimeVersion),
129 sessionMeta: (initializeResult) =>
130 antigravitySessionMeta(initializeResult, input.sessionSystemPromptAppend),
131 clientCapabilities: {
132 ...input.clientCapabilities,
133 // Advertising writes swaps the agent's diff edits for whole-file client_edit_file.
134 fs: {
135 readTextFile: input.clientFileReads === true,
136 writeTextFile: false,
137 },
138 terminal: false,
139 },
140 transformStdout: makeAntigravityStdoutTransform(
141 input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},
142 ),
143 onStderr: makeAntigravityStderrHandler(
144 input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},
145 ),
146 transformSessionUpdate: normalizeAntigravitySessionUpdate,
147 }).pipe(
148 Layer.provide(
149 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
150 ),
151 ),
152 );
153 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context));
154});
155
156export function antigravityPermissionMode(runtimeMode: RuntimeMode): string {
157 switch (runtimeMode) {
158 case "full-access":
159 return "yolo";
160 case "auto-accept-edits":
161 return "auto_edit";
162 case "auto":
163 return "auto";
164 case "approval-required":
165 return "default";
166 }
167}
168
169/**
170 * The agy CLI rejects `yolo` and `auto_edit`, and sessions without native Auto reject `auto`.
171 * Those stay in `default`, where it asks before acting and T3 answers from the live runtime
172 * policy, so permission changes apply on the next turn without a restart.
173 */
174export function antigravitySessionMode(
175 modeId: string,
176 modeState: AcpSessionModeState | undefined,
177): string {
178 if (modeId === "auto") {
179 return modeState?.availableModes.some((mode) => mode.id === "auto") === true
180 ? "auto"
181 : "default";
182 }
183 return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId;
184}
185
186// Only calls that name T3's server: before agy 1.5.8 "Running <tool>" names no server, so another
187// MCP server's tool of the same name would pass.
188const ANTIGRAVITY_T3_MCP_TITLE = /^Run mcp_t3-code_(?<tool>[A-Za-z0-9_]+)\??$/;
189
190function isAntigravityT3McpRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean {
191 const rawInput = unknownRecord(request.toolCall.rawInput);
192 if (rawInput?.ServerName !== undefined) {
193 return (
194 rawInput.ServerName === "t3-code" &&
195 typeof rawInput.ToolName === "string" &&
196 T3_MCP_TOOL_NAMES.has(rawInput.ToolName)
197 );
198 }
199 if (typeof rawInput?.CommandLine === "string") return false;
200 const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(request.toolCall.title?.trim() ?? "")?.groups?.tool;
201 return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool);
202}
203
204export function antigravityPermissionDisposition(
205 policy: AcpRuntimePolicy,
206 request: EffectAcpSchema.RequestPermissionRequest,
207) {
208 const disposition = acpPermissionDisposition(policy, request);
209 if (disposition === "deny") return "deny";
210 // T3 authorizes its own MCP server, so Auto and Auto-accept edits run it unasked, as Claude does.
211 if (
212 (policy.runtimeMode === "auto" || policy.runtimeMode === "auto-accept-edits") &&
213 (policy.approvalPolicy === undefined || policy.approvalPolicy === "never") &&
214 isAntigravityT3McpRequest(request)
215 ) {
216 return "allow";
217 }
218 // agy's Auto has already reviewed what it sends; the user decides unless the sandbox forbids it.
219 return policy.runtimeMode === "auto" ? "ask" : disposition;
220}
221
222/** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */
223export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMode | undefined {
224 switch (modeId) {
225 case "yolo":
226 return "full-access";
227 case "auto_edit":
228 return "auto-accept-edits";
229 case "auto":
230 return "auto";
231 case "default":
232 return "approval-required";
233 default:
234 return undefined;
235 }
236}
237
238export function antigravityModelOptions(
239 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
240) {
241 const model = configOptions.find((option) => option.id === "model");
242 if (model?.type !== "select") return [];
243 return model.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options));
244}
245
246/** Runtime 1.4 reports thinking as its own option; 1.3 encoded it in the model ID. */
247export function antigravityThinkingConfig(
248 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
249) {
250 const option = configOptions?.find((candidate) => candidate.category === "thought_level");
251 return option?.type === "select" ? option : undefined;
252}
253
254/**
255 * Runtime 1.4 lists `gemini-3.8-flash` where 1.3 listed `gemini-3.8-flash-high`. The agent
256 * still accepts the old IDs, so pass them through; the current model may have no thinking option.
257 */
258function legacyAntigravityFamily(
259 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
260 model: string,
261) {
262 return antigravityModelOptions(configOptions)
263 .map((option) => option.value)
264 .filter((family) => model.startsWith(`${family}-`))
265 .toSorted((left, right) => right.length - left.length)[0];
266}
267
268function resolveAntigravityModel(input: {
269 readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
270 readonly model: string | null | undefined;
271 readonly defaultModel?: string | undefined;
272}): string | undefined {
273 const modelConfig = input.configOptions.find((option) => option.id === "model");
274 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
275 if (input.model && input.model !== ANTIGRAVITY_DEFAULT_MODEL) return input.model;
276 const options = antigravityModelOptions(input.configOptions);
277 return input.defaultModel &&
278 (options.some((option) => option.value === input.defaultModel) ||
279 legacyAntigravityFamily(input.configOptions, input.defaultModel) !== undefined)
280 ? input.defaultModel
281 : current;
282}
283
284/** Never replace a saved selection with the default returned by a cold resume. */
285export const applyAntigravityAcpModelSelection = Effect.fn("applyAntigravityAcpModelSelection")(
286 function* <E>(input: {
287 readonly runtime: Pick<
288 AcpSessionRuntime.AcpSessionRuntime["Service"],
289 "getConfigOptions" | "setModel" | "setConfigOption"
290 >;
291 readonly model: string | null | undefined;
292 readonly defaultModel?: string | undefined;
293 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
294 }): Effect.fn.Return<string | undefined, E> {
295 const configOptions = yield* input.runtime.getConfigOptions;
296 const modelConfig = configOptions.find((option) => option.id === "model");
297 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
298 const resolved = resolveAntigravityModel({
299 configOptions,
300 model: input.model,
301 defaultModel: input.defaultModel,
302 });
303 const explicit = Boolean(input.model) && input.model !== ANTIGRAVITY_DEFAULT_MODEL;
304 if (resolved === undefined || (!explicit && resolved === current)) return current;
305 const options = antigravityModelOptions(configOptions);
306 const legacyFamily = options.some((option) => option.value === resolved)
307 ? undefined
308 : legacyAntigravityFamily(configOptions, resolved);
309 if (legacyFamily !== undefined) {
310 yield* input.runtime
311 .setConfigOption("model", resolved, { allowUnlistedValue: true })
312 .pipe(Effect.mapError(input.mapError));
313 return legacyFamily;
314 }
315 if (!options.some((option) => option.value === resolved)) {
316 return yield* Effect.fail(
317 input.mapError(
318 EffectAcpErrors.AcpRequestError.invalidParams(
319 `Antigravity model '${resolved}' is unavailable for this Google account. Select an available model.`,
320 ),
321 ),
322 );
323 }
324 yield* input.runtime.setModel(resolved).pipe(Effect.mapError(input.mapError));
325 return resolved;
326 },
327);
328
329const IMAGE_MIME_TYPES = new Set(["image/bmp", "image/jpeg", "image/png", "image/webp"]);
330const AUDIO_MIME_TYPES = new Set([
331 "audio/aac",
332 "audio/flac",
333 "audio/mp3",
334 "audio/mpeg",
335 "audio/mp4",
336 "audio/m4a",
337 "audio/x-m4a",
338 "audio/ogg",
339 "audio/wav",
340 "audio/x-wav",
341 "audio/webm",
342]);
343const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024;
344const TEXT_MIME_TYPES = new Set([
345 "application/json",
346 "application/ld+json",
347 "application/javascript",
348 "application/typescript",
349 "application/xml",
350 "application/yaml",
351 "application/x-yaml",
352 "application/x-sh",
353]);
354const TEXT_FILE_EXTENSIONS = new Set([
355 ".txt",
356 ".md",
357 ".mdx",
358 ".json",
359 ".jsonl",
360 ".yaml",
361 ".yml",
362 ".toml",
363 ".xml",
364 ".csv",
365 ".tsv",
366 ".js",
367 ".jsx",
368 ".mjs",
369 ".cjs",
370 ".ts",
371 ".tsx",
372 ".html",
373 ".css",
374 ".scss",
375 ".less",
376 ".py",
377 ".rs",
378 ".go",
379 ".java",
380 ".kt",
381 ".swift",
382 ".c",
383 ".h",
384 ".cc",
385 ".cpp",
386 ".hpp",
387 ".cs",
388 ".rb",
389 ".php",
390 ".sh",
391 ".bash",
392 ".zsh",
393 ".sql",
394 ".graphql",
395 ".svelte",
396 ".vue",
397 ".log",
398 ".diff",
399 ".patch",
400 ".ini",
401 ".conf",
402]);
403const ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES = 1024 * 1024;
404const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;
405
406export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {
407 readonly input: ProviderSendTurnInput["input"];
408 readonly attachments: ProviderSendTurnInput["attachments"];
409 readonly resolveAttachmentPath: (
410 attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number],
411 ) => string | null;
412 readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
413}): Effect.fn.Return<
414 ReadonlyArray<EffectAcpSchema.ContentBlock>,
415 EffectAcpErrors.AcpError,
416 FileSystem.FileSystem | Path.Path
417> {
418 const fileSystem = yield* FileSystem.FileSystem;
419 const path = yield* Path.Path;
420 const blocks: Array<EffectAcpSchema.ContentBlock> = [];
421 const text = input.input?.trim();
422 if (text) blocks.push({ type: "text", text });
423 let totalBytes = 0;
424
425 for (const attachment of input.attachments ?? []) {
426 const isPastedText =
427 attachment.type === "file" &&
428 "source" in attachment &&
429 attachment.source?._tag === "pasted-text";
430 // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file.
431 const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? "";
432 const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);
433 const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);
434 const pdf = attachment.type === "file" && mimeType === "application/pdf";
435 const textFile =
436 attachment.type === "file" &&
437 (mimeType.startsWith("text/") ||
438 TEXT_MIME_TYPES.has(mimeType) ||
439 TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
440 const isPathOnly =
441 (attachment.type === "image" && (!image || input.promptCapabilities?.image !== true)) ||
442 (attachment.type === "file" &&
443 (isPastedText ||
444 (audio
445 ? input.promptCapabilities?.audio !== true
446 : !(pdf || textFile) || input.promptCapabilities?.embeddedContext !== true)));
447 const attachmentPath = input.resolveAttachmentPath(attachment);
448 if (!attachmentPath) {
449 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
450 `Invalid attachment '${attachment.name}'.`,
451 );
452 }
453 const info = yield* fileSystem
454 .stat(attachmentPath)
455 .pipe(
456 Effect.mapError(() =>
457 EffectAcpErrors.AcpRequestError.invalidParams(
458 `Could not read attachment '${attachment.name}'.`,
459 ),
460 ),
461 );
462 if (info.type !== "File") {
463 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
464 `Could not read attachment '${attachment.name}'.`,
465 );
466 }
467 if (isPathOnly) continue;
468 const size = Number(info.size);
469 const limit = image
470 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
471 : audio
472 ? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES
473 : pdf
474 ? MAX_TOTAL_ATTACHMENT_BYTES
475 : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;
476 if (
477 attachment.type === "file" &&
478 (size > limit || totalBytes + size > MAX_TOTAL_ATTACHMENT_BYTES)
479 ) {
480 continue;
481 }
482 totalBytes += size;
483 if (size > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
484 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
485 `Image '${attachment.name}' is too large. Antigravity accepts images up to 10 MiB and 50 MiB of native attachments per message.`,
486 );
487 }
488 const uri = yield* path.toFileUrl(attachmentPath).pipe(
489 Effect.map((url) => url.href),
490 Effect.mapError(() =>
491 EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`),
492 ),
493 );
494 if (pdf) {
495 blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType, size });
496 continue;
497 }
498 const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe(
499 Stream.runCollect,
500 Effect.map((chunks) => Buffer.concat(chunks)),
501 Effect.mapError(() =>
502 EffectAcpErrors.AcpRequestError.invalidParams(
503 `Could not read attachment '${attachment.name}'.`,
504 ),
505 ),
506 );
507 totalBytes += bytes.length - size;
508 if (bytes.length > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
509 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
510 `Attachment '${attachment.name}' changed while being read and is too large.`,
511 );
512 }
513 if (image) {
514 blocks.push({ type: "image", data: Buffer.from(bytes).toString("base64"), mimeType });
515 } else if (audio) {
516 blocks.push({ type: "audio", data: Buffer.from(bytes).toString("base64"), mimeType });
517 } else {
518 const encoding =
519 bytes[0] === 0xff && bytes[1] === 0xfe
520 ? "UTF-16LE"
521 : bytes[0] === 0xfe && bytes[1] === 0xff
522 ? "UTF-16BE"
523 : "UTF-8";
524 const decoded = yield* Effect.try({
525 try: () => new TextDecoder(encoding, { fatal: true }).decode(bytes),
526 catch: () =>
527 EffectAcpErrors.AcpRequestError.invalidParams(
528 `Attachment '${attachment.name}' is not a ${encoding} text file.`,
529 ),
530 });
531 if (decoded.includes("\0")) {
532 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
533 `Attachment '${attachment.name}' contains binary data.`,
534 );
535 }
536 blocks.push({ type: "resource", resource: { uri, mimeType, text: decoded } });
537 }
538 }
539 if (blocks.length === 0) {
540 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
541 "A turn requires text or supported attachments.",
542 );
543 }
544 return blocks;
545});