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

antigravityAuthSupport.ts

628 lines22.7 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 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 path separators before parsing quotes. Exit 0 on EPIPE to prevent browser fallback after cancellation.
55const browserHelperSource =
56 `process.stderr.on("error",()=>process.exit(0)).write(` +
57 `"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` +
58 `()=>process.exit(0))`;
59const browserPreflightUrl = "https://example.invalid/t3-antigravity-browser-preflight";
60​
61const removedEnvironmentKeys = new Set([
62 "GEMINI_API_KEY",
63 "GOOGLE_API_KEY",
64 "GOOGLE_APPLICATION_CREDENTIALS",
65 "GOOGLE_CLOUD_PROJECT",
66 "GOOGLE_CLOUD_LOCATION",
67 "GOOGLE_CLOUD_QUOTA_PROJECT",
68 "GOOGLE_GENAI_USE_VERTEXAI",
69 "GCLOUD_PROJECT",
70 "CLOUDSDK_CORE_PROJECT",
71 "AGY_ACP_CCPA_PROJECT",
72 "AGY_ACP_ENABLE_OAUTH",
73 "GEMINI_HOME",
74 "AGY_ACP_FORCE_FILE_STORAGE",
75 "ANTIGRAVITY_HARNESS_PATH",
76 "BROWSER",
77 "PYTHONUNBUFFERED",
78 "ELECTRON_RUN_AS_NODE",
79]);
80​
81export interface AntigravityProfile {
82 readonly platform: NodeJS.Platform;
83 readonly geminiHome: string;
84 readonly acpDirectory: string;
85 readonly tokenPath: string;
86 readonly tempDirectory: string;
87 readonly browserCommand: string;
88 readonly caBundlePath?: string;
90​
91export interface AntigravityAuthConfig {
92 readonly authMethod: AntigravityAuthMethod;
93 readonly apiKey: string;
94 readonly gcpProject: string;
95 readonly gcpLocation: string;
97​
98const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
99 authMethod: "oauth-personal",
100 apiKey: "",
101 gcpProject: "",
102 gcpLocation: "",
103};
104​
105export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
106 return authMethod === "oauth-personal" || authMethod === "oauth-business";
108​
109export function antigravityAuthLabel(authMethod: AntigravityAuthMethod): string {
110 switch (authMethod) {
111 case "oauth-personal":
112 return "Google account";
113 case "oauth-business":
114 return "Gemini Enterprise";
115 case "gemini-api-key":
116 return "Gemini API key";
117 case "agent-platform":
118 return "Agent Platform";
119 }
121​
122export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string | null {
123 switch (auth.authMethod) {
124 case "oauth-personal":
125 return null;
126 case "oauth-business":
127 return auth.gcpProject && auth.gcpLocation
128 ? null
129 : "Gemini Enterprise needs a GCP project and location in the Antigravity provider settings.";
130 case "gemini-api-key":
131 return auth.apiKey ? null : "Enter a Gemini API key in the Antigravity provider settings.";
132 case "agent-platform":
133 return auth.apiKey || (auth.gcpProject && auth.gcpLocation)
134 ? null
135 : "Agent Platform needs an API key, or a GCP project and location, in the Antigravity provider settings.";
136 }
138​
139/**
140 * `auth.type` names the selected method so a native logout clears only that method's credentials
141 * instead of every stored token. Never holds a credential.
142 */
143function antigravityProfileSettings(auth: AntigravityAuthConfig): string {
144 const gcp = {
145 ...(auth.gcpProject ? { project: auth.gcpProject } : {}),
146 ...(auth.gcpLocation ? { location: auth.gcpLocation } : {}),
147 };
148 return `${encodeProfileSettings({
149 auth: { type: auth.authMethod },
150 ...(Object.keys(gcp).length > 0 ? { gcp } : {}),
151 })}\n`;
153​
154export interface AntigravityAuthorizationUrl {
155 readonly authorizationUrl: string;
156 readonly redirectUri: string;
157 readonly state: string;
159​
160function authSupportError(detail: string) {
161 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
163​
164export function isAntigravitySignInRequiredError(error: unknown): boolean {
165 return (
166 (isAcpRequestError(error) && error.code === -32000) ||
167 (isAcpTransportError(error) && error.detail === ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)
168 );
170​
171export interface AntigravityInstanceDirectories {
172 readonly profile: string;
173 /** Keep beside the profile: 120-character archive members under its longer name would exceed Windows' 260-character limit. */
174 readonly runtimeTemp: string;
176​
177/** Hashes the instance ID so case-only differences stay separate on case-insensitive filesystems. */
178export const resolveAntigravityInstanceDirectories = Effect.fn(
179 "resolveAntigravityInstanceDirectories",
180)(function* (stateDir: string, instanceId: ProviderInstanceId) {
181 const digest = yield* Digest.Digest;
182 const path = yield* Path.Path;
183 const key = Hex.encode(yield* digest.digest(Digest.sha256, new TextEncoder().encode(instanceId)));
184 return {
185 profile: path.join(stateDir, "providers", "antigravity", key),
186 runtimeTemp: path.join(stateDir, "antigravity-tmp", key.slice(0, 12)),
187 } satisfies AntigravityInstanceDirectories;
188});
189​
190function quoteBrowserArgument(value: string): string {
191 return `'${value.replaceAll("'", `'"'"'`)}'`;
193​
194function antigravityEnvironment(
195 profile: AntigravityProfile,
196 baseEnv: NodeJS.ProcessEnv,
197 auth: AntigravityAuthConfig,
198 runtimeTempDirectory?: string,
199) {
200 const environment: NodeJS.ProcessEnv = {};
201 for (const [key, value] of Object.entries(baseEnv)) {
202 // Windows treats environment keys as case-insensitive. Remove aliases too.
203 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
204 }
205 // Put the GCP pair in settings.json because GOOGLE_API_KEY takes precedence in the environment.
206 const credential =
207 auth.authMethod === "gemini-api-key" && auth.apiKey
208 ? { GEMINI_API_KEY: auth.apiKey }
209 : auth.authMethod === "agent-platform" && auth.apiKey
210 ? { GOOGLE_API_KEY: auth.apiKey }
211 : {};
212 // Each launch unpacks about 1 GB; use T3-owned temp so the driver can reclaim files after force-kill.
213 const tempDirectory = runtimeTempDirectory ?? profile.tempDirectory;
214 return {
215 ...environment,
216 ...credential,
217 ...(profile.caBundlePath !== undefined &&
218 baseEnv.SSL_CERT_FILE === undefined &&
219 baseEnv.SSL_CERT_DIR === undefined
220 ? { SSL_CERT_FILE: profile.caBundlePath }
221 : {}),
222 GEMINI_HOME: profile.geminiHome,
223 AGY_ACP_FORCE_FILE_STORAGE: "1",
224 BROWSER: profile.browserCommand,
225 PYTHONUNBUFFERED: "1",
226 ELECTRON_RUN_AS_NODE: "1",
227 ...(profile.platform === "win32"
228 ? { TEMP: tempDirectory, TMP: tempDirectory }
229 : { TMPDIR: tempDirectory }),
230 };
232​
233class AntigravitySkillLinkError extends Schema.TaggedError<AntigravitySkillLinkError>()(
234 "AntigravitySkillLinkError",
235 { link: Schema.String, cause: Schema.Defect() },
236) {
237 override get message(): string {
238 return `Could not link Antigravity user skills at ${this.link}.`;
239 }
241​
242/** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills from the real ~/.gemini. */
243const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: {
244 readonly profileDirectory: string;
245 readonly userHome: string;
246 readonly platform: NodeJS.Platform;
247}): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
248 const fs = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const links = antigravityUserSkillDirectories(path, input.profileDirectory);
251 const targets = antigravityUserSkillDirectories(path, path.join(input.userHome, ".gemini"));
252 for (const [link, target] of [
253 [links[0], targets[0]],
254 [links[1], targets[1]],
255 ] as const) {
256 yield* Effect.gen(function* () {
257 // The harness creates these folders itself, and mkdir fails on a dangling link.
258 if (!(yield* fs.exists(target))) {
259 const linked = yield* fs.readLink(link).pipe(
260 Effect.as(true),
261 Effect.orElseSucceed(() => false),
262 );
263 if (linked) yield* fs.remove(link);
264 return;
265 }
266 const existing = yield* fs.readLink(link).pipe(
267 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
268 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
269 // An empty folder is the harness's placeholder from a launch without the link.
270 // rmdir refuses a non-empty folder, so content added meanwhile is never deleted.
271 Effect.catch((error) =>
272 Effect.tryPromise({
273 try: () => NodeFSP.rmdir(link),
274 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
275 }).pipe(
276 Effect.as(undefined),
277 Effect.mapError(() => error),
278 ),
279 ),
280 );
281 if (existing === target) return;
282 if (existing !== undefined) {
283 yield* fs.remove(link);
284 }
285 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
286 yield* Effect.tryPromise({
287 try: () => NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
288 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
289 });
290 }).pipe(
291 Effect.catch((error) =>
292 Effect.logWarning("Antigravity user skills are not linked into the profile.", {
293 link,
294 target,
295 error,
296 }),
297 ),
298 );
299 }
300});
301​
302export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
303 readonly profileDirectory: string;
304 readonly baseEnv?: NodeJS.ProcessEnv;
305 readonly runtimeExecutablePath?: string;
306 readonly platform?: NodeJS.Platform;
307 readonly auth?: AntigravityAuthConfig;
308 readonly userHome?: string;
309 readonly tempDirectory?: string;
310}) {
311 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
312 const fs = yield* FileSystem.FileSystem;
313 const path = yield* Path.Path;
314 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
315 const platform = input.platform ?? (yield* HostProcess.Platform);
316 const userHome =
317 input.userHome ??
318 resolveAntigravityUserHome(
319 platform,
320 input.baseEnv ?? process.env,
321 yield* HostProcess.HomeDirectory,
322 );
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 let caBundlePath: string | undefined;
354 if (platform === "linux") {
355 // Bundled Python may look for certificates at paths absent on this distribution.
356 // Relative paths would resolve differently when the agent runs in the project directory.
357 for (const candidate of [
358 (input.baseEnv ?? process.env).NIX_SSL_CERT_FILE,
359 "/etc/ssl/certs/ca-bundle.crt",
360 "/etc/ssl/certs/ca-certificates.crt",
361 "/etc/pki/tls/certs/ca-bundle.crt",
362 "/etc/ssl/cert.pem",
363 ]) {
364 if (
365 candidate &&
366 path.isAbsolute(candidate) &&
367 (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)))
368 ) {
369 caBundlePath = candidate;
370 break;
371 }
372 }
373 }
374 const profile: AntigravityProfile = {
375 platform,
376 geminiHome,
377 acpDirectory,
378 tokenPath: path.join(acpDirectory, "acp_token.json"),
379 tempDirectory,
380 browserCommand,
381 ...(caBundlePath === undefined ? {} : { caBundlePath }),
382 };
383 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
384 yield* Effect.gen(function* () {
385 const child = yield* spawner.spawn(
386 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
387 env: environment,
388 extendEnv: false,
389 shell: false,
390 }),
391 );
392 const [stdout, stderr, exitCode] = yield* Effect.all(
393 [
394 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
395 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
396 child.exitCode,
397 ],
398 { concurrency: "unbounded" },
399 );
400 if (
401 Number(exitCode) !== 0 ||
402 stdout.bytes !== 0 ||
403 stdout.truncated ||
404 stderr.truncated ||
405 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
406 ) {
407 return yield* authSupportError("Antigravity browser suppression could not be verified.");
408 }
409 }).pipe(
410 Effect.scoped,
411 Effect.timeoutOrElse({
412 duration: "30 seconds",
413 orElse: () =>
414 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
415 }),
416 Effect.mapError((error) =>
417 error._tag === "AcpTransportError"
418 ? error
419 : authSupportError("Antigravity browser suppression could not be verified."),
420 ),
421 );
422​
423 for (const directory of [geminiHome, acpDirectory, tempDirectory]) {
424 yield* fs
425 .makeDirectory(directory, { recursive: true, mode: 0o700 })
426 .pipe(
427 Effect.mapError(() =>
428 authSupportError("The Antigravity profile directory could not be created."),
429 ),
430 );
431 if (platform !== "win32") {
432 yield* fs
433 .chmod(directory, 0o700)
434 .pipe(
435 Effect.mapError(() =>
436 authSupportError("The Antigravity profile directory permissions could not be set."),
437 ),
438 );
439 }
440 }
441 yield* fs
442 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
443 .pipe(
444 Effect.mapError(() =>
445 authSupportError("The Antigravity profile settings could not be written."),
446 ),
447 );
448 yield* linkAntigravityUserSkills({ profileDirectory: geminiHome, userHome, platform });
449 return profile;
450});
451​
452export function buildAntigravityAcpSpawnInput(input: {
453 readonly installation: {
454 readonly executablePath: string;
455 readonly harnessPath: string | null;
456 };
457 readonly profile: AntigravityProfile;
458 readonly cwd: string;
459 readonly baseEnv?: NodeJS.ProcessEnv;
460 readonly auth?: AntigravityAuthConfig;
461 readonly runtimeTempDirectory?: string;
462}): AcpSessionRuntime.AcpSpawnInput {
463 return {
464 command: input.installation.executablePath,
465 // The agy CLI has no harness sibling and serves ACP through its `acp` subcommand.
466 args:
467 input.installation.harnessPath === null
468 ? ["acp"]
469 : input.profile.platform === "linux"
470 ? ["--uid="]
471 : [],
472 cwd: input.cwd,
473 env: {
474 ...antigravityEnvironment(
475 input.profile,
476 input.baseEnv ?? process.env,
477 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
478 input.runtimeTempDirectory,
479 ),
480 ...(input.installation.harnessPath === null
481 ? {}
482 : { ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath }),
483 },
484 extendEnv: false,
485 };
487​
488export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
489 function* (
490 authorizationUrl: string,
491 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
492 const invalidUrl = () =>
493 authSupportError("Antigravity returned an invalid Google sign-in URL.");
494 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
495 return yield* invalidUrl();
496 }
497 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
498 const state = url.searchParams.get("state");
499 const redirectUri = url.searchParams.get("redirect_uri");
500 if (
501 url.origin !== "https://accounts.google.com" ||
502 url.pathname !== "/o/oauth2/v2/auth" ||
503 url.username !== "" ||
504 url.password !== "" ||
505 url.hash !== "" ||
506 url.searchParams.getAll("state").length !== 1 ||
507 url.searchParams.getAll("redirect_uri").length !== 1 ||
508 url.searchParams.getAll("response_type").length !== 1 ||
509 url.searchParams.get("response_type") !== "code" ||
510 state === null ||
511 state.length === 0 ||
512 state.length > 512 ||
513 /\s/.test(state) ||
514 redirectUri === null ||
515 !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
516 ) {
517 return yield* invalidUrl();
518 }
519 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
520 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
521 return { authorizationUrl, redirectUri, state };
522 },
523);
524​
525export function makeAntigravityStdoutTransform(
526 input: {
527 readonly onAuthorizationUrl?: (
528 authorizationUrl: string,
529 ) => Effect.Effect<void, AcpErrors.AcpError>;
530 } = {},
531) {
532 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
533 line: Uint8Array,
534 ) {
535 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
536 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
537 const request = yield* parseAntigravityAuthorizationUrl(
538 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
539 );
540 if (!input.onAuthorizationUrl) {
541 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
542 }
543 yield* input.onAuthorizationUrl(request.authorizationUrl);
544 return [];
545 });
546​
547 return (
548 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
549 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
550 Stream.suspend(() => {
551 let pending: Uint8Array[] = [];
552 let pendingBytes = 0;
553 const finishLine = () => {
554 const line = Buffer.concat(pending, pendingBytes);
555 pending = [];
556 pendingBytes = 0;
557 return line;
558 };
559 return stdout.pipe(
560 Stream.mapEffect(
561 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
562 const lines: Uint8Array[] = [];
563 let offset = 0;
564 while (offset < chunk.byteLength) {
565 const newline = chunk.indexOf(10, offset);
566 const end = newline === -1 ? chunk.byteLength : newline + 1;
567 const part = chunk.subarray(offset, end);
568 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
569 return yield* authSupportError(
570 "Antigravity sent a protocol line that is too large.",
571 );
572 }
573 pending.push(part);
574 pendingBytes += part.byteLength;
575 if (newline !== -1) lines.push(finishLine());
576 offset = end;
577 }
578 return lines;
579 }),
580 ),
581 Stream.flatMap(Stream.fromIterable),
582 Stream.concat(
583 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
584 ),
585 Stream.mapEffect(handleLine),
586 Stream.flatMap(Stream.fromIterable),
587 );
588 });
590​
591export function makeAntigravityStderrHandler(
592 input: {
593 readonly onAuthorizationUrl?: (
594 authorizationUrl: string,
595 ) => Effect.Effect<void, AcpErrors.AcpError>;
596 } = {},
597) {
598 let pending = "";
599 const handleLine = (line: string) => {
600 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
601 if (message.length > maxBrowserHelperLineLength) {
602 return Effect.void;
603 }
604 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
605 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
606 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
607 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
608 : undefined;
609 if (url === undefined) return Effect.void;
610 return url.pipe(
611 Effect.flatMap(parseAntigravityAuthorizationUrl),
612 Effect.matchEffect({
613 onFailure: () => Effect.void,
614 onSuccess: (request) =>
615 input.onAuthorizationUrl
616 ? input.onAuthorizationUrl(request.authorizationUrl)
617 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
618 }),
619 );
620 };
621​
622 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
623 const lines = `${pending}${text}`.split("\n");
624 pending = lines.pop() ?? "";
625 if (pending.length > maxBrowserHelperLineLength) pending = "";
626 yield* Effect.forEach(lines, handleLine, { discard: true });
627 });