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

antigravityAuthSupport.ts

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