Open History to see the last commit
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 { HostProcessPlatform } 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 Encoding from "effect/Encoding";
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/unstable/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
17import * as AcpErrors from "effect-acp/errors";
18
19import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
20import type { AcpSpawnInput } from "./acp/AcpSessionRuntime.ts";
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// Keep this source free of both colons and semicolons. EPIPE must still exit 0
56// so Python does not fall back to an OS browser after 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 /** Parent of the per-process temp directories PyInstaller unpacks into. */
89 readonly tempDirectory: string;
90 readonly browserCommand: string;
91}
92
93/**
94 * Credentials for the non-personal ACP auth methods. The agent reads the API
95 * key from its environment and the GCP project and location from
96 * `settings.json` in the profile. Empty strings mean "not set".
97 */
98export interface AntigravityAuthConfig {
99 readonly authMethod: AntigravityAuthMethod;
100 readonly apiKey: string;
101 readonly gcpProject: string;
102 readonly gcpLocation: string;
103}
104
105export const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
106 authMethod: "oauth-personal",
107 apiKey: "",
108 gcpProject: "",
109 gcpLocation: "",
110};
111
112/** True for the two methods that open a Google sign-in page. */
113export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
114 return authMethod === "oauth-personal" || authMethod === "oauth-business";
115}
116
117/** Label shown on the provider card once the method has authenticated. */
118export function antigravityAuthLabel(authMethod: AntigravityAuthMethod): string {
119 switch (authMethod) {
120 case "oauth-personal":
121 return "Google account";
122 case "oauth-business":
123 return "Gemini Enterprise";
124 case "gemini-api-key":
125 return "Gemini API key";
126 case "agent-platform":
127 return "Agent Platform";
128 }
129}
130
131/**
132 * Explains what is missing before a non-personal method can authenticate, or
133 * null when the config is complete. Personal sign-in never needs config.
134 */
135export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string | null {
136 switch (auth.authMethod) {
137 case "oauth-personal":
138 return null;
139 case "oauth-business":
140 return auth.gcpProject && auth.gcpLocation
141 ? null
142 : "Gemini Enterprise needs a GCP project and location in the Antigravity provider settings.";
143 case "gemini-api-key":
144 return auth.apiKey ? null : "Enter a Gemini API key in the Antigravity provider settings.";
145 case "agent-platform":
146 return auth.apiKey || (auth.gcpProject && auth.gcpLocation)
147 ? null
148 : "Agent Platform needs an API key, or a GCP project and location, in the Antigravity provider settings.";
149 }
150}
151
152/**
153 * `settings.json` content for the agent's profile. `auth.type` names the
154 * selected method so a native logout clears only that method's credentials
155 * instead of every stored token. The GCP block feeds Enterprise and Agent
156 * Platform. Never holds a credential.
157 */
158export function antigravityProfileSettings(auth: AntigravityAuthConfig): string {
159 const gcp = {
160 ...(auth.gcpProject ? { project: auth.gcpProject } : {}),
161 ...(auth.gcpLocation ? { location: auth.gcpLocation } : {}),
162 };
163 return `${encodeProfileSettings({
164 auth: { type: auth.authMethod },
165 ...(Object.keys(gcp).length > 0 ? { gcp } : {}),
166 })}\n`;
167}
168
169export interface AntigravityAuthorizationUrl {
170 readonly authorizationUrl: string;
171 readonly redirectUri: string;
172 readonly state: string;
173}
174
175function authSupportError(detail: string) {
176 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
177}
178
179/** Recognizes native auth failures and interactive login blocked by T3. */
180export function isAntigravitySignInRequiredError(error: unknown): boolean {
181 return (
182 (isAcpRequestError(error) && error.code === -32000) ||
183 (isAcpTransportError(error) && error.detail === ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)
184 );
185}
186
187export interface AntigravityInstanceDirectories {
188 /** GEMINI_HOME for the agent. Holds the instance's Google sign-in. */
189 readonly profile: string;
190 /**
191 * Parent of the per-process directories the agent unpacks into. It sits
192 * beside the profile, not inside it: the agent unpacks members up to 120
193 * characters deep, and the profile's longer name would push them past
194 * Windows' 260-character path limit.
195 */
196 readonly runtimeTemp: string;
197}
198
199/** Hashes the instance ID so case-only differences stay separate on case-insensitive filesystems. */
200export const resolveAntigravityInstanceDirectories = Effect.fn(
201 "resolveAntigravityInstanceDirectories",
202)(function* (stateDir: string, instanceId: ProviderInstanceId) {
203 const crypto = yield* Crypto.Crypto;
204 const path = yield* Path.Path;
205 const key = Encoding.encodeHex(
206 yield* crypto.digest("SHA-256", new TextEncoder().encode(instanceId)),
207 );
208 return {
209 profile: path.join(stateDir, "providers", "antigravity", key),
210 runtimeTemp: path.join(stateDir, "antigravity-tmp", key.slice(0, 12)),
211 } satisfies AntigravityInstanceDirectories;
212});
213
214function quoteBrowserArgument(value: string): string {
215 return `'${value.replaceAll("'", `'"'"'`)}'`;
216}
217
218function antigravityEnvironment(
219 profile: AntigravityProfile,
220 baseEnv: NodeJS.ProcessEnv,
221 auth: AntigravityAuthConfig,
222 runtimeTempDirectory?: string,
223) {
224 const environment: NodeJS.ProcessEnv = {};
225 for (const [key, value] of Object.entries(baseEnv)) {
226 // Windows treats environment keys as case-insensitive. Remove aliases too.
227 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
228 }
229 // Only the configured method's credential reaches the agent. The agent
230 // prefers GOOGLE_API_KEY over the GCP pair for Agent Platform, so the pair
231 // goes through settings.json instead of the environment.
232 const credential =
233 auth.authMethod === "gemini-api-key" && auth.apiKey
234 ? { GEMINI_API_KEY: auth.apiKey }
235 : auth.authMethod === "agent-platform" && auth.apiKey
236 ? { GOOGLE_API_KEY: auth.apiKey }
237 : {};
238 // The agent is a PyInstaller one-file bundle. It unpacks about 1 GB into
239 // the system temp directory per launch and a force kill leaves that behind.
240 // Point it at a T3-owned directory so the driver can reclaim the space.
241 const tempDirectory = runtimeTempDirectory ?? profile.tempDirectory;
242 return {
243 ...environment,
244 ...credential,
245 GEMINI_HOME: profile.geminiHome,
246 AGY_ACP_FORCE_FILE_STORAGE: "1",
247 BROWSER: profile.browserCommand,
248 PYTHONUNBUFFERED: "1",
249 ELECTRON_RUN_AS_NODE: "1",
250 ...(profile.platform === "win32"
251 ? { TEMP: tempDirectory, TMP: tempDirectory }
252 : { TMPDIR: tempDirectory }),
253 };
254}
255
256/**
257 * The agent reads its user-global skills under `GEMINI_HOME`, which T3 points
258 * at the private profile. Link the two skill directories back to the user's
259 * real `~/.gemini` so global skills load, while MCP servers, hooks, and
260 * credentials stay isolated. Best effort: a link that cannot be made only
261 * costs global skills, never the session. A real directory at the link path
262 * is the user's own content and is left alone.
263 */
264const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(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 links = antigravityUserSkillDirectories(path, input.profileDirectory);
272 const targets = antigravityUserSkillDirectories(path, path.join(input.userHome, ".gemini"));
273 for (const [link, target] of [
274 [links[0], targets[0]],
275 [links[1], targets[1]],
276 ] as const) {
277 yield* Effect.gen(function* () {
278 const existing = yield* fs.readLink(link).pipe(
279 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
280 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
281 );
282 if (existing === target) return;
283 if (existing !== undefined) {
284 yield* fs.remove(link);
285 }
286 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
287 yield* Effect.tryPromise(() =>
288 NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
289 );
290 }).pipe(
291 // A non-symlink at the link path fails `readLink`; anything else is a
292 // filesystem refusal. Both leave the profile usable.
293 Effect.catch((error) =>
294 Effect.logWarning("Antigravity user skills are not linked into the profile.", {
295 link,
296 target,
297 error,
298 }),
299 ),
300 );
301 }
302});
303
304/** Prepares a private profile without reading or copying Google credentials. */
305export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
306 readonly profileDirectory: string;
307 readonly baseEnv?: NodeJS.ProcessEnv;
308 readonly runtimeExecutablePath?: string;
309 readonly platform?: NodeJS.Platform;
310 readonly auth?: AntigravityAuthConfig;
311 /** Home the agent expands `~` against. Defaults to the launch environment's. */
312 readonly userHome?: string;
313 /** Parent of per-process temp directories. Defaults to one inside the profile. */
314 readonly tempDirectory?: string;
315}) {
316 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
317 const fs = yield* FileSystem.FileSystem;
318 const path = yield* Path.Path;
319 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
320 const platform = input.platform ?? (yield* HostProcessPlatform);
321 const userHome =
322 input.userHome ?? resolveAntigravityUserHome(platform, input.baseEnv ?? process.env);
323 const runtimeExecutablePath =
324 input.runtimeExecutablePath ??
325 (yield* resolveNodeExecutable("Antigravity sign-in", input.baseEnv).pipe(
326 Effect.mapError(
327 (cause) =>
328 new AcpErrors.AcpTransportError({
329 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
330 cause,
331 }),
332 ),
333 ));
334 const helperExecutable =
335 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
336 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
337 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
338 if (
339 browserCommand.includes(platform === "win32" ? ";" : ":") ||
340 helperExecutable.includes("\r") ||
341 helperExecutable.includes("\n") ||
342 helperExecutable.includes("\0") ||
343 helperExecutable.includes("%s")
344 ) {
345 return yield* authSupportError(
346 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
347 );
348 }
349
350 const geminiHome = path.resolve(input.profileDirectory);
351 const acpDirectory = path.join(geminiHome, "antigravity-acp");
352 const tempDirectory = input.tempDirectory ?? path.join(acpDirectory, "tmp");
353 const profile: AntigravityProfile = {
354 platform,
355 geminiHome,
356 acpDirectory,
357 tokenPath: path.join(acpDirectory, "acp_token.json"),
358 tempDirectory,
359 browserCommand,
360 };
361 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
362 yield* Effect.gen(function* () {
363 const child = yield* spawner.spawn(
364 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
365 env: environment,
366 extendEnv: false,
367 shell: false,
368 }),
369 );
370 const [stdout, stderr, exitCode] = yield* Effect.all(
371 [
372 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
373 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
374 child.exitCode,
375 ],
376 { concurrency: "unbounded" },
377 );
378 if (
379 Number(exitCode) !== 0 ||
380 stdout.bytes !== 0 ||
381 stdout.truncated ||
382 stderr.truncated ||
383 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
384 ) {
385 return yield* authSupportError("Antigravity browser suppression could not be verified.");
386 }
387 }).pipe(
388 Effect.scoped,
389 Effect.timeoutOrElse({
390 duration: "5 seconds",
391 orElse: () =>
392 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
393 }),
394 Effect.mapError((error) =>
395 error._tag === "AcpTransportError"
396 ? error
397 : authSupportError("Antigravity browser suppression could not be verified."),
398 ),
399 );
400
401 for (const directory of [geminiHome, acpDirectory, tempDirectory]) {
402 yield* fs
403 .makeDirectory(directory, { recursive: true, mode: 0o700 })
404 .pipe(
405 Effect.mapError(() =>
406 authSupportError("The Antigravity profile directory could not be created."),
407 ),
408 );
409 if (platform !== "win32") {
410 yield* fs
411 .chmod(directory, 0o700)
412 .pipe(
413 Effect.mapError(() =>
414 authSupportError("The Antigravity profile directory permissions could not be set."),
415 ),
416 );
417 }
418 }
419 // Rewriting on every launch keeps a method, project, or location edit in
420 // Settings effective. The agent also records auth.type here after a
421 // sign-in, which matches the value written below.
422 yield* fs
423 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
424 .pipe(
425 Effect.mapError(() =>
426 authSupportError("The Antigravity profile settings could not be written."),
427 ),
428 );
429 yield* linkAntigravityUserSkills({ profileDirectory: geminiHome, userHome, platform });
430 return profile;
431});
432
433/** Applies the same subscription-only launch settings to every ACP process. */
434export function buildAntigravityAcpSpawnInput(input: {
435 readonly installation: {
436 readonly executablePath: string;
437 readonly harnessPath: string;
438 };
439 readonly profile: AntigravityProfile;
440 readonly cwd: string;
441 readonly baseEnv?: NodeJS.ProcessEnv;
442 readonly auth?: AntigravityAuthConfig;
443 /** Per-process temp directory. Defaults to the profile's shared temp directory. */
444 readonly runtimeTempDirectory?: string;
445}): AcpSpawnInput {
446 return {
447 command: input.installation.executablePath,
448 args: input.profile.platform === "linux" ? ["--uid="] : [],
449 cwd: input.cwd,
450 env: {
451 ...antigravityEnvironment(
452 input.profile,
453 input.baseEnv ?? process.env,
454 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
455 input.runtimeTempDirectory,
456 ),
457 ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath,
458 },
459 extendEnv: false,
460 };
461}
462
463/** Reads only the public authorization request, never an OAuth token file. */
464export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
465 function* (
466 authorizationUrl: string,
467 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
468 const invalidUrl = () =>
469 authSupportError("Antigravity returned an invalid Google sign-in URL.");
470 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
471 return yield* invalidUrl();
472 }
473 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
474 const state = url.searchParams.get("state");
475 const redirectUri = url.searchParams.get("redirect_uri");
476 if (
477 url.origin !== "https://accounts.google.com" ||
478 url.pathname !== "/o/oauth2/v2/auth" ||
479 url.username !== "" ||
480 url.password !== "" ||
481 url.hash !== "" ||
482 url.searchParams.getAll("state").length !== 1 ||
483 url.searchParams.getAll("redirect_uri").length !== 1 ||
484 url.searchParams.getAll("response_type").length !== 1 ||
485 url.searchParams.get("response_type") !== "code" ||
486 state === null ||
487 state.length === 0 ||
488 state.length > 512 ||
489 /\s/.test(state) ||
490 redirectUri === null ||
491 !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
492 ) {
493 return yield* invalidUrl();
494 }
495 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
496 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
497 return { authorizationUrl, redirectUri, state };
498 },
499);
500
501export function makeAntigravityStdoutTransform(
502 input: {
503 readonly onAuthorizationUrl?: (
504 authorizationUrl: string,
505 ) => Effect.Effect<void, AcpErrors.AcpError>;
506 } = {},
507) {
508 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
509 line: Uint8Array,
510 ) {
511 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
512 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
513 const request = yield* parseAntigravityAuthorizationUrl(
514 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
515 );
516 if (!input.onAuthorizationUrl) {
517 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
518 }
519 yield* input.onAuthorizationUrl(request.authorizationUrl);
520 return [];
521 });
522
523 return (
524 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
525 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
526 Stream.suspend(() => {
527 let pending: Uint8Array[] = [];
528 let pendingBytes = 0;
529 const finishLine = () => {
530 const line = Buffer.concat(pending, pendingBytes);
531 pending = [];
532 pendingBytes = 0;
533 return line;
534 };
535 return stdout.pipe(
536 Stream.mapEffect(
537 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
538 const lines: Uint8Array[] = [];
539 let offset = 0;
540 while (offset < chunk.byteLength) {
541 const newline = chunk.indexOf(10, offset);
542 const end = newline === -1 ? chunk.byteLength : newline + 1;
543 const part = chunk.subarray(offset, end);
544 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
545 return yield* authSupportError(
546 "Antigravity sent a protocol line that is too large.",
547 );
548 }
549 pending.push(part);
550 pendingBytes += part.byteLength;
551 if (newline !== -1) lines.push(finishLine());
552 offset = end;
553 }
554 return lines;
555 }),
556 ),
557 Stream.flatMap(Stream.fromIterable),
558 Stream.concat(
559 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
560 ),
561 Stream.mapEffect(handleLine),
562 Stream.flatMap(Stream.fromIterable),
563 );
564 });
565}
566
567/** Receives native 1.1.1 sign-in URLs and T3 browser-helper URLs without logging stderr. */
568export function makeAntigravityStderrHandler(
569 input: {
570 readonly onAuthorizationUrl?: (
571 authorizationUrl: string,
572 ) => Effect.Effect<void, AcpErrors.AcpError>;
573 } = {},
574) {
575 let pending = "";
576 const handleLine = (line: string) => {
577 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
578 if (message.length > maxBrowserHelperLineLength) {
579 return Effect.void;
580 }
581 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
582 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
583 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
584 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
585 : undefined;
586 if (url === undefined) return Effect.void;
587 return url.pipe(
588 Effect.flatMap(parseAntigravityAuthorizationUrl),
589 Effect.matchEffect({
590 onFailure: () => Effect.void,
591 onSuccess: (request) =>
592 input.onAuthorizationUrl
593 ? input.onAuthorizationUrl(request.authorizationUrl)
594 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
595 }),
596 );
597 };
598
599 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
600 const lines = `${pending}${text}`.split("\n");
601 pending = lines.pop() ?? "";
602 if (pending.length > maxBrowserHelperLineLength) pending = "";
603 yield* Effect.forEach(lines, handleLine, { discard: true });
604 });
605}