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

AntigravityAcpSupport.ts

365 lines12.3 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 | "onStderr"
35 | "resumeMethod"
36 | "transformSessionUpdate"
37 | "transformStdout"
38> {
39 readonly agentDeviceEnvironment?: Readonly<Record<string, string>>;
40 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
41 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
42 readonly clientFileSystem?: 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 clientCapabilities: {
61 fs: {
62 readTextFile: input.clientFileSystem === true,
63 writeTextFile: input.clientFileSystem === true,
64 },
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​
95function 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​
103function resolveAntigravityModel(input: {
104 readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
105 readonly model: string | null | undefined;
106 readonly defaultModel?: string | undefined;
107}): string | undefined {
108 const modelConfig = input.configOptions.find((option) => option.id === "model");
109 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
110 if (input.model && input.model !== ANTIGRAVITY_DEFAULT_MODEL) return input.model;
111 const options = antigravityModelOptions(input.configOptions);
112 return input.defaultModel && options.some((option) => option.value === input.defaultModel)
113 ? input.defaultModel
114 : current;
116​
117/** Never replace a saved selection with the default returned by a cold resume. */
118export const applyAntigravityAcpModelSelection = Effect.fn("applyAntigravityAcpModelSelection")(
119 function* <E>(input: {
120 readonly runtime: Pick<
121 AcpSessionRuntime.AcpSessionRuntime["Service"],
122 "getConfigOptions" | "setModel"
123 >;
124 readonly model: string | null | undefined;
125 readonly defaultModel?: string | undefined;
126 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
127 }): Effect.fn.Return<string | undefined, E> {
128 const configOptions = yield* input.runtime.getConfigOptions;
129 const modelConfig = configOptions.find((option) => option.id === "model");
130 const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined;
131 const resolved = resolveAntigravityModel({
132 configOptions,
133 model: input.model,
134 defaultModel: input.defaultModel,
135 });
136 const explicit = Boolean(input.model) && input.model !== ANTIGRAVITY_DEFAULT_MODEL;
137 if (resolved === undefined || (!explicit && resolved === current)) return current;
138 const options = antigravityModelOptions(configOptions);
139 if (!options.some((option) => option.value === resolved)) {
140 return yield* Effect.fail(
141 input.mapError(
142 EffectAcpErrors.AcpRequestError.invalidParams(
143 `Antigravity model '${resolved}' is unavailable for this Google account. Select an available model.`,
144 ),
145 ),
146 );
147 }
148 yield* input.runtime.setModel(resolved).pipe(Effect.mapError(input.mapError));
149 return resolved;
150 },
151);
152​
153const IMAGE_MIME_TYPES = new Set(["image/bmp", "image/jpeg", "image/png", "image/webp"]);
154const AUDIO_MIME_TYPES = new Set([
155 "audio/aac",
156 "audio/flac",
157 "audio/mp3",
158 "audio/mpeg",
159 "audio/mp4",
160 "audio/m4a",
161 "audio/x-m4a",
162 "audio/ogg",
163 "audio/wav",
164 "audio/x-wav",
165 "audio/webm",
166]);
167const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024;
168const TEXT_MIME_TYPES = new Set([
169 "application/json",
170 "application/ld+json",
171 "application/javascript",
172 "application/typescript",
173 "application/xml",
174 "application/yaml",
175 "application/x-yaml",
176 "application/x-sh",
177]);
178const TEXT_FILE_EXTENSIONS = new Set([
179 ".txt",
180 ".md",
181 ".mdx",
182 ".json",
183 ".jsonl",
184 ".yaml",
185 ".yml",
186 ".toml",
187 ".xml",
188 ".csv",
189 ".tsv",
190 ".js",
191 ".jsx",
192 ".mjs",
193 ".cjs",
194 ".ts",
195 ".tsx",
196 ".html",
197 ".css",
198 ".scss",
199 ".less",
200 ".py",
201 ".rs",
202 ".go",
203 ".java",
204 ".kt",
205 ".swift",
206 ".c",
207 ".h",
208 ".cc",
209 ".cpp",
210 ".hpp",
211 ".cs",
212 ".rb",
213 ".php",
214 ".sh",
215 ".bash",
216 ".zsh",
217 ".sql",
218 ".graphql",
219 ".svelte",
220 ".vue",
221 ".log",
222 ".diff",
223 ".patch",
224 ".ini",
225 ".conf",
226]);
227const ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES = 1024 * 1024;
228const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES;
229​
230export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: {
231 readonly input: ProviderSendTurnInput["input"];
232 readonly attachments: ProviderSendTurnInput["attachments"];
233 readonly attachmentsDir: string;
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 // ProviderService has already put the file path in the text block. Keep a
252 // folded clipboard paste lazy so the agent can search or sample it rather
253 // than paying to embed the entire resource in context immediately.
254 const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? "";
255 const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType);
256 const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType);
257 const pdf = attachment.type === "file" && mimeType === "application/pdf";
258 const textFile =
259 attachment.type === "file" &&
260 (mimeType.startsWith("text/") ||
261 TEXT_MIME_TYPES.has(mimeType) ||
262 TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
263 const isPathOnly =
264 attachment.type === "file" && (isPastedText || (!audio && !pdf && !textFile));
265 if (attachment.type === "image" && !image) {
266 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
267 `Antigravity does not support '${attachment.name}' (${attachment.mimeType}). Attach a BMP, JPEG, PNG, WebP, PDF, audio, or text file.`,
268 );
269 }
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});