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