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

antigravityAuthSupport.ts

575 lines20.8 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's symlink has no type argument, and Windows needs a junction to link without elevation.
2import * as NodeFSP from "node:fs/promises";
3​
4import type { AntigravityAuthMethod, ProviderInstanceId } from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
7import * as Crypto from "effect/Crypto";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as FileSystem from "effect/FileSystem";
11import * as Path from "effect/Path";
12import type * as PlatformError from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17import * as AcpErrors from "effect-acp/errors";
18​
19import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
20import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
21import {
22 antigravityUserSkillDirectories,
23 resolveAntigravityUserHome,
24} from "./Drivers/AntigravitySkills.ts";
25​
26export const ANTIGRAVITY_AUTH_STDOUT_PREFIX =
27 "Open the following link to authenticate the ACP server: ";
28export const ANTIGRAVITY_AUTH_BROWSER_MARKER = "__T3_ANTIGRAVITY_AUTH_URL__";
29export const ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE =
30 "Sign in to Antigravity in Settings before you continue.";
31​
32const maxAuthorizationUrlLength = 16_384;
33const maxBrowserHelperLineLength =
34 Math.max(ANTIGRAVITY_AUTH_BROWSER_MARKER.length, ANTIGRAVITY_AUTH_STDOUT_PREFIX.length) +
35 maxAuthorizationUrlLength +
36 2;
37const maxStdoutLineBytes = 16 * 1024 * 1024;
38const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX);
39const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);
40const decodeBrowserHelperUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String));
41const ProfileSettingsFile = Schema.Struct({
42 auth: Schema.Struct({ type: Schema.String }),
43 gcp: Schema.optional(
44 Schema.Struct({
45 project: Schema.optional(Schema.String),
46 location: Schema.optional(Schema.String),
47 }),
48 ),
49});
50const encodeProfileSettings = Schema.encodeSync(Schema.fromJsonString(ProfileSettingsFile));
51const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
52const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError);
53​
54// Python splits BROWSER on the platform path separator before it parses quotes.
55// EPIPE must still exit 0 so Python does not fall back to an OS browser after
56// cancellation.
57const browserHelperSource =
58 `process.stderr.on("error",()=>process.exit(0)).write(` +
59 `"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` +
60 `()=>process.exit(0))`;
61const browserPreflightUrl = "https://example.invalid/t3-antigravity-browser-preflight";
62​
63const removedEnvironmentKeys = new Set([
64 "GEMINI_API_KEY",
65 "GOOGLE_API_KEY",
66 "GOOGLE_APPLICATION_CREDENTIALS",
67 "GOOGLE_CLOUD_PROJECT",
68 "GOOGLE_CLOUD_LOCATION",
69 "GOOGLE_CLOUD_QUOTA_PROJECT",
70 "GOOGLE_GENAI_USE_VERTEXAI",
71 "GCLOUD_PROJECT",
72 "CLOUDSDK_CORE_PROJECT",
73 "AGY_ACP_CCPA_PROJECT",
74 "AGY_ACP_ENABLE_OAUTH",
75 "GEMINI_HOME",
76 "AGY_ACP_FORCE_FILE_STORAGE",
77 "ANTIGRAVITY_HARNESS_PATH",
78 "BROWSER",
79 "PYTHONUNBUFFERED",
80 "ELECTRON_RUN_AS_NODE",
81]);
82​
83export interface AntigravityProfile {
84 readonly platform: NodeJS.Platform;
85 readonly geminiHome: string;
86 readonly acpDirectory: string;
87 readonly tokenPath: string;
88 readonly tempDirectory: string;
89 readonly browserCommand: string;
91​
92export interface AntigravityAuthConfig {
93 readonly authMethod: AntigravityAuthMethod;
94 readonly apiKey: string;
95 readonly gcpProject: string;
96 readonly gcpLocation: string;
98​
99export const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
100 authMethod: "oauth-personal",
101 apiKey: "",
102 gcpProject: "",
103 gcpLocation: "",
104};
105​
106export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
107 return authMethod === "oauth-personal" || authMethod === "oauth-business";
109​
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 }
122​
123export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string | null {
124 switch (auth.authMethod) {
125 case "oauth-personal":
126 return null;
127 case "oauth-business":
128 return auth.gcpProject && auth.gcpLocation
129 ? null
130 : "Gemini Enterprise needs a GCP project and location in the Antigravity provider settings.";
131 case "gemini-api-key":
132 return auth.apiKey ? null : "Enter a Gemini API key in the Antigravity provider settings.";
133 case "agent-platform":
134 return auth.apiKey || (auth.gcpProject && auth.gcpLocation)
135 ? null
136 : "Agent Platform needs an API key, or a GCP project and location, in the Antigravity provider settings.";
137 }
139​
140/**
141 * `auth.type` names the selected method so a native logout clears only that method's credentials
142 * instead of every stored token. Never holds a credential.
143 */
144export function antigravityProfileSettings(auth: AntigravityAuthConfig): string {
145 const gcp = {
146 ...(auth.gcpProject ? { project: auth.gcpProject } : {}),
147 ...(auth.gcpLocation ? { location: auth.gcpLocation } : {}),
148 };
149 return `${encodeProfileSettings({
150 auth: { type: auth.authMethod },
151 ...(Object.keys(gcp).length > 0 ? { gcp } : {}),
152 })}\n`;
154​
155export interface AntigravityAuthorizationUrl {
156 readonly authorizationUrl: string;
157 readonly redirectUri: string;
158 readonly state: string;
160​
161function authSupportError(detail: string) {
162 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
164​
165export function isAntigravitySignInRequiredError(error: unknown): boolean {
166 return (
167 (isAcpRequestError(error) && error.code === -32000) ||
168 (isAcpTransportError(error) && error.detail === ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)
169 );
171​
172export interface AntigravityInstanceDirectories {
173 readonly profile: string;
174 /**
175 * It sits beside the profile, not inside it: the agent unpacks members up to 120 characters deep,
176 * and the profile's longer name would push them past Windows' 260-character path limit.
177 */
178 readonly runtimeTemp: string;
180​
181/** Hashes the instance ID so case-only differences stay separate on case-insensitive filesystems. */
182export const resolveAntigravityInstanceDirectories = Effect.fn(
183 "resolveAntigravityInstanceDirectories",
184)(function* (stateDir: string, instanceId: ProviderInstanceId) {
185 const crypto = yield* Crypto.Crypto;
186 const path = yield* Path.Path;
187 const key = Hex.encode(yield* crypto.digest("SHA-256", new TextEncoder().encode(instanceId)));
188 return {
189 profile: path.join(stateDir, "providers", "antigravity", key),
190 runtimeTemp: path.join(stateDir, "antigravity-tmp", key.slice(0, 12)),
191 } satisfies AntigravityInstanceDirectories;
192});
193​
194function quoteBrowserArgument(value: string): string {
195 return `'${value.replaceAll("'", `'"'"'`)}'`;
197​
198function antigravityEnvironment(
199 profile: AntigravityProfile,
200 baseEnv: NodeJS.ProcessEnv,
201 auth: AntigravityAuthConfig,
202 runtimeTempDirectory?: string,
203) {
204 const environment: NodeJS.ProcessEnv = {};
205 for (const [key, value] of Object.entries(baseEnv)) {
206 // Windows treats environment keys as case-insensitive. Remove aliases too.
207 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
208 }
209 // The agent prefers GOOGLE_API_KEY over the GCP pair for Agent Platform, so the pair goes through
210 // settings.json instead of the environment.
211 const credential =
212 auth.authMethod === "gemini-api-key" && auth.apiKey
213 ? { GEMINI_API_KEY: auth.apiKey }
214 : auth.authMethod === "agent-platform" && auth.apiKey
215 ? { GOOGLE_API_KEY: auth.apiKey }
216 : {};
217 // It unpacks about 1 GB into the system temp directory per launch and a force
218 // kill leaves that behind. Point it at a T3-owned directory so the driver can
219 // reclaim the space.
220 const tempDirectory = runtimeTempDirectory ?? profile.tempDirectory;
221 return {
222 ...environment,
223 ...credential,
224 GEMINI_HOME: profile.geminiHome,
225 AGY_ACP_FORCE_FILE_STORAGE: "1",
226 BROWSER: profile.browserCommand,
227 PYTHONUNBUFFERED: "1",
228 ELECTRON_RUN_AS_NODE: "1",
229 ...(profile.platform === "win32"
230 ? { TEMP: tempDirectory, TMP: tempDirectory }
231 : { TMPDIR: tempDirectory }),
232 };
234​
235/**
236 * The agent reads its user-global skills under `GEMINI_HOME`, which T3 points
237 * at the private profile. Link the two skill directories back to the user's
238 * real `~/.gemini` so global skills load, while MCP servers, hooks, and
239 * credentials stay isolated.
240 */
241const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: {
242 readonly profileDirectory: string;
243 readonly userHome: string;
244 readonly platform: NodeJS.Platform;
245}): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const links = antigravityUserSkillDirectories(path, input.profileDirectory);
249 const targets = antigravityUserSkillDirectories(path, path.join(input.userHome, ".gemini"));
250 for (const [link, target] of [
251 [links[0], targets[0]],
252 [links[1], targets[1]],
253 ] as const) {
254 yield* Effect.gen(function* () {
255 const existing = yield* fs.readLink(link).pipe(
256 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
257 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
258 );
259 if (existing === target) return;
260 if (existing !== undefined) {
261 yield* fs.remove(link);
262 }
263 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
264 yield* Effect.tryPromise(() =>
265 NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
266 );
267 }).pipe(
268 Effect.catch((error) =>
269 Effect.logWarning("Antigravity user skills are not linked into the profile.", {
270 link,
271 target,
272 error,
273 }),
274 ),
275 );
276 }
277});
278​
279export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
280 readonly profileDirectory: string;
281 readonly baseEnv?: NodeJS.ProcessEnv;
282 readonly runtimeExecutablePath?: string;
283 readonly platform?: NodeJS.Platform;
284 readonly auth?: AntigravityAuthConfig;
285 readonly userHome?: string;
286 readonly tempDirectory?: string;
287}) {
288 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
289 const fs = yield* FileSystem.FileSystem;
290 const path = yield* Path.Path;
291 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
292 const platform = input.platform ?? (yield* HostProcess.Platform);
293 const userHome =
294 input.userHome ??
295 resolveAntigravityUserHome(
296 platform,
297 input.baseEnv ?? process.env,
298 yield* HostProcess.HomeDirectory,
299 );
300 const runtimeExecutablePath =
301 input.runtimeExecutablePath ??
302 (yield* resolveNodeExecutable("Antigravity sign-in", input.baseEnv).pipe(
303 Effect.mapError(
304 (cause) =>
305 new AcpErrors.AcpTransportError({
306 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
307 cause,
308 }),
309 ),
310 ));
311 const helperExecutable =
312 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
313 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
314 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
315 if (
316 browserCommand.includes(platform === "win32" ? ";" : ":") ||
317 helperExecutable.includes("\r") ||
318 helperExecutable.includes("\n") ||
319 helperExecutable.includes("\0") ||
320 helperExecutable.includes("%s")
321 ) {
322 return yield* authSupportError(
323 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
324 );
325 }
326​
327 const geminiHome = path.resolve(input.profileDirectory);
328 const acpDirectory = path.join(geminiHome, "antigravity-acp");
329 const tempDirectory = input.tempDirectory ?? path.join(acpDirectory, "tmp");
330 const profile: AntigravityProfile = {
331 platform,
332 geminiHome,
333 acpDirectory,
334 tokenPath: path.join(acpDirectory, "acp_token.json"),
335 tempDirectory,
336 browserCommand,
337 };
338 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
339 yield* Effect.gen(function* () {
340 const child = yield* spawner.spawn(
341 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
342 env: environment,
343 extendEnv: false,
344 shell: false,
345 }),
346 );
347 const [stdout, stderr, exitCode] = yield* Effect.all(
348 [
349 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
350 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
351 child.exitCode,
352 ],
353 { concurrency: "unbounded" },
354 );
355 if (
356 Number(exitCode) !== 0 ||
357 stdout.bytes !== 0 ||
358 stdout.truncated ||
359 stderr.truncated ||
360 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
361 ) {
362 return yield* authSupportError("Antigravity browser suppression could not be verified.");
363 }
364 }).pipe(
365 Effect.scoped,
366 Effect.timeoutOrElse({
367 duration: "5 seconds",
368 orElse: () =>
369 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
370 }),
371 Effect.mapError((error) =>
372 error._tag === "AcpTransportError"
373 ? error
374 : authSupportError("Antigravity browser suppression could not be verified."),
375 ),
376 );
377​
378 for (const directory of [geminiHome, acpDirectory, tempDirectory]) {
379 yield* fs
380 .makeDirectory(directory, { recursive: true, mode: 0o700 })
381 .pipe(
382 Effect.mapError(() =>
383 authSupportError("The Antigravity profile directory could not be created."),
384 ),
385 );
386 if (platform !== "win32") {
387 yield* fs
388 .chmod(directory, 0o700)
389 .pipe(
390 Effect.mapError(() =>
391 authSupportError("The Antigravity profile directory permissions could not be set."),
392 ),
393 );
394 }
395 }
396 yield* fs
397 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
398 .pipe(
399 Effect.mapError(() =>
400 authSupportError("The Antigravity profile settings could not be written."),
401 ),
402 );
403 yield* linkAntigravityUserSkills({ profileDirectory: geminiHome, userHome, platform });
404 return profile;
405});
406​
407export function buildAntigravityAcpSpawnInput(input: {
408 readonly installation: {
409 readonly executablePath: string;
410 readonly harnessPath: string;
411 };
412 readonly profile: AntigravityProfile;
413 readonly cwd: string;
414 readonly baseEnv?: NodeJS.ProcessEnv;
415 readonly auth?: AntigravityAuthConfig;
416 readonly runtimeTempDirectory?: string;
417}): AcpSessionRuntime.AcpSpawnInput {
418 return {
419 command: input.installation.executablePath,
420 args: input.profile.platform === "linux" ? ["--uid="] : [],
421 cwd: input.cwd,
422 env: {
423 ...antigravityEnvironment(
424 input.profile,
425 input.baseEnv ?? process.env,
426 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
427 input.runtimeTempDirectory,
428 ),
429 ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath,
430 },
431 extendEnv: false,
432 };
434​
435export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
436 function* (
437 authorizationUrl: string,
438 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
439 const invalidUrl = () =>
440 authSupportError("Antigravity returned an invalid Google sign-in URL.");
441 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
442 return yield* invalidUrl();
443 }
444 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
445 const state = url.searchParams.get("state");
446 const redirectUri = url.searchParams.get("redirect_uri");
447 if (
448 url.origin !== "https://accounts.google.com" ||
449 url.pathname !== "/o/oauth2/v2/auth" ||
450 url.username !== "" ||
451 url.password !== "" ||
452 url.hash !== "" ||
453 url.searchParams.getAll("state").length !== 1 ||
454 url.searchParams.getAll("redirect_uri").length !== 1 ||
455 url.searchParams.getAll("response_type").length !== 1 ||
456 url.searchParams.get("response_type") !== "code" ||
457 state === null ||
458 state.length === 0 ||
459 state.length > 512 ||
460 /\s/.test(state) ||
461 redirectUri === null ||
462 !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
463 ) {
464 return yield* invalidUrl();
465 }
466 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
467 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
468 return { authorizationUrl, redirectUri, state };
469 },
470);
471​
472export function makeAntigravityStdoutTransform(
473 input: {
474 readonly onAuthorizationUrl?: (
475 authorizationUrl: string,
476 ) => Effect.Effect<void, AcpErrors.AcpError>;
477 } = {},
478) {
479 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
480 line: Uint8Array,
481 ) {
482 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
483 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
484 const request = yield* parseAntigravityAuthorizationUrl(
485 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
486 );
487 if (!input.onAuthorizationUrl) {
488 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
489 }
490 yield* input.onAuthorizationUrl(request.authorizationUrl);
491 return [];
492 });
493​
494 return (
495 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
496 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
497 Stream.suspend(() => {
498 let pending: Uint8Array[] = [];
499 let pendingBytes = 0;
500 const finishLine = () => {
501 const line = Buffer.concat(pending, pendingBytes);
502 pending = [];
503 pendingBytes = 0;
504 return line;
505 };
506 return stdout.pipe(
507 Stream.mapEffect(
508 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
509 const lines: Uint8Array[] = [];
510 let offset = 0;
511 while (offset < chunk.byteLength) {
512 const newline = chunk.indexOf(10, offset);
513 const end = newline === -1 ? chunk.byteLength : newline + 1;
514 const part = chunk.subarray(offset, end);
515 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
516 return yield* authSupportError(
517 "Antigravity sent a protocol line that is too large.",
518 );
519 }
520 pending.push(part);
521 pendingBytes += part.byteLength;
522 if (newline !== -1) lines.push(finishLine());
523 offset = end;
524 }
525 return lines;
526 }),
527 ),
528 Stream.flatMap(Stream.fromIterable),
529 Stream.concat(
530 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
531 ),
532 Stream.mapEffect(handleLine),
533 Stream.flatMap(Stream.fromIterable),
534 );
535 });
537​
538export function makeAntigravityStderrHandler(
539 input: {
540 readonly onAuthorizationUrl?: (
541 authorizationUrl: string,
542 ) => Effect.Effect<void, AcpErrors.AcpError>;
543 } = {},
544) {
545 let pending = "";
546 const handleLine = (line: string) => {
547 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
548 if (message.length > maxBrowserHelperLineLength) {
549 return Effect.void;
550 }
551 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
552 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
553 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
554 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
555 : undefined;
556 if (url === undefined) return Effect.void;
557 return url.pipe(
558 Effect.flatMap(parseAntigravityAuthorizationUrl),
559 Effect.matchEffect({
560 onFailure: () => Effect.void,
561 onSuccess: (request) =>
562 input.onAuthorizationUrl
563 ? input.onAuthorizationUrl(request.authorizationUrl)
564 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
565 }),
566 );
567 };
568​
569 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
570 const lines = `${pending}${text}`.split("\n");
571 pending = lines.pop() ?? "";
572 if (pending.length > maxBrowserHelperLineLength) pending = "";
573 yield* Effect.forEach(lines, handleLine, { discard: true });
574 });