Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityAcpSupport.ts

548 lines19.8 KB

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