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