Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityAcpSupport.ts

399 lines13.7 KB

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 | "clientInfo"
35 | "onStderr"
36 | "resumeMethod"
37 | "transformSessionUpdate"
38 | "transformStdout"
39> {
40 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
41 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
42 readonly clientFileReads?: boolean;
43 readonly authMethod?: AntigravityAuthMethod;
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 // The agent offers non-Gemini models only to allowlisted clients such as Zed.
61 clientInfo: { name: "zed", version: "0.0.0" },
62 clientCapabilities: {
63 // Advertising writes swaps the agent's diff edits for whole-file client_edit_file.
64 fs: { readTextFile: input.clientFileReads === true, writeTextFile: false },
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 }
94​
95export function 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));
102​
103/** Runtime 1.4 reports thinking as its own option; 1.3 encoded it in the model ID. */
104export function antigravityThinkingConfig(
105 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
106) {
107 const option = configOptions?.find((candidate) => candidate.category === "thought_level");
108 return option?.type === "select" ? option : undefined;
110​
111/**
112 * Runtime 1.4 lists `gemini-3.8-flash` where 1.3 listed `gemini-3.8-flash-high`. The agent
113 * still accepts the old IDs, so pass them through; the current model may have no thinking option.
114 */
115function legacyAntigravityFamily(
116 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
117 model: string,
118) {
119 return antigravityModelOptions(configOptions)
120 .map((option) => option.value)
121 .filter((family) => model.startsWith(`${family}-`))
122 .toSorted((left, right) => right.length - left.length)[0];
124​
125function resolveAntigravityModel(input: {
126 readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
127 readonly model: string | null | undefined;
128 readonly defaultModel?: string | undefined;
129}): string | undefined {
130 const modelConfig = input.configOptions.find((option) => option.id === "model");
131 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
132 if (input.model && input.model !== ANTIGRAVITY_DEFAULT_MODEL) return input.model;
133 const options = antigravityModelOptions(input.configOptions);
134 return input.defaultModel &&
135 (options.some((option) => option.value === input.defaultModel) ||
136 legacyAntigravityFamily(input.configOptions, input.defaultModel) !== undefined)
137 ? input.defaultModel
138 : current;
140​
141/** Never replace a saved selection with the default returned by a cold resume. */
142export const applyAntigravityAcpModelSelection = Effect.fn("applyAntigravityAcpModelSelection")(
143 function* <E>(input: {
144 readonly runtime: Pick<
145 AcpSessionRuntime.AcpSessionRuntime["Service"],
146 "getConfigOptions" | "setModel" | "setConfigOption"
147 >;
148 readonly model: string | null | undefined;
149 readonly defaultModel?: string | undefined;
150 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
151 }): Effect.fn.Return<string | undefined, E> {
152 const configOptions = yield* input.runtime.getConfigOptions;
153 const modelConfig = configOptions.find((option) => option.id === "model");
154 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
155 const resolved = resolveAntigravityModel({
156 configOptions,
157 model: input.model,
158 defaultModel: input.defaultModel,
159 });
160 const explicit = Boolean(input.model) && input.model !== ANTIGRAVITY_DEFAULT_MODEL;
161 if (resolved === undefined || (!explicit && resolved === current)) return current;
162 const options = antigravityModelOptions(configOptions);
163 const legacyFamily = options.some((option) => option.value === resolved)
164 ? undefined
165 : legacyAntigravityFamily(configOptions, resolved);
166 if (legacyFamily !== undefined) {
167 yield* input.runtime
168 .setConfigOption("model", resolved, { allowUnlistedValue: true })
169 .pipe(Effect.mapError(input.mapError));
170 return legacyFamily;
171 }
172 if (!options.some((option) => option.value === resolved)) {
173 return yield* Effect.fail(
174 input.mapError(
175 EffectAcpErrors.AcpRequestError.invalidParams(
176 `Antigravity model '${resolved}' is unavailable for this Google account. Select an available model.`,
177 ),
178 ),
179 );
180 }
181 yield* input.runtime.setModel(resolved).pipe(Effect.mapError(input.mapError));
182 return resolved;
183 },
184);
185​
186const IMAGE_MIME_TYPES = new Set(["image/bmp", "image/jpeg", "image/png", "image/webp"]);
187const AUDIO_MIME_TYPES = new Set([
188 "audio/aac",
189 "audio/flac",
190 "audio/mp3",
191 "audio/mpeg",
192 "audio/mp4",
193 "audio/m4a",
194 "audio/x-m4a",
195 "audio/ogg",
196 "audio/wav",
197 "audio/x-wav",
198 "audio/webm",
199]);
200const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024;
201const TEXT_MIME_TYPES = new Set([
202 "application/json",
203 "application/ld+json",
204 "application/javascript",
205 "application/typescript",
206 "application/xml",
207 "application/yaml",
208 "application/x-yaml",
209 "application/x-sh",
210]);
211const TEXT_FILE_EXTENSIONS = new Set([
212 ".txt",
213 ".md",
214 ".mdx",
215 ".json",
216 ".jsonl",
217 ".yaml",
218 ".yml",
219 ".toml",
220 ".xml",
221 ".csv",
222 ".tsv",
223 ".js",
224 ".jsx",
225 ".mjs",
226 ".cjs",
227 ".ts",
228 ".tsx",
229 ".html",
230 ".css",
231 ".scss",
232 ".less",
233 ".py",
234 ".rs",
235 ".go",
236 ".java",
237 ".kt",
238 ".swift",
239 ".c",
240 ".h",
241 ".cc",
242 ".cpp",
243 ".hpp",
244 ".cs",
245 ".rb",
246 ".php",
247 ".sh",
248 ".bash",
249 ".zsh",
250 ".sql",
251 ".graphql",
252 ".svelte",
253 ".vue",
254 ".log",
255 ".diff",
256 ".patch",
257 ".ini",
258 ".conf",
259]);
260const ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES = 1024 * 1024;
261const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;
262​
263export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {
264 readonly input: ProviderSendTurnInput["input"];
265 readonly attachments: ProviderSendTurnInput["attachments"];
266 readonly attachmentsDir: string;
267 readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
268}): Effect.fn.Return<
269 ReadonlyArray<EffectAcpSchema.ContentBlock>,
270 EffectAcpErrors.AcpError,
271 FileSystem.FileSystem | Path.Path
272> {
273 const fileSystem = yield* FileSystem.FileSystem;
274 const path = yield* Path.Path;
275 const blocks: Array<EffectAcpSchema.ContentBlock> = [];
276 const text = input.input?.trim();
277 if (text) blocks.push({ type: "text", text });
278 let totalBytes = 0;
279​
280 for (const attachment of input.attachments ?? []) {
281 const isPastedText =
282 attachment.type === "file" &&
283 "source" in attachment &&
284 attachment.source?._tag === "pasted-text";
285 // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file.
286 const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? "";
287 const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);
288 const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);
289 const pdf = attachment.type === "file" && mimeType === "application/pdf";
290 const textFile =
291 attachment.type === "file" &&
292 (mimeType.startsWith("text/") ||
293 TEXT_MIME_TYPES.has(mimeType) ||
294 TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
295 const isPathOnly =
296 (attachment.type === "image" && (!image || input.promptCapabilities?.image !== true)) ||
297 (attachment.type === "file" &&
298 (isPastedText ||
299 (audio
300 ? input.promptCapabilities?.audio !== true
301 : pdf || textFile
302 ? input.promptCapabilities?.embeddedContext !== true
303 : true)));
304 const attachmentPath = resolveAttachmentPath({
305 attachmentsDir: input.attachmentsDir,
306 attachment,
307 });
308 if (!attachmentPath) {
309 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
310 `Invalid attachment '${attachment.name}'.`,
311 );
312 }
313 const info = yield* fileSystem
314 .stat(attachmentPath)
315 .pipe(
316 Effect.mapError(() =>
317 EffectAcpErrors.AcpRequestError.invalidParams(
318 `Could not read attachment '${attachment.name}'.`,
319 ),
320 ),
321 );
322 if (info.type !== "File") {
323 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
324 `Could not read attachment '${attachment.name}'.`,
325 );
326 }
327 if (isPathOnly) continue;
328 const size = Number(info.size);
329 const limit = image
330 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
331 : audio
332 ? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES
333 : pdf
334 ? MAX_TOTAL_ATTACHMENT_BYTES
335 : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;
336 if (
337 attachment.type === "file" &&
338 (size > limit || totalBytes + size > MAX_TOTAL_ATTACHMENT_BYTES)
339 ) {
340 continue;
341 }
342 totalBytes += size;
343 if (size > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
344 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
345 `Image '${attachment.name}' is too large. Antigravity accepts images up to 10 MiB and 50 MiB of native attachments per message.`,
346 );
347 }
348 const uri = yield* path.toFileUrl(attachmentPath).pipe(
349 Effect.map((url) => url.href),
350 Effect.mapError(() =>
351 EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`),
352 ),
353 );
354 if (pdf) {
355 blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType });
356 continue;
357 }
358 const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe(
359 Stream.runCollect,
360 Effect.map((chunks) => Buffer.concat(chunks)),
361 Effect.mapError(() =>
362 EffectAcpErrors.AcpRequestError.invalidParams(
363 `Could not read attachment '${attachment.name}'.`,
364 ),
365 ),
366 );
367 totalBytes += bytes.length - size;
368 if (bytes.length > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
369 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
370 `Attachment '${attachment.name}' changed while being read and is too large.`,
371 );
372 }
373 if (image) {
374 blocks.push({ type: "image", data: Buffer.from(bytes).toString("base64"), mimeType });
375 } else if (audio) {
376 blocks.push({ type: "audio", data: Buffer.from(bytes).toString("base64"), mimeType });
377 } else {
378 const decoded = yield* Effect.try({
379 try: () => new TextDecoder("utf-8", { fatal: true }).decode(bytes),
380 catch: () =>
381 EffectAcpErrors.AcpRequestError.invalidParams(
382 `Attachment '${attachment.name}' is not a UTF-8 text file.`,
383 ),
384 });
385 if (decoded.includes("\0")) {
386 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
387 `Attachment '${attachment.name}' contains binary data.`,
388 );
389 }
390 blocks.push({ type: "resource", resource: { uri, mimeType, text: decoded } });
391 }
392 }
393 if (blocks.length === 0) {
394 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
395 "A turn requires text or supported attachments.",
396 );
397 }
398 return blocks;
399});