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

antigravityAuthSupport.ts

775 lines28.6 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 Digest from "effect/crypto/Digest";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import type * as PlatformError from "effect/PlatformError";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import * as ChildProcess from "effect/process/ChildProcess";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import * as AcpErrors from "effect-acp/errors";
19​
20import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
21import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
22import {
23 antigravityUserSkillDirectories,
24 resolveAntigravityUserHome,
25} from "./Drivers/AntigravitySkills.ts";
26​
27export const ANTIGRAVITY_AUTH_STDOUT_PREFIX =
28 "Open the following link to authenticate the ACP server: ";
29export const ANTIGRAVITY_AUTH_BROWSER_MARKER = "__T3_ANTIGRAVITY_AUTH_URL__";
30export const ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE =
31 "Sign in to Antigravity in Settings before you continue.";
32​
33const maxAuthorizationUrlLength = 16_384;
34const maxBrowserHelperLineLength =
35 Math.max(ANTIGRAVITY_AUTH_BROWSER_MARKER.length, ANTIGRAVITY_AUTH_STDOUT_PREFIX.length) +
36 maxAuthorizationUrlLength +
37 2;
38const maxStdoutLineBytes = 16 * 1024 * 1024;
39const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX);
40const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);
41const decodeBrowserHelperUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String));
42const ProfileSettingsFile = Schema.Struct({
43 auth: Schema.Struct({ type: Schema.String }),
44 gcp: Schema.optional(
45 Schema.Struct({
46 project: Schema.optional(Schema.String),
47 location: Schema.optional(Schema.String),
48 }),
49 ),
50});
51const encodeProfileSettings = Schema.encodeSync(Schema.fromJsonString(ProfileSettingsFile));
52const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
53const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError);
54​
55// Python splits BROWSER on path separators before parsing quotes. Exit 0 on EPIPE to prevent browser fallback after cancellation.
56const browserHelperSource =
57 `process.stderr.on("error",()=>process.exit(0)).write(` +
58 `"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` +
59 `()=>process.exit(0))`;
60const browserPreflightUrl = "https://example.invalid/t3-antigravity-browser-preflight";
61​
62const removedEnvironmentKeys = new Set([
63 "GEMINI_API_KEY",
64 "GOOGLE_API_KEY",
65 "GOOGLE_APPLICATION_CREDENTIALS",
66 "GOOGLE_CLOUD_PROJECT",
67 "GOOGLE_CLOUD_LOCATION",
68 "GOOGLE_CLOUD_QUOTA_PROJECT",
69 "GOOGLE_GENAI_USE_VERTEXAI",
70 "GCLOUD_PROJECT",
71 "CLOUDSDK_CORE_PROJECT",
72 "AGY_ACP_CCPA_PROJECT",
73 "AGY_ACP_ENABLE_OAUTH",
74 "GEMINI_HOME",
75 "AGY_ACP_FORCE_FILE_STORAGE",
76 "AGY_CLI_DISABLE_AUTO_UPDATE",
77 "BROWSER",
78 "PYTHONUNBUFFERED",
79 "ELECTRON_RUN_AS_NODE",
80 // An inherited pipe whose owner exited makes Electron-as-Node print Crashpad errors to stderr.
81 "CHROME_CRASHPAD_PIPE_NAME",
82]);
83​
84export interface AntigravityProfile {
85 readonly platform: NodeJS.Platform;
86 readonly geminiHome: string;
87 readonly acpDirectory: string;
88 readonly tokenPath: string;
89 readonly browserCommand: string;
90 readonly caBundlePath?: string;
92​
93export interface AntigravityAuthConfig {
94 readonly authMethod: AntigravityAuthMethod;
95 readonly apiKey: string;
96 readonly gcpProject: string;
97 readonly gcpLocation: string;
99​
100const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
101 authMethod: "oauth-personal",
102 apiKey: "",
103 gcpProject: "",
104 gcpLocation: "",
105};
106​
107export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
108 return authMethod === "oauth-personal" || authMethod === "oauth-business";
110​
111export function antigravityAuthLabel(authMethod: AntigravityAuthMethod): string {
112 switch (authMethod) {
113 case "oauth-personal":
114 return "Google account";
115 case "oauth-business":
116 return "Gemini Enterprise";
117 case "gemini-api-key":
118 return "Gemini API key";
119 case "agent-platform":
120 return "Agent Platform";
121 }
123​
124export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string | null {
125 switch (auth.authMethod) {
126 case "oauth-personal":
127 return null;
128 case "oauth-business":
129 return auth.gcpProject && auth.gcpLocation
130 ? null
131 : "Gemini Enterprise needs a GCP project and location in the Antigravity provider settings.";
132 case "gemini-api-key":
133 return auth.apiKey ? null : "Enter a Gemini API key in the Antigravity provider settings.";
134 case "agent-platform":
135 return auth.apiKey || (auth.gcpProject && auth.gcpLocation)
136 ? null
137 : "Agent Platform needs an API key, or a GCP project and location, in the Antigravity provider settings.";
138 }
140​
141/**
142 * `auth.type` names the selected method so a native logout clears only that method's credentials
143 * instead of every stored token. Never holds a credential.
144 */
145function 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`;
155​
156export interface AntigravityAuthorizationUrl {
157 readonly authorizationUrl: string;
158 readonly redirectUri: string;
159 readonly state: string;
161​
162function authSupportError(detail: string) {
163 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
165​
166// The 1.5 CLI answers `authenticate` with this internal error when it has no sign-in and no display.
167const NATIVE_CLI_NO_BROWSER_PREFIX = "No browser is available here";
168​
169export function isAntigravitySignInRequiredError(error: unknown): boolean {
170 return (
171 (isAcpRequestError(error) &&
172 (error.code === -32000 ||
173 (error.code === -32603 && error.errorMessage.startsWith(NATIVE_CLI_NO_BROWSER_PREFIX)))) ||
174 (isAcpTransportError(error) && error.detail === ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)
175 );
177​
178export interface AntigravityInstanceDirectories {
179 readonly profile: string;
180 /** Per-process temp folders from earlier releases; the driver only sweeps leftovers here. */
181 readonly runtimeTemp: string;
183​
184/** Hashes the instance ID so case-only differences stay separate on case-insensitive filesystems. */
185export const resolveAntigravityInstanceDirectories = Effect.fn(
186 "resolveAntigravityInstanceDirectories",
187)(function* (stateDir: string, instanceId: ProviderInstanceId) {
188 const digest = yield* Digest.Digest;
189 const path = yield* Path.Path;
190 const key = Hex.encode(yield* digest.digest(Digest.sha256, new TextEncoder().encode(instanceId)));
191 return {
192 profile: path.join(stateDir, "providers", "antigravity", key),
193 runtimeTemp: path.join(stateDir, "antigravity-tmp", key.slice(0, 12)),
194 } satisfies AntigravityInstanceDirectories;
195});
196​
197function quoteBrowserArgument(value: string): string {
198 return `'${value.replaceAll("'", `'"'"'`)}'`;
200​
201function antigravityEnvironment(
202 profile: AntigravityProfile,
203 baseEnv: NodeJS.ProcessEnv,
204 auth: AntigravityAuthConfig,
205) {
206 const environment: NodeJS.ProcessEnv = {};
207 for (const [key, value] of Object.entries(baseEnv)) {
208 // Windows treats environment keys as case-insensitive. Remove aliases too.
209 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
210 }
211 // Put the GCP pair in settings.json because GOOGLE_API_KEY takes precedence in the environment.
212 const credential =
213 auth.authMethod === "gemini-api-key" && auth.apiKey
214 ? { GEMINI_API_KEY: auth.apiKey }
215 : auth.authMethod === "agent-platform" && auth.apiKey
216 ? { GOOGLE_API_KEY: auth.apiKey }
217 : {};
218 return {
219 ...environment,
220 ...credential,
221 ...(profile.caBundlePath !== undefined &&
222 baseEnv.SSL_CERT_FILE === undefined &&
223 baseEnv.SSL_CERT_DIR === undefined
224 ? { SSL_CERT_FILE: profile.caBundlePath }
225 : {}),
226 // The 1.5 CLI ignores AGY_ACP_FORCE_FILE_STORAGE and keeps Google sign-ins in one OS keyring
227 // entry for every profile, unless it believes it runs over SSH. Sign-in then uses `--login`.
228 ...(auth.authMethod === "oauth-personal"
229 ? { SSH_CONNECTION: baseEnv.SSH_CONNECTION || "127.0.0.1 0 127.0.0.1 0" }
230 : {}),
231 GEMINI_HOME: profile.geminiHome,
232 AGY_ACP_FORCE_FILE_STORAGE: "1",
233 // agy's troubleshooting docs specify "true"; the interactive CLI keeps self-updating with "1".
234 AGY_CLI_DISABLE_AUTO_UPDATE: "true",
235 BROWSER: profile.browserCommand,
236 PYTHONUNBUFFERED: "1",
237 ELECTRON_RUN_AS_NODE: "1",
238 };
240​
241/** Bundled Python may look for certificates at paths absent on this Linux distribution. */
242export const resolveAntigravityCaBundle = Effect.fn("resolveAntigravityCaBundle")(function* (
243 platform: NodeJS.Platform,
244 baseEnv: NodeJS.ProcessEnv,
245) {
246 if (platform !== "linux") return undefined;
247 const fs = yield* FileSystem.FileSystem;
248 const path = yield* Path.Path;
249 // Relative paths would resolve differently when the agent runs in the project directory.
250 for (const candidate of [
251 baseEnv.NIX_SSL_CERT_FILE,
252 "/etc/ssl/certs/ca-bundle.crt",
253 "/etc/ssl/certs/ca-certificates.crt",
254 "/etc/pki/tls/certs/ca-bundle.crt",
255 "/etc/ssl/cert.pem",
256 ]) {
257 if (
258 candidate &&
259 path.isAbsolute(candidate) &&
260 (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)))
261 ) {
262 return candidate;
263 }
264 }
265 return undefined;
266});
267​
268/** `agy usage` ignores GEMINI_HOME and reads its sign-in under `$HOME/.gemini`, so it runs with a private home. */
269export function antigravityUsageEnvironment(
270 baseEnv: NodeJS.ProcessEnv,
271 home: string,
272 caBundlePath: string | undefined,
273) {
274 const environment: NodeJS.ProcessEnv = {};
275 for (const [key, value] of Object.entries(baseEnv)) {
276 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
277 }
278 return {
279 ...environment,
280 ...(caBundlePath !== undefined &&
281 baseEnv.SSL_CERT_FILE === undefined &&
282 baseEnv.SSL_CERT_DIR === undefined
283 ? { SSL_CERT_FILE: caBundlePath }
284 : {}),
285 HOME: home,
286 USERPROFILE: home,
287 // Keeps the CLI on the copied token file instead of the keyring entry every profile shares.
288 SSH_CONNECTION: baseEnv.SSH_CONNECTION || "127.0.0.1 0 127.0.0.1 0",
289 AGY_ACP_FORCE_FILE_STORAGE: "1",
290 AGY_CLI_DISABLE_AUTO_UPDATE: "true",
291 };
293​
294class AntigravitySkillLinkError extends Schema.TaggedError<AntigravitySkillLinkError>()(
295 "AntigravitySkillLinkError",
296 { link: Schema.String, cause: Schema.Defect() },
297) {
298 override get message(): string {
299 return `Could not link Antigravity user configuration at ${this.link}.`;
300 }
302​
303const antigravityUserConfigFiles = [
304 ["AGENTS.md"],
305 ["GEMINI.md"],
306 ["config", "skills.json"],
307 ["config", "mcp_config.json"],
308] as const;
309​
310/** Private GEMINI_HOME isolates credentials and hooks; link global skills, rules and MCP servers from the real ~/.gemini. */
311const linkAntigravityUserConfig = Effect.fn("linkAntigravityUserConfig")(function* (input: {
312 readonly profileDirectory: string;
313 readonly userHome: string;
314 readonly platform: NodeJS.Platform;
315}): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
316 const fs = yield* FileSystem.FileSystem;
317 const path = yield* Path.Path;
318 const userGemini = path.join(input.userHome, ".gemini");
319 const links = antigravityUserSkillDirectories(path, input.profileDirectory);
320 const targets = antigravityUserSkillDirectories(path, userGemini);
321 const directoryType = input.platform === "win32" ? "junction" : "dir";
322 for (const [link, target, type] of [
323 [links[0], targets[0], directoryType],
324 [links[1], targets[1], directoryType],
325 // File symlinks need elevation or Developer Mode on Windows, so config files are copied there.
326 ...(input.platform === "win32"
327 ? []
328 : antigravityUserConfigFiles.map(
329 (segments) =>
330 [
331 path.join(input.profileDirectory, ...segments),
332 path.join(userGemini, ...segments),
333 "file",
334 ] as const,
335 )),
336 ] as const) {
337 yield* Effect.gen(function* () {
338 // The harness creates these folders itself, and mkdir fails on a dangling link.
339 if (!(yield* fs.exists(target))) {
340 const linked = yield* fs.readLink(link).pipe(
341 Effect.as(true),
342 Effect.orElseSucceed(() => false),
343 );
344 if (linked) yield* fs.remove(link);
345 return;
346 }
347 const existing = yield* fs.readLink(link).pipe(
348 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
349 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
350 // An empty folder or file is the harness's placeholder from a launch without the link
351 // (the CLI writes a 0-byte mcp_config.json). rmdir refuses a non-empty folder.
352 Effect.catch((error) =>
353 Effect.tryPromise({
354 try: async () => {
355 const info = await NodeFSP.lstat(link);
356 if (info.isFile() && info.size === 0) return NodeFSP.unlink(link);
357 return NodeFSP.rmdir(link);
358 },
359 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
360 }).pipe(
361 Effect.as(undefined),
362 Effect.mapError(() => error),
363 ),
364 ),
365 );
366 if (existing === target) return;
367 if (existing !== undefined) {
368 yield* fs.remove(link);
369 }
370 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
371 yield* Effect.tryPromise({
372 try: () => NodeFSP.symlink(target, link, type),
373 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
374 });
375 }).pipe(
376 Effect.catch((error) =>
377 Effect.logWarning("Antigravity user configuration is not linked into the profile.", {
378 link,
379 target,
380 error,
381 }),
382 ),
383 );
384 }
385});
386​
387const RuleCopiesJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
388const decodeRuleCopies = Schema.decodeUnknownOption(RuleCopiesJson);
389const encodeRuleCopies = Schema.encodeSync(RuleCopiesJson);
390​
391/** Copies refresh each launch; the recorded copy keeps a file the profile owns or edited untouched. */
392const copyAntigravityUserConfigFiles = Effect.fn("copyAntigravityUserConfigFiles")(
393 function* (input: {
394 readonly profileDirectory: string;
395 readonly userHome: string;
396 }): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
397 const fs = yield* FileSystem.FileSystem;
398 const path = yield* Path.Path;
399 const manifestPath = path.join(input.profileDirectory, ".t3-rule-copies.json");
400 const readOptional = (file: string) =>
401 fs.readFileString(file).pipe(Effect.orElseSucceed((): string | undefined => undefined));
402 const manifestText = yield* readOptional(manifestPath);
403 const copies: Record<string, string> = {
404 ...Option.getOrElse(decodeRuleCopies(manifestText), () => ({})),
405 };
406 for (const segments of antigravityUserConfigFiles) {
407 const key = segments.join("/");
408 const link = path.join(input.profileDirectory, ...segments);
409 const target = path.join(input.userHome, ".gemini", ...segments);
410 yield* Effect.gen(function* () {
411 const current = yield* readOptional(link);
412 if (current !== undefined && current !== "" && current !== copies[key]) {
413 delete copies[key];
414 return;
415 }
416 const source = yield* readOptional(target);
417 if (source === undefined) {
418 if (current !== undefined) yield* fs.remove(link);
419 delete copies[key];
420 return;
421 }
422 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
423 yield* fs.writeFileString(link, source);
424 copies[key] = source;
425 }).pipe(
426 Effect.catch((error) =>
427 Effect.logWarning("Antigravity user configuration is not copied into the profile.", {
428 link,
429 target,
430 error,
431 }),
432 ),
433 );
434 }
435 yield* fs
436 .writeFileString(manifestPath, encodeRuleCopies(copies))
437 .pipe(
438 Effect.catch((error) =>
439 Effect.logWarning("Antigravity rule copy record could not be written.", { error }),
440 ),
441 );
442 },
443);
444​
445export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
446 readonly profileDirectory: string;
447 readonly baseEnv?: NodeJS.ProcessEnv;
448 readonly runtimeExecutablePath?: string;
449 readonly platform?: NodeJS.Platform;
450 readonly auth?: AntigravityAuthConfig;
451 readonly userHome?: string;
452}) {
453 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
454 const fs = yield* FileSystem.FileSystem;
455 const path = yield* Path.Path;
456 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
457 const platform = input.platform ?? (yield* HostProcess.Platform);
458 const userHome =
459 input.userHome ??
460 resolveAntigravityUserHome(
461 platform,
462 input.baseEnv ?? process.env,
463 yield* HostProcess.HomeDirectory,
464 );
465 const runtimeExecutablePath =
466 input.runtimeExecutablePath ??
467 (yield* resolveNodeExecutable("Antigravity sign-in", input.baseEnv).pipe(
468 Effect.mapError(
469 (cause) =>
470 new AcpErrors.AcpTransportError({
471 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
472 cause,
473 }),
474 ),
475 ));
476 const helperExecutable =
477 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
478 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
479 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
480 if (
481 browserCommand.includes(platform === "win32" ? ";" : ":") ||
482 helperExecutable.includes("\r") ||
483 helperExecutable.includes("\n") ||
484 helperExecutable.includes("\0") ||
485 helperExecutable.includes("%s")
486 ) {
487 return yield* authSupportError(
488 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
489 );
490 }
491​
492 const geminiHome = path.resolve(input.profileDirectory);
493 const acpDirectory = path.join(geminiHome, "antigravity-acp");
494 const caBundlePath = yield* resolveAntigravityCaBundle(platform, input.baseEnv ?? process.env);
495 const profile: AntigravityProfile = {
496 platform,
497 geminiHome,
498 acpDirectory,
499 tokenPath: path.join(acpDirectory, "acp_token.json"),
500 browserCommand,
501 ...(caBundlePath === undefined ? {} : { caBundlePath }),
502 };
503 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
504 yield* Effect.gen(function* () {
505 const child = yield* spawner.spawn(
506 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
507 env: environment,
508 extendEnv: false,
509 shell: false,
510 }),
511 );
512 const [stdout, stderr, exitCode] = yield* Effect.all(
513 [
514 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
515 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
516 child.exitCode,
517 ],
518 { concurrency: "unbounded" },
519 );
520 if (
521 Number(exitCode) !== 0 ||
522 stdout.bytes !== 0 ||
523 stdout.truncated ||
524 stderr.truncated ||
525 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
526 ) {
527 return yield* authSupportError("Antigravity browser suppression could not be verified.");
528 }
529 }).pipe(
530 Effect.scoped,
531 Effect.timeoutOrElse({
532 duration: "30 seconds",
533 orElse: () =>
534 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
535 }),
536 Effect.mapError((error) =>
537 error._tag === "AcpTransportError"
538 ? error
539 : authSupportError("Antigravity browser suppression could not be verified."),
540 ),
541 );
542​
543 for (const directory of [geminiHome, acpDirectory]) {
544 yield* fs
545 .makeDirectory(directory, { recursive: true, mode: 0o700 })
546 .pipe(
547 Effect.mapError(() =>
548 authSupportError("The Antigravity profile directory could not be created."),
549 ),
550 );
551 if (platform !== "win32") {
552 yield* fs
553 .chmod(directory, 0o700)
554 .pipe(
555 Effect.mapError(() =>
556 authSupportError("The Antigravity profile directory permissions could not be set."),
557 ),
558 );
559 }
560 }
561 yield* fs
562 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
563 .pipe(
564 Effect.mapError(() =>
565 authSupportError("The Antigravity profile settings could not be written."),
566 ),
567 );
568 yield* linkAntigravityUserConfig({ profileDirectory: geminiHome, userHome, platform });
569 if (platform === "win32") {
570 yield* copyAntigravityUserConfigFiles({ profileDirectory: geminiHome, userHome });
571 }
572 return profile;
573});
574​
575export function buildAntigravityAcpSpawnInput(input: {
576 readonly installation: { readonly executablePath: string };
577 readonly profile: AntigravityProfile;
578 readonly cwd: string;
579 readonly baseEnv?: NodeJS.ProcessEnv;
580 readonly auth?: AntigravityAuthConfig;
581}): AcpSessionRuntime.AcpSpawnInput {
582 return {
583 command: input.installation.executablePath,
584 args: [
585 "acp",
586 "--gemini-dir",
587 input.profile.geminiHome,
588 "--app-data-dir",
589 // The CLI joins this beneath gemini-dir, including when the value is absolute.
590 "antigravity-acp",
591 ],
592 cwd: input.cwd,
593 env: antigravityEnvironment(
594 input.profile,
595 input.baseEnv ?? process.env,
596 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
597 ),
598 extendEnv: false,
599 };
601​
602/** Where `agy acp --login` sends Google; the page shows a code the user pastes back. */
603const ANTIGRAVITY_CODE_REDIRECT_URI = "https://antigravity.google/oauth-callback";
604​
605export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
606 function* (
607 authorizationUrl: string,
608 kind: "loopback" | "code" = "loopback",
609 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
610 const invalidUrl = () =>
611 authSupportError("Antigravity returned an invalid Google sign-in URL.");
612 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
613 return yield* invalidUrl();
614 }
615 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
616 const state = url.searchParams.get("state");
617 const redirectUri = url.searchParams.get("redirect_uri");
618 if (
619 url.origin !== "https://accounts.google.com" ||
620 url.pathname !== (kind === "loopback" ? "/o/oauth2/v2/auth" : "/o/oauth2/auth") ||
621 url.username !== "" ||
622 url.password !== "" ||
623 url.hash !== "" ||
624 url.searchParams.getAll("state").length !== 1 ||
625 url.searchParams.getAll("redirect_uri").length !== 1 ||
626 url.searchParams.getAll("response_type").length !== 1 ||
627 url.searchParams.get("response_type") !== "code" ||
628 state === null ||
629 state.length === 0 ||
630 state.length > 512 ||
631 /\s/.test(state) ||
632 redirectUri === null ||
633 (kind === "loopback"
634 ? !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
635 : redirectUri !== ANTIGRAVITY_CODE_REDIRECT_URI)
636 ) {
637 return yield* invalidUrl();
638 }
639 if (kind === "code") return { authorizationUrl, redirectUri, state };
640 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
641 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
642 return { authorizationUrl, redirectUri, state };
643 },
644);
645​
646/**
647 * What `agy acp --login` reads after its link: the code the Antigravity page shows, or that page's
648 * URL, which must answer this sign-in. Undefined for anything else, including any line break.
649 */
650export function antigravityLoginResponse(
651 pending: AntigravityAuthorizationUrl,
652 response: string,
653): string | undefined {
654 const value = response.trim();
655 if (/^[\w./~-]{1,2048}$/.test(value)) return value;
656 if (value.length > maxAuthorizationUrlLength || /\s/.test(value)) return undefined;
657 const url = URL.parse(value);
658 if (
659 url === null ||
660 `${url.origin}${url.pathname}` !== pending.redirectUri ||
661 url.username !== "" ||
662 url.password !== "" ||
663 url.searchParams.getAll("state").length !== 1 ||
664 url.searchParams.get("state") !== pending.state ||
665 url.searchParams.getAll("code").length !== 1 ||
666 !url.searchParams.get("code")
667 ) {
668 return undefined;
669 }
670 return value;
672​
673export function makeAntigravityStdoutTransform(
674 input: {
675 readonly onAuthorizationUrl?: (
676 authorizationUrl: string,
677 ) => Effect.Effect<void, AcpErrors.AcpError>;
678 } = {},
679) {
680 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
681 line: Uint8Array,
682 ) {
683 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
684 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
685 const request = yield* parseAntigravityAuthorizationUrl(
686 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
687 );
688 if (!input.onAuthorizationUrl) {
689 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
690 }
691 yield* input.onAuthorizationUrl(request.authorizationUrl);
692 return [];
693 });
694​
695 return (
696 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
697 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
698 Stream.suspend(() => {
699 let pending: Uint8Array[] = [];
700 let pendingBytes = 0;
701 const finishLine = () => {
702 const line = Buffer.concat(pending, pendingBytes);
703 pending = [];
704 pendingBytes = 0;
705 return line;
706 };
707 return stdout.pipe(
708 Stream.mapEffect(
709 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
710 const lines: Uint8Array[] = [];
711 let offset = 0;
712 while (offset < chunk.byteLength) {
713 const newline = chunk.indexOf(10, offset);
714 const end = newline === -1 ? chunk.byteLength : newline + 1;
715 const part = chunk.subarray(offset, end);
716 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
717 return yield* authSupportError(
718 "Antigravity sent a protocol line that is too large.",
719 );
720 }
721 pending.push(part);
722 pendingBytes += part.byteLength;
723 if (newline !== -1) lines.push(finishLine());
724 offset = end;
725 }
726 return lines;
727 }),
728 ),
729 Stream.flatMap(Stream.fromIterable),
730 Stream.concat(
731 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
732 ),
733 Stream.mapEffect(handleLine),
734 Stream.flatMap(Stream.fromIterable),
735 );
736 });
738​
739export function makeAntigravityStderrHandler(
740 input: {
741 readonly onAuthorizationUrl?: (
742 authorizationUrl: string,
743 ) => Effect.Effect<void, AcpErrors.AcpError>;
744 } = {},
745) {
746 let pending = "";
747 // Untraced: this runs for every stderr line.
748 const handleLine = Effect.fnUntraced(function* (line: string) {
749 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
750 if (message.length > maxBrowserHelperLineLength) return;
751 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
752 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
753 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
754 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
755 : undefined;
756 if (url === undefined) return;
757 yield* url.pipe(
758 Effect.flatMap(parseAntigravityAuthorizationUrl),
759 Effect.matchEffect({
760 onFailure: () => Effect.void,
761 onSuccess: (request) =>
762 input.onAuthorizationUrl
763 ? input.onAuthorizationUrl(request.authorizationUrl)
764 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
765 }),
766 );
767 });
768​
769 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
770 const lines = `${pending}${text}`.split("\n");
771 pending = lines.pop() ?? "";
772 if (pending.length > maxBrowserHelperLineLength) pending = "";
773 yield* Effect.forEach(lines, handleLine, { discard: true });
774 });