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

AntigravityAcpSupport.ts

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