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