Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2// @effect-diagnostics-next-line nodeBuiltinImport:off - resolveAntigravityProfileDirectory is a pure sync helper, so it cannot use the Path service.
3import * as NodePath from "node:path";
4
5import type { AntigravityAuthMethod, ProviderInstanceId } from "@t3tools/contracts";
6import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import type * as PlatformError from "effect/PlatformError";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import * as ChildProcess from "effect/unstable/process/ChildProcess";
14import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
15import * as AcpErrors from "effect-acp/errors";
16
17import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
18import type { AcpSpawnInput } from "./acp/AcpSessionRuntime.ts";
19
20export const ANTIGRAVITY_AUTH_STDOUT_PREFIX =
21 "Open the following link to authenticate the ACP server: ";
22export const ANTIGRAVITY_AUTH_BROWSER_MARKER = "__T3_ANTIGRAVITY_AUTH_URL__";
23export const ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE =
24 "Sign in to Antigravity in Settings before you continue.";
25
26const maxAuthorizationUrlLength = 16_384;
27const maxBrowserHelperLineLength =
28 Math.max(ANTIGRAVITY_AUTH_BROWSER_MARKER.length, ANTIGRAVITY_AUTH_STDOUT_PREFIX.length) +
29 maxAuthorizationUrlLength +
30 2;
31const maxStdoutLineBytes = 16 * 1024 * 1024;
32const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX);
33const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);
34const decodeBrowserHelperUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String));
35const ProfileSettingsFile = Schema.Struct({
36 auth: Schema.Struct({ type: Schema.String }),
37 gcp: Schema.optional(
38 Schema.Struct({
39 project: Schema.optional(Schema.String),
40 location: Schema.optional(Schema.String),
41 }),
42 ),
43});
44const encodeProfileSettings = Schema.encodeSync(Schema.fromJsonString(ProfileSettingsFile));
45const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
46const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError);
47
48// Python splits BROWSER on the platform path separator before it parses quotes.
49// Keep this source free of both colons and semicolons. EPIPE must still exit 0
50// so Python does not fall back to an OS browser after cancellation.
51const browserHelperSource =
52 `process.stderr.on("error",()=>process.exit(0)).write(` +
53 `"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` +
54 `()=>process.exit(0))`;
55const browserPreflightUrl = "https://example.invalid/t3-antigravity-browser-preflight";
56
57const removedEnvironmentKeys = new Set([
58 "GEMINI_API_KEY",
59 "GOOGLE_API_KEY",
60 "GOOGLE_APPLICATION_CREDENTIALS",
61 "GOOGLE_CLOUD_PROJECT",
62 "GOOGLE_CLOUD_LOCATION",
63 "GOOGLE_CLOUD_QUOTA_PROJECT",
64 "GOOGLE_GENAI_USE_VERTEXAI",
65 "GCLOUD_PROJECT",
66 "CLOUDSDK_CORE_PROJECT",
67 "AGY_ACP_CCPA_PROJECT",
68 "AGY_ACP_ENABLE_OAUTH",
69 "GEMINI_HOME",
70 "AGY_ACP_FORCE_FILE_STORAGE",
71 "ANTIGRAVITY_HARNESS_PATH",
72 "BROWSER",
73 "PYTHONUNBUFFERED",
74 "ELECTRON_RUN_AS_NODE",
75]);
76
77export interface AntigravityProfile {
78 readonly platform: NodeJS.Platform;
79 readonly geminiHome: string;
80 readonly acpDirectory: string;
81 readonly tokenPath: string;
82 readonly browserCommand: string;
83}
84
85/**
86 * Credentials for the non-personal ACP auth methods. The agent reads the API
87 * key from its environment and the GCP project and location from
88 * `settings.json` in the profile. Empty strings mean "not set".
89 */
90export interface AntigravityAuthConfig {
91 readonly authMethod: AntigravityAuthMethod;
92 readonly apiKey: string;
93 readonly gcpProject: string;
94 readonly gcpLocation: string;
95}
96
97export const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
98 authMethod: "oauth-personal",
99 apiKey: "",
100 gcpProject: "",
101 gcpLocation: "",
102};
103
104/** True for the two methods that open a Google sign-in page. */
105export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
106 return authMethod === "oauth-personal" || authMethod === "oauth-business";
107}
108
109/** Label shown on the provider card once the method has authenticated. */
110export function antigravityAuthLabel(authMethod: AntigravityAuthMethod): string {
111 switch (authMethod) {
112 case "oauth-personal":
113 return "Google account";
114 case "oauth-business":
115 return "Gemini Enterprise";
116 case "gemini-api-key":
117 return "Gemini API key";
118 case "agent-platform":
119 return "Agent Platform";
120 }
121}
122
123/**
124 * Explains what is missing before a non-personal method can authenticate, or
125 * null when the config is complete. Personal sign-in never needs config.
126 */
127export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string | null {
128 switch (auth.authMethod) {
129 case "oauth-personal":
130 return null;
131 case "oauth-business":
132 return auth.gcpProject && auth.gcpLocation
133 ? null
134 : "Gemini Enterprise needs a GCP project and location in the Antigravity provider settings.";
135 case "gemini-api-key":
136 return auth.apiKey ? null : "Enter a Gemini API key in the Antigravity provider settings.";
137 case "agent-platform":
138 return auth.apiKey || (auth.gcpProject && auth.gcpLocation)
139 ? null
140 : "Agent Platform needs an API key, or a GCP project and location, in the Antigravity provider settings.";
141 }
142}
143
144/**
145 * `settings.json` content for the agent's profile. `auth.type` names the
146 * selected method so a native logout clears only that method's credentials
147 * instead of every stored token. The GCP block feeds Enterprise and Agent
148 * Platform. Never holds a credential.
149 */
150export function antigravityProfileSettings(auth: AntigravityAuthConfig): string {
151 const gcp = {
152 ...(auth.gcpProject ? { project: auth.gcpProject } : {}),
153 ...(auth.gcpLocation ? { location: auth.gcpLocation } : {}),
154 };
155 return `${encodeProfileSettings({
156 auth: { type: auth.authMethod },
157 ...(Object.keys(gcp).length > 0 ? { gcp } : {}),
158 })}\n`;
159}
160
161export interface AntigravityAuthorizationUrl {
162 readonly authorizationUrl: string;
163 readonly redirectUri: string;
164 readonly state: string;
165}
166
167function authSupportError(detail: string) {
168 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
169}
170
171/** Recognizes native auth failures and interactive login blocked by T3. */
172export function isAntigravitySignInRequiredError(error: unknown): boolean {
173 return (
174 (isAcpRequestError(error) && error.code === -32000) ||
175 (isAcpTransportError(error) && error.detail === ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)
176 );
177}
178
179/** Keeps case-sensitive instance IDs separate on case-insensitive filesystems. */
180export function resolveAntigravityProfileDirectory(
181 stateDir: string,
182 instanceId: ProviderInstanceId,
183): string {
184 const directoryName = NodeCrypto.createHash("sha256").update(instanceId).digest("hex");
185 return NodePath.join(stateDir, "providers", "antigravity", directoryName);
186}
187
188function quoteBrowserArgument(value: string): string {
189 return `'${value.replaceAll("'", `'"'"'`)}'`;
190}
191
192function antigravityEnvironment(
193 profile: AntigravityProfile,
194 baseEnv: NodeJS.ProcessEnv,
195 auth: AntigravityAuthConfig,
196) {
197 const environment: NodeJS.ProcessEnv = {};
198 for (const [key, value] of Object.entries(baseEnv)) {
199 // Windows treats environment keys as case-insensitive. Remove aliases too.
200 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
201 }
202 // Only the configured method's credential reaches the agent. The agent
203 // prefers GOOGLE_API_KEY over the GCP pair for Agent Platform, so the pair
204 // goes through settings.json instead of the environment.
205 const credential =
206 auth.authMethod === "gemini-api-key" && auth.apiKey
207 ? { GEMINI_API_KEY: auth.apiKey }
208 : auth.authMethod === "agent-platform" && auth.apiKey
209 ? { GOOGLE_API_KEY: auth.apiKey }
210 : {};
211 return {
212 ...environment,
213 ...credential,
214 GEMINI_HOME: profile.geminiHome,
215 AGY_ACP_FORCE_FILE_STORAGE: "1",
216 BROWSER: profile.browserCommand,
217 PYTHONUNBUFFERED: "1",
218 ELECTRON_RUN_AS_NODE: "1",
219 };
220}
221
222/** Prepares a private profile without reading or copying Google credentials. */
223export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
224 readonly profileDirectory: string;
225 readonly baseEnv?: NodeJS.ProcessEnv;
226 readonly runtimeExecutablePath?: string;
227 readonly platform?: NodeJS.Platform;
228 readonly auth?: AntigravityAuthConfig;
229}) {
230 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
231 const fs = yield* FileSystem.FileSystem;
232 const path = yield* Path.Path;
233 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
234 const platform = input.platform ?? (yield* HostProcessPlatform);
235 const runtimeExecutablePath = input.runtimeExecutablePath ?? (yield* HostProcessExecutablePath);
236 const helperExecutable =
237 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
238 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
239 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
240 if (
241 browserCommand.includes(platform === "win32" ? ";" : ":") ||
242 helperExecutable.includes("\r") ||
243 helperExecutable.includes("\n") ||
244 helperExecutable.includes("\0") ||
245 helperExecutable.includes("%s")
246 ) {
247 return yield* authSupportError(
248 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
249 );
250 }
251
252 const geminiHome = path.resolve(input.profileDirectory);
253 const acpDirectory = path.join(geminiHome, "antigravity-acp");
254 const profile: AntigravityProfile = {
255 platform,
256 geminiHome,
257 acpDirectory,
258 tokenPath: path.join(acpDirectory, "acp_token.json"),
259 browserCommand,
260 };
261 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
262 yield* Effect.gen(function* () {
263 const child = yield* spawner.spawn(
264 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
265 env: environment,
266 extendEnv: false,
267 shell: false,
268 }),
269 );
270 const [stdout, stderr, exitCode] = yield* Effect.all(
271 [
272 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
273 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
274 child.exitCode,
275 ],
276 { concurrency: "unbounded" },
277 );
278 if (
279 Number(exitCode) !== 0 ||
280 stdout.bytes !== 0 ||
281 stdout.truncated ||
282 stderr.truncated ||
283 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
284 ) {
285 return yield* authSupportError("Antigravity browser suppression could not be verified.");
286 }
287 }).pipe(
288 Effect.scoped,
289 Effect.timeoutOrElse({
290 duration: "5 seconds",
291 orElse: () =>
292 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
293 }),
294 Effect.mapError((error) =>
295 error._tag === "AcpTransportError"
296 ? error
297 : authSupportError("Antigravity browser suppression could not be verified."),
298 ),
299 );
300
301 for (const directory of [geminiHome, acpDirectory]) {
302 yield* fs
303 .makeDirectory(directory, { recursive: true, mode: 0o700 })
304 .pipe(
305 Effect.mapError(() =>
306 authSupportError("The Antigravity profile directory could not be created."),
307 ),
308 );
309 if (platform !== "win32") {
310 yield* fs
311 .chmod(directory, 0o700)
312 .pipe(
313 Effect.mapError(() =>
314 authSupportError("The Antigravity profile directory permissions could not be set."),
315 ),
316 );
317 }
318 }
319 // Rewriting on every launch keeps a method, project, or location edit in
320 // Settings effective. The agent also records auth.type here after a
321 // sign-in, which matches the value written below.
322 yield* fs
323 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
324 .pipe(
325 Effect.mapError(() =>
326 authSupportError("The Antigravity profile settings could not be written."),
327 ),
328 );
329 return profile;
330});
331
332/** Applies the same subscription-only launch settings to every ACP process. */
333export function buildAntigravityAcpSpawnInput(input: {
334 readonly installation: {
335 readonly executablePath: string;
336 readonly harnessPath: string;
337 };
338 readonly profile: AntigravityProfile;
339 readonly cwd: string;
340 readonly baseEnv?: NodeJS.ProcessEnv;
341 readonly auth?: AntigravityAuthConfig;
342}): AcpSpawnInput {
343 return {
344 command: input.installation.executablePath,
345 args: input.profile.platform === "linux" ? ["--uid="] : [],
346 cwd: input.cwd,
347 env: {
348 ...antigravityEnvironment(
349 input.profile,
350 input.baseEnv ?? process.env,
351 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
352 ),
353 ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath,
354 },
355 extendEnv: false,
356 };
357}
358
359/** Reads only the public authorization request, never an OAuth token file. */
360export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
361 function* (
362 authorizationUrl: string,
363 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
364 const invalidUrl = () =>
365 authSupportError("Antigravity returned an invalid Google sign-in URL.");
366 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
367 return yield* invalidUrl();
368 }
369 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
370 const state = url.searchParams.get("state");
371 const redirectUri = url.searchParams.get("redirect_uri");
372 if (
373 url.origin !== "https://accounts.google.com" ||
374 url.pathname !== "/o/oauth2/v2/auth" ||
375 url.username !== "" ||
376 url.password !== "" ||
377 url.hash !== "" ||
378 url.searchParams.getAll("state").length !== 1 ||
379 url.searchParams.getAll("redirect_uri").length !== 1 ||
380 url.searchParams.getAll("response_type").length !== 1 ||
381 url.searchParams.get("response_type") !== "code" ||
382 state === null ||
383 state.length === 0 ||
384 state.length > 512 ||
385 /\s/.test(state) ||
386 redirectUri === null ||
387 !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
388 ) {
389 return yield* invalidUrl();
390 }
391 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
392 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
393 return { authorizationUrl, redirectUri, state };
394 },
395);
396
397export function makeAntigravityStdoutTransform(
398 input: {
399 readonly onAuthorizationUrl?: (
400 authorizationUrl: string,
401 ) => Effect.Effect<void, AcpErrors.AcpError>;
402 } = {},
403) {
404 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
405 line: Uint8Array,
406 ) {
407 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
408 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
409 const request = yield* parseAntigravityAuthorizationUrl(
410 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
411 );
412 if (!input.onAuthorizationUrl) {
413 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
414 }
415 yield* input.onAuthorizationUrl(request.authorizationUrl);
416 return [];
417 });
418
419 return (
420 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
421 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
422 Stream.suspend(() => {
423 let pending: Uint8Array[] = [];
424 let pendingBytes = 0;
425 const finishLine = () => {
426 const line = Buffer.concat(pending, pendingBytes);
427 pending = [];
428 pendingBytes = 0;
429 return line;
430 };
431 return stdout.pipe(
432 Stream.mapEffect(
433 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
434 const lines: Uint8Array[] = [];
435 let offset = 0;
436 while (offset < chunk.byteLength) {
437 const newline = chunk.indexOf(10, offset);
438 const end = newline === -1 ? chunk.byteLength : newline + 1;
439 const part = chunk.subarray(offset, end);
440 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
441 return yield* authSupportError(
442 "Antigravity sent a protocol line that is too large.",
443 );
444 }
445 pending.push(part);
446 pendingBytes += part.byteLength;
447 if (newline !== -1) lines.push(finishLine());
448 offset = end;
449 }
450 return lines;
451 }),
452 ),
453 Stream.flatMap(Stream.fromIterable),
454 Stream.concat(
455 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
456 ),
457 Stream.mapEffect(handleLine),
458 Stream.flatMap(Stream.fromIterable),
459 );
460 });
461}
462
463/** Receives native 1.1.1 sign-in URLs and T3 browser-helper URLs without logging stderr. */
464export function makeAntigravityStderrHandler(
465 input: {
466 readonly onAuthorizationUrl?: (
467 authorizationUrl: string,
468 ) => Effect.Effect<void, AcpErrors.AcpError>;
469 } = {},
470) {
471 let pending = "";
472 const handleLine = (line: string) => {
473 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
474 if (message.length > maxBrowserHelperLineLength) {
475 return Effect.void;
476 }
477 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
478 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
479 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
480 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
481 : undefined;
482 if (url === undefined) return Effect.void;
483 return url.pipe(
484 Effect.flatMap(parseAntigravityAuthorizationUrl),
485 Effect.matchEffect({
486 onFailure: () => Effect.void,
487 onSuccess: (request) =>
488 input.onAuthorizationUrl
489 ? input.onAuthorizationUrl(request.authorizationUrl)
490 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
491 }),
492 );
493 };
494
495 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
496 const lines = `${pending}${text}`.split("\n");
497 pending = lines.pop() ?? "";
498 if (pending.length > maxBrowserHelperLineLength) pending = "";
499 yield* Effect.forEach(lines, handleLine, { discard: true });
500 });
501}