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