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