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

AntigravityAcpSupport.ts

389 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/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;
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 }
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));
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;
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]);
246const ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES = 1024 * 1024;
247const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;
248​
249/**
250 * Sends supported uploads as native ACP content. Other files, and native
251 * candidates over their limits, reach the agent through the saved path
252 * ProviderService puts in the text block.
253 */
254export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {
255 readonly input: ProviderSendTurnInput["input"];
256 readonly attachments: ProviderSendTurnInput["attachments"];
257 readonly attachmentsDir: string;
258}): Effect.fn.Return<
259 ReadonlyArray<EffectAcpSchema.ContentBlock>,
260 EffectAcpErrors.AcpError,
261 FileSystem.FileSystem | Path.Path
262> {
263 const fileSystem = yield* FileSystem.FileSystem;
264 const path = yield* Path.Path;
265 const blocks: Array<EffectAcpSchema.ContentBlock> = [];
266 const text = input.input?.trim();
267 if (text) blocks.push({ type: "text", text });
268 let totalBytes = 0;
269​
270 for (const attachment of input.attachments ?? []) {
271 const isPastedText =
272 attachment.type === "file" &&
273 "source" in attachment &&
274 attachment.source?._tag === "pasted-text";
275 // ProviderService has already put the file path in the text block. Keep a
276 // folded clipboard paste lazy so the agent can search or sample it rather
277 // than paying to embed the entire resource in context immediately.
278 const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? "";
279 const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);
280 const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);
281 const pdf = attachment.type === "file" && mimeType === "application/pdf";
282 const textFile =
283 attachment.type === "file" &&
284 (mimeType.startsWith("text/") ||
285 TEXT_MIME_TYPES.has(mimeType) ||
286 TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
287 const isPathOnly =
288 attachment.type === "file" && (isPastedText || (!audio && !pdf && !textFile));
289 if (attachment.type === "image" && !image) {
290 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
291 `Antigravity does not support '${attachment.name}' (${attachment.mimeType}). Attach a BMP, JPEG, PNG, WebP, PDF, audio, or text file.`,
292 );
293 }
294 const attachmentPath = resolveAttachmentPath({
295 attachmentsDir: input.attachmentsDir,
296 attachment,
297 });
298 if (!attachmentPath) {
299 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
300 `Invalid attachment '${attachment.name}'.`,
301 );
302 }
303 const info = yield* fileSystem
304 .stat(attachmentPath)
305 .pipe(
306 Effect.mapError(() =>
307 EffectAcpErrors.AcpRequestError.invalidParams(
308 `Could not read attachment '${attachment.name}'.`,
309 ),
310 ),
311 );
312 if (info.type !== "File") {
313 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
314 `Could not read attachment '${attachment.name}'.`,
315 );
316 }
317 if (isPathOnly) continue;
318 const size = Number(info.size);
319 const limit = image
320 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
321 : audio
322 ? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES
323 : pdf
324 ? MAX_TOTAL_ATTACHMENT_BYTES
325 : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES;
326 if (
327 attachment.type === "file" &&
328 (size > limit || totalBytes + size > MAX_TOTAL_ATTACHMENT_BYTES)
329 ) {
330 continue;
331 }
332 totalBytes += size;
333 if (size > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
334 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
335 `Image '${attachment.name}' is too large. Antigravity accepts images up to 10 MiB and 50 MiB of native attachments per message.`,
336 );
337 }
338 const uri = yield* path.toFileUrl(attachmentPath).pipe(
339 Effect.map((url) => url.href),
340 Effect.mapError(() =>
341 EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`),
342 ),
343 );
344 if (pdf) {
345 blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType });
346 continue;
347 }
348 const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe(
349 Stream.runCollect,
350 Effect.map((chunks) => Buffer.concat(chunks)),
351 Effect.mapError(() =>
352 EffectAcpErrors.AcpRequestError.invalidParams(
353 `Could not read attachment '${attachment.name}'.`,
354 ),
355 ),
356 );
357 totalBytes += bytes.length - size;
358 if (bytes.length > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
359 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
360 `Attachment '${attachment.name}' changed while being read and is too large.`,
361 );
362 }
363 if (image) {
364 blocks.push({ type: "image", data: Buffer.from(bytes).toString("base64"), mimeType });
365 } else if (audio) {
366 blocks.push({ type: "audio", data: Buffer.from(bytes).toString("base64"), mimeType });
367 } else {
368 const decoded = yield* Effect.try({
369 try: () => new TextDecoder("utf-8", { fatal: true }).decode(bytes),
370 catch: () =>
371 EffectAcpErrors.AcpRequestError.invalidParams(
372 `Attachment '${attachment.name}' is not a UTF-8 text file.`,
373 ),
374 });
375 if (decoded.includes("\0")) {
376 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
377 `Attachment '${attachment.name}' contains binary data.`,
378 );
379 }
380 blocks.push({ type: "resource", resource: { uri, mimeType, text: decoded } });
381 }
382 }
383 if (blocks.length === 0) {
384 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
385 "A turn requires text or supported attachments.",
386 );
387 }
388 return blocks;
389});