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

antigravityAuthSupport.ts

653 lines24.2 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 // An inherited pipe whose owner exited makes Electron-as-Node print Crashpad errors to stderr.
80 "CHROME_CRASHPAD_PIPE_NAME",
81]);
82​
83export interface AntigravityProfile {
84 readonly platform: NodeJS.Platform;
85 readonly geminiHome: string;
86 readonly acpDirectory: string;
87 readonly tokenPath: string;
88 readonly tempDirectory: string;
89 readonly browserCommand: string;
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 /** Keep beside the profile: 120-character archive members under its longer name would exceed Windows' 260-character limit. */
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 runtimeTempDirectory?: string,
206) {
207 const environment: NodeJS.ProcessEnv = {};
208 for (const [key, value] of Object.entries(baseEnv)) {
209 // Windows treats environment keys as case-insensitive. Remove aliases too.
210 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
211 }
212 // Put the GCP pair in settings.json because GOOGLE_API_KEY takes precedence in the environment.
213 const credential =
214 auth.authMethod === "gemini-api-key" && auth.apiKey
215 ? { GEMINI_API_KEY: auth.apiKey }
216 : auth.authMethod === "agent-platform" && auth.apiKey
217 ? { GOOGLE_API_KEY: auth.apiKey }
218 : {};
219 // Each launch unpacks about 1 GB; use T3-owned temp so the driver can reclaim files after force-kill.
220 const tempDirectory = runtimeTempDirectory ?? profile.tempDirectory;
221 return {
222 ...environment,
223 ...credential,
224 ...(profile.caBundlePath !== undefined &&
225 baseEnv.SSL_CERT_FILE === undefined &&
226 baseEnv.SSL_CERT_DIR === undefined
227 ? { SSL_CERT_FILE: profile.caBundlePath }
228 : {}),
229 GEMINI_HOME: profile.geminiHome,
230 AGY_ACP_FORCE_FILE_STORAGE: "1",
231 BROWSER: profile.browserCommand,
232 PYTHONUNBUFFERED: "1",
233 ELECTRON_RUN_AS_NODE: "1",
234 ...(profile.platform === "win32"
235 ? { TEMP: tempDirectory, TMP: tempDirectory }
236 : { TMPDIR: tempDirectory }),
237 };
239​
240class AntigravitySkillLinkError extends Schema.TaggedError<AntigravitySkillLinkError>()(
241 "AntigravitySkillLinkError",
242 { link: Schema.String, cause: Schema.Defect() },
243) {
244 override get message(): string {
245 return `Could not link Antigravity user skills at ${this.link}.`;
246 }
248​
249/** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills from the real ~/.gemini. */
250const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: {
251 readonly profileDirectory: string;
252 readonly userHome: string;
253 readonly platform: NodeJS.Platform;
254}): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
255 const fs = yield* FileSystem.FileSystem;
256 const path = yield* Path.Path;
257 const links = antigravityUserSkillDirectories(path, input.profileDirectory);
258 const targets = antigravityUserSkillDirectories(path, path.join(input.userHome, ".gemini"));
259 for (const [link, target] of [
260 [links[0], targets[0]],
261 [links[1], targets[1]],
262 ] as const) {
263 yield* Effect.gen(function* () {
264 // The harness creates these folders itself, and mkdir fails on a dangling link.
265 if (!(yield* fs.exists(target))) {
266 const linked = yield* fs.readLink(link).pipe(
267 Effect.as(true),
268 Effect.orElseSucceed(() => false),
269 );
270 if (linked) yield* fs.remove(link);
271 return;
272 }
273 const existing = yield* fs.readLink(link).pipe(
274 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
275 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
276 // An empty folder is the harness's placeholder from a launch without the link.
277 // rmdir refuses a non-empty folder, so content added meanwhile is never deleted.
278 Effect.catch((error) =>
279 Effect.tryPromise({
280 try: () => NodeFSP.rmdir(link),
281 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
282 }).pipe(
283 Effect.as(undefined),
284 Effect.mapError(() => error),
285 ),
286 ),
287 );
288 if (existing === target) return;
289 if (existing !== undefined) {
290 yield* fs.remove(link);
291 }
292 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
293 yield* Effect.tryPromise({
294 try: () => NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
295 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
296 });
297 }).pipe(
298 Effect.catch((error) =>
299 Effect.logWarning("Antigravity user skills are not linked into the profile.", {
300 link,
301 target,
302 error,
303 }),
304 ),
305 );
306 }
307});
308​
309export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
310 readonly profileDirectory: string;
311 readonly baseEnv?: NodeJS.ProcessEnv;
312 readonly runtimeExecutablePath?: string;
313 readonly platform?: NodeJS.Platform;
314 readonly auth?: AntigravityAuthConfig;
315 readonly userHome?: string;
316 readonly tempDirectory?: string;
317}) {
318 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
319 const fs = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
322 const platform = input.platform ?? (yield* HostProcess.Platform);
323 const userHome =
324 input.userHome ??
325 resolveAntigravityUserHome(
326 platform,
327 input.baseEnv ?? process.env,
328 yield* HostProcess.HomeDirectory,
329 );
330 const runtimeExecutablePath =
331 input.runtimeExecutablePath ??
332 (yield* resolveNodeExecutable("Antigravity sign-in", input.baseEnv).pipe(
333 Effect.mapError(
334 (cause) =>
335 new AcpErrors.AcpTransportError({
336 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
337 cause,
338 }),
339 ),
340 ));
341 const helperExecutable =
342 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
343 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
344 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
345 if (
346 browserCommand.includes(platform === "win32" ? ";" : ":") ||
347 helperExecutable.includes("\r") ||
348 helperExecutable.includes("\n") ||
349 helperExecutable.includes("\0") ||
350 helperExecutable.includes("%s")
351 ) {
352 return yield* authSupportError(
353 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
354 );
355 }
356​
357 const geminiHome = path.resolve(input.profileDirectory);
358 const acpDirectory = path.join(geminiHome, "antigravity-acp");
359 const tempDirectory = input.tempDirectory ?? path.join(acpDirectory, "tmp");
360 let caBundlePath: string | undefined;
361 if (platform === "linux") {
362 // Bundled Python may look for certificates at paths absent on this distribution.
363 // Relative paths would resolve differently when the agent runs in the project directory.
364 for (const candidate of [
365 (input.baseEnv ?? process.env).NIX_SSL_CERT_FILE,
366 "/etc/ssl/certs/ca-bundle.crt",
367 "/etc/ssl/certs/ca-certificates.crt",
368 "/etc/pki/tls/certs/ca-bundle.crt",
369 "/etc/ssl/cert.pem",
370 ]) {
371 if (
372 candidate &&
373 path.isAbsolute(candidate) &&
374 (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)))
375 ) {
376 caBundlePath = candidate;
377 break;
378 }
379 }
380 }
381 const profile: AntigravityProfile = {
382 platform,
383 geminiHome,
384 acpDirectory,
385 tokenPath: path.join(acpDirectory, "acp_token.json"),
386 tempDirectory,
387 browserCommand,
388 ...(caBundlePath === undefined ? {} : { caBundlePath }),
389 };
390 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
391 yield* Effect.gen(function* () {
392 const child = yield* spawner.spawn(
393 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
394 env: environment,
395 extendEnv: false,
396 shell: false,
397 }),
398 );
399 const [stdout, stderr, exitCode] = yield* Effect.all(
400 [
401 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
402 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
403 child.exitCode,
404 ],
405 { concurrency: "unbounded" },
406 );
407 if (
408 Number(exitCode) !== 0 ||
409 stdout.bytes !== 0 ||
410 stdout.truncated ||
411 stderr.truncated ||
412 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
413 ) {
414 return yield* authSupportError("Antigravity browser suppression could not be verified.");
415 }
416 }).pipe(
417 Effect.scoped,
418 Effect.timeoutOrElse({
419 duration: "30 seconds",
420 orElse: () =>
421 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
422 }),
423 Effect.mapError((error) =>
424 error._tag === "AcpTransportError"
425 ? error
426 : authSupportError("Antigravity browser suppression could not be verified."),
427 ),
428 );
429​
430 for (const directory of [geminiHome, acpDirectory, tempDirectory]) {
431 yield* fs
432 .makeDirectory(directory, { recursive: true, mode: 0o700 })
433 .pipe(
434 Effect.mapError(() =>
435 authSupportError("The Antigravity profile directory could not be created."),
436 ),
437 );
438 if (platform !== "win32") {
439 yield* fs
440 .chmod(directory, 0o700)
441 .pipe(
442 Effect.mapError(() =>
443 authSupportError("The Antigravity profile directory permissions could not be set."),
444 ),
445 );
446 }
447 }
448 yield* fs
449 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
450 .pipe(
451 Effect.mapError(() =>
452 authSupportError("The Antigravity profile settings could not be written."),
453 ),
454 );
455 yield* linkAntigravityUserSkills({ profileDirectory: geminiHome, userHome, platform });
456 return profile;
457});
458​
459export function buildAntigravityAcpSpawnInput(input: {
460 readonly installation: {
461 readonly executablePath: string;
462 readonly harnessPath: string | null;
463 };
464 readonly profile: AntigravityProfile;
465 readonly cwd: string;
466 readonly baseEnv?: NodeJS.ProcessEnv;
467 readonly auth?: AntigravityAuthConfig;
468 readonly runtimeTempDirectory?: string;
469}): AcpSessionRuntime.AcpSpawnInput {
470 return {
471 command: input.installation.executablePath,
472 // The agy CLI has no harness sibling and serves ACP through its `acp` subcommand.
473 // The harness can survive a failed local agent and return end_turn; its native
474 // logs are the failure signal, so the transport must receive them.
475 args:
476 input.installation.harnessPath === null
477 ? [
478 "acp",
479 "--gemini-dir",
480 input.profile.geminiHome,
481 "--app-data-dir",
482 // The CLI joins this beneath gemini-dir, including when the value is absolute.
483 "antigravity-acp",
484 ]
485 : [...(input.profile.platform === "linux" ? ["--uid="] : []), "--alsologtostderr"],
486 cwd: input.cwd,
487 env: {
488 ...antigravityEnvironment(
489 input.profile,
490 input.baseEnv ?? process.env,
491 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
492 input.runtimeTempDirectory,
493 ),
494 ...(input.installation.harnessPath === null
495 ? {}
496 : { ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath }),
497 },
498 extendEnv: false,
499 };
501​
502export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
503 function* (
504 authorizationUrl: string,
505 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
506 const invalidUrl = () =>
507 authSupportError("Antigravity returned an invalid Google sign-in URL.");
508 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
509 return yield* invalidUrl();
510 }
511 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
512 const state = url.searchParams.get("state");
513 const redirectUri = url.searchParams.get("redirect_uri");
514 if (
515 url.origin !== "https://accounts.google.com" ||
516 url.pathname !== "/o/oauth2/v2/auth" ||
517 url.username !== "" ||
518 url.password !== "" ||
519 url.hash !== "" ||
520 url.searchParams.getAll("state").length !== 1 ||
521 url.searchParams.getAll("redirect_uri").length !== 1 ||
522 url.searchParams.getAll("response_type").length !== 1 ||
523 url.searchParams.get("response_type") !== "code" ||
524 state === null ||
525 state.length === 0 ||
526 state.length > 512 ||
527 /\s/.test(state) ||
528 redirectUri === null ||
529 !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
530 ) {
531 return yield* invalidUrl();
532 }
533 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
534 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
535 return { authorizationUrl, redirectUri, state };
536 },
537);
538​
539export function makeAntigravityStdoutTransform(
540 input: {
541 readonly onAuthorizationUrl?: (
542 authorizationUrl: string,
543 ) => Effect.Effect<void, AcpErrors.AcpError>;
544 } = {},
545) {
546 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
547 line: Uint8Array,
548 ) {
549 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
550 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
551 const request = yield* parseAntigravityAuthorizationUrl(
552 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
553 );
554 if (!input.onAuthorizationUrl) {
555 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
556 }
557 yield* input.onAuthorizationUrl(request.authorizationUrl);
558 return [];
559 });
560​
561 return (
562 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
563 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
564 Stream.suspend(() => {
565 let pending: Uint8Array[] = [];
566 let pendingBytes = 0;
567 const finishLine = () => {
568 const line = Buffer.concat(pending, pendingBytes);
569 pending = [];
570 pendingBytes = 0;
571 return line;
572 };
573 return stdout.pipe(
574 Stream.mapEffect(
575 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
576 const lines: Uint8Array[] = [];
577 let offset = 0;
578 while (offset < chunk.byteLength) {
579 const newline = chunk.indexOf(10, offset);
580 const end = newline === -1 ? chunk.byteLength : newline + 1;
581 const part = chunk.subarray(offset, end);
582 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
583 return yield* authSupportError(
584 "Antigravity sent a protocol line that is too large.",
585 );
586 }
587 pending.push(part);
588 pendingBytes += part.byteLength;
589 if (newline !== -1) lines.push(finishLine());
590 offset = end;
591 }
592 return lines;
593 }),
594 ),
595 Stream.flatMap(Stream.fromIterable),
596 Stream.concat(
597 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
598 ),
599 Stream.mapEffect(handleLine),
600 Stream.flatMap(Stream.fromIterable),
601 );
602 });
604​
605// glog records from the managed harness after which its ACP process can no longer run a turn.
606const ANTIGRAVITY_HARNESS_FAILURE_LOG =
607 /^[IWEF]\d{4} \d{2}:\d{2}:\d{2}\.\d+ +\d+ (?:local_connection\.py:\d+\] harness stderr: Agent run failed:|server\.py:\d+\] (?:Failed to rebuild agent for session |Agent connection lost for session ))/;
608​
609export function makeAntigravityStderrHandler(
610 input: {
611 readonly onAuthorizationUrl?: (
612 authorizationUrl: string,
613 ) => Effect.Effect<void, AcpErrors.AcpError>;
614 } = {},
615) {
616 let pending = "";
617 // Untraced: with native logs on stderr this runs for every harness log line.
618 const handleLine = Effect.fnUntraced(function* (line: string) {
619 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
620 if (message.length > maxBrowserHelperLineLength) return;
621 if (ANTIGRAVITY_HARNESS_FAILURE_LOG.test(message)) {
622 return yield* new AcpErrors.AcpTransportError({
623 method: "session/prompt",
624 detail:
625 "Antigravity's local agent connection failed. Send a follow-up to resume with a fresh process.",
626 cause: undefined,
627 });
628 }
629 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
630 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
631 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
632 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
633 : undefined;
634 if (url === undefined) return;
635 yield* url.pipe(
636 Effect.flatMap(parseAntigravityAuthorizationUrl),
637 Effect.matchEffect({
638 onFailure: () => Effect.void,
639 onSuccess: (request) =>
640 input.onAuthorizationUrl
641 ? input.onAuthorizationUrl(request.authorizationUrl)
642 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
643 }),
644 );
645 });
646​
647 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
648 const lines = `${pending}${text}`.split("\n");
649 pending = lines.pop() ?? "";
650 if (pending.length > maxBrowserHelperLineLength) pending = "";
651 yield* Effect.forEach(lines, handleLine, { discard: true });
652 });