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

AntigravityAcpSupport.ts

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