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 Crypto from "effect/Crypto";
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 Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
17import * as EffectAcpErrors from "effect-acp/errors";
18import type * as EffectAcpSchema from "effect-acp/schema";
19
20import { resolveAttachmentPath } from "../../attachmentStore.ts";
21import {
22 makeAntigravityStderrHandler,
23 makeAntigravityStdoutTransform,
24} from "../antigravityAuthSupport.ts";
25import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
26import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts";
27
28export interface AntigravityAcpRuntimeInput extends Omit<
29 AcpSessionRuntime.AcpSessionRuntimeOptions,
30 | "authMethodId"
31 | "cancelBehavior"
32 | "clientCapabilities"
33 | "onStderr"
34 | "resumeMethod"
35 | "transformSessionUpdate"
36 | "transformStdout"
37> {
38 /** Device CLI environment supplied for this provider session. */
39 readonly agentDeviceEnvironment?: Readonly<Record<string, string>>;
40 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
41 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
42 /**
43 * Advertise `fs.readTextFile` and `fs.writeTextFile`. The agent then routes
44 * workspace reads and writes through T3, which turns each edit into a
45 * `session/request_permission` with the file content, instead of writing
46 * through its own tools. Chat sessions turn this on. Setup, probe, and text
47 * generation helpers leave it off so they never touch a workspace.
48 */
49 readonly clientFileSystem?: boolean;
50 /** ACP `authenticate` method id. Defaults to the personal Google account flow. */
51 readonly authMethod?: AntigravityAuthMethod;
52}
53
54/** Normal launches reject browser login; only the auth flow supplies `onAuthorizationUrl`. */
55export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(function* (
56 input: AntigravityAcpRuntimeInput,
57): Effect.fn.Return<
58 AcpSessionRuntime.AcpSessionRuntime["Service"],
59 EffectAcpErrors.AcpError,
60 Crypto.Crypto | Scope.Scope
61> {
62 const context = yield* Layer.build(
63 AcpSessionRuntime.layer({
64 ...input,
65 authMethodId: input.authMethod ?? "oauth-personal",
66 resumeMethod: "resume",
67 cancelBehavior: "wait-for-prompt",
68 clientCapabilities: {
69 fs: {
70 readTextFile: input.clientFileSystem === true,
71 writeTextFile: input.clientFileSystem === true,
72 },
73 terminal: false,
74 },
75 transformStdout: makeAntigravityStdoutTransform(
76 input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},
77 ),
78 onStderr: makeAntigravityStderrHandler(
79 input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},
80 ),
81 transformSessionUpdate: normalizeAntigravitySessionUpdate,
82 }).pipe(
83 Layer.provide(
84 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
85 ),
86 ),
87 );
88 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context));
89});
90
91export function antigravityPermissionMode(runtimeMode: RuntimeMode): string {
92 switch (runtimeMode) {
93 case "full-access":
94 return "yolo";
95 case "auto-accept-edits":
96 return "auto_edit";
97 case "auto":
98 case "approval-required":
99 return "default";
100 }
101}
102
103export function antigravityModelOptions(
104 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
105) {
106 const model = configOptions.find((option) => option.id === "model");
107 if (model?.type !== "select") return [];
108 return model.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options));
109}
110
111/**
112 * Resolves the model a turn should run on. A saved selection is reapplied
113 * as-is. The provider default alias resolves to `defaultModel` when the
114 * account offers it, so T3 can pick a newer model than the one Google marks
115 * current. Otherwise the agent's current selection stands.
116 */
117export function resolveAntigravityModel(input: {
118 readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
119 readonly model: string | null | undefined;
120 readonly defaultModel?: string | undefined;
121}): string | undefined {
122 const modelConfig = input.configOptions.find((option) => option.id === "model");
123 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
124 if (input.model && input.model !== ANTIGRAVITY_DEFAULT_MODEL) return input.model;
125 const options = antigravityModelOptions(input.configOptions);
126 return input.defaultModel && options.some((option) => option.value === input.defaultModel)
127 ? input.defaultModel
128 : current;
129}
130
131/** Never replace a saved selection with the default returned by a cold resume. */
132export const applyAntigravityAcpModelSelection = Effect.fn("applyAntigravityAcpModelSelection")(
133 function* <E>(input: {
134 readonly runtime: Pick<
135 AcpSessionRuntime.AcpSessionRuntime["Service"],
136 "getConfigOptions" | "setModel"
137 >;
138 readonly model: string | null | undefined;
139 /** Model to select for the provider default alias. See `resolveAntigravityModel`. */
140 readonly defaultModel?: string | undefined;
141 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
142 }): Effect.fn.Return<string | undefined, E> {
143 const configOptions = yield* input.runtime.getConfigOptions;
144 const modelConfig = configOptions.find((option) => option.id === "model");
145 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
146 const resolved = resolveAntigravityModel({
147 configOptions,
148 model: input.model,
149 defaultModel: input.defaultModel,
150 });
151 // The default alias never sends an internal ID. It selects the manifest
152 // default when that differs from the agent's current model, and otherwise
153 // leaves the agent's choice alone.
154 const explicit = Boolean(input.model) && input.model !== ANTIGRAVITY_DEFAULT_MODEL;
155 if (resolved === undefined || (!explicit && resolved === current)) return current;
156 const options = antigravityModelOptions(configOptions);
157 if (!options.some((option) => option.value === resolved)) {
158 return yield* Effect.fail(
159 input.mapError(
160 EffectAcpErrors.AcpRequestError.invalidParams(
161 `Antigravity model '${resolved}' is unavailable for this Google account. Select an available model.`,
162 ),
163 ),
164 );
165 }
166 yield* input.runtime.setModel(resolved).pipe(Effect.mapError(input.mapError));
167 return resolved;
168 },
169);
170
171const IMAGE_MIME_TYPES = new Set(["image/bmp", "image/jpeg", "image/png", "image/webp"]);
172// Formats the bundled SDK's Audio type accepts. Anything else is rejected up front.
173const AUDIO_MIME_TYPES = new Set([
174 "audio/aac",
175 "audio/flac",
176 "audio/mp3",
177 "audio/mpeg",
178 "audio/mp4",
179 "audio/m4a",
180 "audio/x-m4a",
181 "audio/ogg",
182 "audio/wav",
183 "audio/x-wav",
184 "audio/webm",
185]);
186const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024;
187const TEXT_MIME_TYPES = new Set([
188 "application/json",
189 "application/ld+json",
190 "application/javascript",
191 "application/typescript",
192 "application/xml",
193 "application/yaml",
194 "application/x-yaml",
195 "application/x-sh",
196]);
197const TEXT_FILE_EXTENSIONS = new Set([
198 ".txt",
199 ".md",
200 ".mdx",
201 ".json",
202 ".jsonl",
203 ".yaml",
204 ".yml",
205 ".toml",
206 ".xml",
207 ".csv",
208 ".tsv",
209 ".js",
210 ".jsx",
211 ".mjs",
212 ".cjs",
213 ".ts",
214 ".tsx",
215 ".html",
216 ".css",
217 ".scss",
218 ".less",
219 ".py",
220 ".rs",
221 ".go",
222 ".java",
223 ".kt",
224 ".swift",
225 ".c",
226 ".h",
227 ".cc",
228 ".cpp",
229 ".hpp",
230 ".cs",
231 ".rb",
232 ".php",
233 ".sh",
234 ".bash",
235 ".zsh",
236 ".sql",
237 ".graphql",
238 ".svelte",
239 ".vue",
240 ".log",
241 ".diff",
242 ".patch",
243 ".ini",
244 ".conf",
245]);
246export const ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES = 1024 * 1024;
247const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;
248
249/** Sends uploads as native ACP content instead of workspace path hints. */
250export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {
251 readonly input: ProviderSendTurnInput["input"];
252 readonly attachments: ProviderSendTurnInput["attachments"];
253 readonly attachmentsDir: string;
254}): Effect.fn.Return<
255 ReadonlyArray<EffectAcpSchema.ContentBlock>,
256 EffectAcpErrors.AcpError,
257 FileSystem.FileSystem | Path.Path
258> {
259 const fileSystem = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const blocks: Array<EffectAcpSchema.ContentBlock> = [];
262 const text = input.input?.trim();
263 if (text) blocks.push({ type: "text", text });
264 let totalBytes = 0;
265
266 for (const attachment of input.attachments ?? []) {
267 const isPastedText =
268 attachment.type === "file" &&
269 "source" in attachment &&
270 attachment.source?._tag === "pasted-text";
271 // ProviderService has already put the file path in the text block. Keep a
272 // folded clipboard paste lazy so the agent can search or sample it rather
273 // than paying to embed the entire resource in context immediately.
274 const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? "";
275 const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);
276 const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);
277 const pdf = attachment.type === "file" && mimeType === "application/pdf";
278 const textFile =
279 attachment.type === "file" &&
280 (mimeType.startsWith("text/") ||
281 TEXT_MIME_TYPES.has(mimeType) ||
282 TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
283 if (!image && !audio && !pdf && !textFile) {
284 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
285 `Antigravity does not support '${attachment.name}' (${attachment.mimeType}). Attach a BMP, JPEG, PNG, WebP, PDF, audio, or text file.`,
286 );
287 }
288 const attachmentPath = resolveAttachmentPath({
289 attachmentsDir: input.attachmentsDir,
290 attachment,
291 });
292 if (!attachmentPath) {
293 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
294 `Invalid attachment '${attachment.name}'.`,
295 );
296 }
297 const info = yield* fileSystem
298 .stat(attachmentPath)
299 .pipe(
300 Effect.mapError(() =>
301 EffectAcpErrors.AcpRequestError.invalidParams(
302 `Could not read attachment '${attachment.name}'.`,
303 ),
304 ),
305 );
306 if (isPastedText) {
307 if (info.type !== "File") {
308 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
309 `Could not read attachment '${attachment.name}'.`,
310 );
311 }
312 continue;
313 }
314 const size = Number(info.size);
315 const limit = image
316 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
317 : audio
318 ? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES
319 : pdf
320 ? PROVIDER_SEND_TURN_MAX_FILE_BYTES
321 : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;
322 totalBytes += size;
323 if (info.type !== "File" || size > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
324 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
325 `Attachment '${attachment.name}' is too large. Antigravity accepts text files up to 1 MiB, images up to 10 MiB, audio up to 20 MiB, and 50 MiB total attachments.`,
326 );
327 }
328 const uri = yield* path.toFileUrl(attachmentPath).pipe(
329 Effect.map((url) => url.href),
330 Effect.mapError(() =>
331 EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`),
332 ),
333 );
334 if (pdf) {
335 blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType });
336 continue;
337 }
338 const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe(
339 Stream.runCollect,
340 Effect.map((chunks) => Buffer.concat(chunks)),
341 Effect.mapError(() =>
342 EffectAcpErrors.AcpRequestError.invalidParams(
343 `Could not read attachment '${attachment.name}'.`,
344 ),
345 ),
346 );
347 totalBytes += bytes.length - size;
348 if (bytes.length > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
349 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
350 `Attachment '${attachment.name}' changed while being read and is too large.`,
351 );
352 }
353 if (image) {
354 blocks.push({ type: "image", data: Buffer.from(bytes).toString("base64"), mimeType });
355 } else if (audio) {
356 blocks.push({ type: "audio", data: Buffer.from(bytes).toString("base64"), mimeType });
357 } else {
358 const decoded = yield* Effect.try({
359 try: () => new TextDecoder("utf-8", { fatal: true }).decode(bytes),
360 catch: () =>
361 EffectAcpErrors.AcpRequestError.invalidParams(
362 `Attachment '${attachment.name}' is not a UTF-8 text file.`,
363 ),
364 });
365 if (decoded.includes("\0")) {
366 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
367 `Attachment '${attachment.name}' contains binary data.`,
368 );
369 }
370 blocks.push({ type: "resource", resource: { uri, mimeType, text: decoded } });
371 }
372 }
373 if (blocks.length === 0) {
374 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
375 "A turn requires text or supported attachments.",
376 );
377 }
378 return blocks;
379});