@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 748 lines 27.7 KB
Raw
1 // @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's symlink has no type argument, and Windows needs a junction to link without elevation.
2 import * as NodeFSP from "node:fs/promises";
3
4 import type { AntigravityAuthMethod, ProviderInstanceId } from "@t3tools/contracts";
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
7 import * as Digest from "effect/crypto/Digest";
8 import * as Effect from "effect/Effect";
9 import * as Hex from "effect/encoding/Hex";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Option from "effect/Option";
12 import * as Path from "effect/Path";
13 import type * as PlatformError from "effect/PlatformError";
14 import * as Schema from "effect/Schema";
15 import * as Stream from "effect/Stream";
16 import * as ChildProcess from "effect/process/ChildProcess";
17 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18 import * as AcpErrors from "effect-acp/errors";
19
20 import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
21 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
22 import {
23 antigravityUserSkillDirectories,
24 resolveAntigravityUserHome,
25 } from "./Drivers/AntigravitySkills.ts";
26
27 export const ANTIGRAVITY_AUTH_STDOUT_PREFIX =
28 "Open the following link to authenticate the ACP server: ";
29 export const ANTIGRAVITY_AUTH_BROWSER_MARKER = "__T3_ANTIGRAVITY_AUTH_URL__";
30 export const ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE =
31 "Sign in to Antigravity in Settings before you continue.";
32
33 const maxAuthorizationUrlLength = 16_384;
34 const maxBrowserHelperLineLength =
35 Math.max(ANTIGRAVITY_AUTH_BROWSER_MARKER.length, ANTIGRAVITY_AUTH_STDOUT_PREFIX.length) +
36 maxAuthorizationUrlLength +
37 2;
38 const maxStdoutLineBytes = 16 * 1024 * 1024;
39 const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX);
40 const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);
41 const decodeBrowserHelperUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String));
42 const 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 });
51 const encodeProfileSettings = Schema.encodeSync(Schema.fromJsonString(ProfileSettingsFile));
52 const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
53 const 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.
56 const 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))`;
60 const browserPreflightUrl = "https://example.invalid/t3-antigravity-browser-preflight";
61
62 const 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
84 export 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;
92 }
93
94 export interface AntigravityAuthConfig {
95 readonly authMethod: AntigravityAuthMethod;
96 readonly apiKey: string;
97 readonly gcpProject: string;
98 readonly gcpLocation: string;
99 }
100
101 const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
102 authMethod: "oauth-personal",
103 apiKey: "",
104 gcpProject: "",
105 gcpLocation: "",
106 };
107
108 export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
109 return authMethod === "oauth-personal" || authMethod === "oauth-business";
110 }
111
112 export 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 }
123 }
124
125 export 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 }
140 }
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 */
146 function 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`;
155 }
156
157 export interface AntigravityAuthorizationUrl {
158 readonly authorizationUrl: string;
159 readonly redirectUri: string;
160 readonly state: string;
161 }
162
163 function authSupportError(detail: string) {
164 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
165 }
166
167 // The 1.5 CLI answers `authenticate` with this internal error when it has no sign-in and no display.
168 const NATIVE_CLI_NO_BROWSER_PREFIX = "No browser is available here";
169
170 export 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 );
177 }
178
179 export 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;
183 }
184
185 /** Hashes the instance ID so case-only differences stay separate on case-insensitive filesystems. */
186 export 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
198 function quoteBrowserArgument(value: string): string {
199 return `'${value.replaceAll("'", `'"'"'`)}'`;
200 }
201
202 function 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_CLI_DISABLE_AUTO_UPDATE: "1",
238 BROWSER: profile.browserCommand,
239 PYTHONUNBUFFERED: "1",
240 ELECTRON_RUN_AS_NODE: "1",
241 ...(profile.platform === "win32"
242 ? { TEMP: tempDirectory, TMP: tempDirectory }
243 : { TMPDIR: tempDirectory }),
244 };
245 }
246
247 class AntigravitySkillLinkError extends Schema.TaggedError<AntigravitySkillLinkError>()(
248 "AntigravitySkillLinkError",
249 { link: Schema.String, cause: Schema.Defect() },
250 ) {
251 override get message(): string {
252 return `Could not link Antigravity user configuration at ${this.link}.`;
253 }
254 }
255
256 const antigravityUserConfigFiles = [
257 ["AGENTS.md"],
258 ["GEMINI.md"],
259 ["config", "skills.json"],
260 ] as const;
261
262 /** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills and rules from the real ~/.gemini. */
263 const linkAntigravityUserConfig = Effect.fn("linkAntigravityUserConfig")(function* (input: {
264 readonly profileDirectory: string;
265 readonly userHome: string;
266 readonly platform: NodeJS.Platform;
267 }): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
268 const fs = yield* FileSystem.FileSystem;
269 const path = yield* Path.Path;
270 const userGemini = path.join(input.userHome, ".gemini");
271 const links = antigravityUserSkillDirectories(path, input.profileDirectory);
272 const targets = antigravityUserSkillDirectories(path, userGemini);
273 const directoryType = input.platform === "win32" ? "junction" : "dir";
274 for (const [link, target, type] of [
275 [links[0], targets[0], directoryType],
276 [links[1], targets[1], directoryType],
277 // File symlinks need elevation or Developer Mode on Windows, so config files are copied there.
278 ...(input.platform === "win32"
279 ? []
280 : antigravityUserConfigFiles.map(
281 (segments) =>
282 [
283 path.join(input.profileDirectory, ...segments),
284 path.join(userGemini, ...segments),
285 "file",
286 ] as const,
287 )),
288 ] as const) {
289 yield* Effect.gen(function* () {
290 // The harness creates these folders itself, and mkdir fails on a dangling link.
291 if (!(yield* fs.exists(target))) {
292 const linked = yield* fs.readLink(link).pipe(
293 Effect.as(true),
294 Effect.orElseSucceed(() => false),
295 );
296 if (linked) yield* fs.remove(link);
297 return;
298 }
299 const existing = yield* fs.readLink(link).pipe(
300 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
301 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
302 // An empty folder is the harness's placeholder from a launch without the link.
303 // rmdir refuses a non-empty folder, so content added meanwhile is never deleted.
304 Effect.catch((error) =>
305 Effect.tryPromise({
306 try: () => NodeFSP.rmdir(link),
307 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
308 }).pipe(
309 Effect.as(undefined),
310 Effect.mapError(() => error),
311 ),
312 ),
313 );
314 if (existing === target) return;
315 if (existing !== undefined) {
316 yield* fs.remove(link);
317 }
318 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
319 yield* Effect.tryPromise({
320 try: () => NodeFSP.symlink(target, link, type),
321 catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
322 });
323 }).pipe(
324 Effect.catch((error) =>
325 Effect.logWarning("Antigravity user configuration is not linked into the profile.", {
326 link,
327 target,
328 error,
329 }),
330 ),
331 );
332 }
333 });
334
335 const RuleCopiesJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
336 const decodeRuleCopies = Schema.decodeUnknownOption(RuleCopiesJson);
337 const encodeRuleCopies = Schema.encodeSync(RuleCopiesJson);
338
339 /** Copies refresh each launch; the recorded copy keeps a file the profile owns or edited untouched. */
340 const copyAntigravityUserConfigFiles = Effect.fn("copyAntigravityUserConfigFiles")(
341 function* (input: {
342 readonly profileDirectory: string;
343 readonly userHome: string;
344 }): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
345 const fs = yield* FileSystem.FileSystem;
346 const path = yield* Path.Path;
347 const manifestPath = path.join(input.profileDirectory, ".t3-rule-copies.json");
348 const readOptional = (file: string) =>
349 fs.readFileString(file).pipe(Effect.orElseSucceed((): string | undefined => undefined));
350 const manifestText = yield* readOptional(manifestPath);
351 const copies: Record<string, string> = {
352 ...Option.getOrElse(decodeRuleCopies(manifestText), () => ({})),
353 };
354 for (const segments of antigravityUserConfigFiles) {
355 const key = segments.join("/");
356 const link = path.join(input.profileDirectory, ...segments);
357 const target = path.join(input.userHome, ".gemini", ...segments);
358 yield* Effect.gen(function* () {
359 const current = yield* readOptional(link);
360 if (current !== undefined && current !== copies[key]) {
361 delete copies[key];
362 return;
363 }
364 const source = yield* readOptional(target);
365 if (source === undefined) {
366 if (current !== undefined) yield* fs.remove(link);
367 delete copies[key];
368 return;
369 }
370 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
371 yield* fs.writeFileString(link, source);
372 copies[key] = source;
373 }).pipe(
374 Effect.catch((error) =>
375 Effect.logWarning("Antigravity user configuration is not copied into the profile.", {
376 link,
377 target,
378 error,
379 }),
380 ),
381 );
382 }
383 yield* fs
384 .writeFileString(manifestPath, encodeRuleCopies(copies))
385 .pipe(
386 Effect.catch((error) =>
387 Effect.logWarning("Antigravity rule copy record could not be written.", { error }),
388 ),
389 );
390 },
391 );
392
393 export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
394 readonly profileDirectory: string;
395 readonly baseEnv?: NodeJS.ProcessEnv;
396 readonly runtimeExecutablePath?: string;
397 readonly platform?: NodeJS.Platform;
398 readonly auth?: AntigravityAuthConfig;
399 readonly userHome?: string;
400 readonly tempDirectory?: string;
401 }) {
402 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
406 const platform = input.platform ?? (yield* HostProcess.Platform);
407 const userHome =
408 input.userHome ??
409 resolveAntigravityUserHome(
410 platform,
411 input.baseEnv ?? process.env,
412 yield* HostProcess.HomeDirectory,
413 );
414 const runtimeExecutablePath =
415 input.runtimeExecutablePath ??
416 (yield* resolveNodeExecutable("Antigravity sign-in", input.baseEnv).pipe(
417 Effect.mapError(
418 (cause) =>
419 new AcpErrors.AcpTransportError({
420 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
421 cause,
422 }),
423 ),
424 ));
425 const helperExecutable =
426 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
427 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
428 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
429 if (
430 browserCommand.includes(platform === "win32" ? ";" : ":") ||
431 helperExecutable.includes("\r") ||
432 helperExecutable.includes("\n") ||
433 helperExecutable.includes("\0") ||
434 helperExecutable.includes("%s")
435 ) {
436 return yield* authSupportError(
437 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
438 );
439 }
440
441 const geminiHome = path.resolve(input.profileDirectory);
442 const acpDirectory = path.join(geminiHome, "antigravity-acp");
443 const tempDirectory = input.tempDirectory ?? path.join(acpDirectory, "tmp");
444 let caBundlePath: string | undefined;
445 if (platform === "linux") {
446 // Bundled Python may look for certificates at paths absent on this distribution.
447 // Relative paths would resolve differently when the agent runs in the project directory.
448 for (const candidate of [
449 (input.baseEnv ?? process.env).NIX_SSL_CERT_FILE,
450 "/etc/ssl/certs/ca-bundle.crt",
451 "/etc/ssl/certs/ca-certificates.crt",
452 "/etc/pki/tls/certs/ca-bundle.crt",
453 "/etc/ssl/cert.pem",
454 ]) {
455 if (
456 candidate &&
457 path.isAbsolute(candidate) &&
458 (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)))
459 ) {
460 caBundlePath = candidate;
461 break;
462 }
463 }
464 }
465 const profile: AntigravityProfile = {
466 platform,
467 geminiHome,
468 acpDirectory,
469 tokenPath: path.join(acpDirectory, "acp_token.json"),
470 tempDirectory,
471 browserCommand,
472 ...(caBundlePath === undefined ? {} : { caBundlePath }),
473 };
474 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
475 yield* Effect.gen(function* () {
476 const child = yield* spawner.spawn(
477 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
478 env: environment,
479 extendEnv: false,
480 shell: false,
481 }),
482 );
483 const [stdout, stderr, exitCode] = yield* Effect.all(
484 [
485 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
486 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
487 child.exitCode,
488 ],
489 { concurrency: "unbounded" },
490 );
491 if (
492 Number(exitCode) !== 0 ||
493 stdout.bytes !== 0 ||
494 stdout.truncated ||
495 stderr.truncated ||
496 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
497 ) {
498 return yield* authSupportError("Antigravity browser suppression could not be verified.");
499 }
500 }).pipe(
501 Effect.scoped,
502 Effect.timeoutOrElse({
503 duration: "30 seconds",
504 orElse: () =>
505 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
506 }),
507 Effect.mapError((error) =>
508 error._tag === "AcpTransportError"
509 ? error
510 : authSupportError("Antigravity browser suppression could not be verified."),
511 ),
512 );
513
514 for (const directory of [geminiHome, acpDirectory, tempDirectory]) {
515 yield* fs
516 .makeDirectory(directory, { recursive: true, mode: 0o700 })
517 .pipe(
518 Effect.mapError(() =>
519 authSupportError("The Antigravity profile directory could not be created."),
520 ),
521 );
522 if (platform !== "win32") {
523 yield* fs
524 .chmod(directory, 0o700)
525 .pipe(
526 Effect.mapError(() =>
527 authSupportError("The Antigravity profile directory permissions could not be set."),
528 ),
529 );
530 }
531 }
532 yield* fs
533 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
534 .pipe(
535 Effect.mapError(() =>
536 authSupportError("The Antigravity profile settings could not be written."),
537 ),
538 );
539 yield* linkAntigravityUserConfig({ profileDirectory: geminiHome, userHome, platform });
540 if (platform === "win32") {
541 yield* copyAntigravityUserConfigFiles({ profileDirectory: geminiHome, userHome });
542 }
543 return profile;
544 });
545
546 export function buildAntigravityAcpSpawnInput(input: {
547 readonly installation: { readonly executablePath: string };
548 readonly profile: AntigravityProfile;
549 readonly cwd: string;
550 readonly baseEnv?: NodeJS.ProcessEnv;
551 readonly auth?: AntigravityAuthConfig;
552 readonly runtimeTempDirectory?: string;
553 }): AcpSessionRuntime.AcpSpawnInput {
554 return {
555 command: input.installation.executablePath,
556 args: [
557 "acp",
558 "--gemini-dir",
559 input.profile.geminiHome,
560 "--app-data-dir",
561 // The CLI joins this beneath gemini-dir, including when the value is absolute.
562 "antigravity-acp",
563 ],
564 cwd: input.cwd,
565 env: antigravityEnvironment(
566 input.profile,
567 input.baseEnv ?? process.env,
568 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
569 input.runtimeTempDirectory,
570 ),
571 extendEnv: false,
572 };
573 }
574
575 /** Where `agy acp --login` sends Google; the page shows a code the user pastes back. */
576 const ANTIGRAVITY_CODE_REDIRECT_URI = "https://antigravity.google/oauth-callback";
577
578 export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
579 function* (
580 authorizationUrl: string,
581 kind: "loopback" | "code" = "loopback",
582 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
583 const invalidUrl = () =>
584 authSupportError("Antigravity returned an invalid Google sign-in URL.");
585 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
586 return yield* invalidUrl();
587 }
588 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
589 const state = url.searchParams.get("state");
590 const redirectUri = url.searchParams.get("redirect_uri");
591 if (
592 url.origin !== "https://accounts.google.com" ||
593 url.pathname !== (kind === "loopback" ? "/o/oauth2/v2/auth" : "/o/oauth2/auth") ||
594 url.username !== "" ||
595 url.password !== "" ||
596 url.hash !== "" ||
597 url.searchParams.getAll("state").length !== 1 ||
598 url.searchParams.getAll("redirect_uri").length !== 1 ||
599 url.searchParams.getAll("response_type").length !== 1 ||
600 url.searchParams.get("response_type") !== "code" ||
601 state === null ||
602 state.length === 0 ||
603 state.length > 512 ||
604 /\s/.test(state) ||
605 redirectUri === null ||
606 (kind === "loopback"
607 ? !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
608 : redirectUri !== ANTIGRAVITY_CODE_REDIRECT_URI)
609 ) {
610 return yield* invalidUrl();
611 }
612 if (kind === "code") return { authorizationUrl, redirectUri, state };
613 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
614 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
615 return { authorizationUrl, redirectUri, state };
616 },
617 );
618
619 /**
620 * What `agy acp --login` reads after its link: the code the Antigravity page shows, or that page's
621 * URL, which must answer this sign-in. Undefined for anything else, including any line break.
622 */
623 export function antigravityLoginResponse(
624 pending: AntigravityAuthorizationUrl,
625 response: string,
626 ): string | undefined {
627 const value = response.trim();
628 if (/^[\w./~-]{1,2048}$/.test(value)) return value;
629 if (value.length > maxAuthorizationUrlLength || /\s/.test(value)) return undefined;
630 const url = URL.parse(value);
631 if (
632 url === null ||
633 `${url.origin}${url.pathname}` !== pending.redirectUri ||
634 url.username !== "" ||
635 url.password !== "" ||
636 url.searchParams.getAll("state").length !== 1 ||
637 url.searchParams.get("state") !== pending.state ||
638 url.searchParams.getAll("code").length !== 1 ||
639 !url.searchParams.get("code")
640 ) {
641 return undefined;
642 }
643 return value;
644 }
645
646 export function makeAntigravityStdoutTransform(
647 input: {
648 readonly onAuthorizationUrl?: (
649 authorizationUrl: string,
650 ) => Effect.Effect<void, AcpErrors.AcpError>;
651 } = {},
652 ) {
653 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
654 line: Uint8Array,
655 ) {
656 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
657 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
658 const request = yield* parseAntigravityAuthorizationUrl(
659 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
660 );
661 if (!input.onAuthorizationUrl) {
662 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
663 }
664 yield* input.onAuthorizationUrl(request.authorizationUrl);
665 return [];
666 });
667
668 return (
669 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
670 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
671 Stream.suspend(() => {
672 let pending: Uint8Array[] = [];
673 let pendingBytes = 0;
674 const finishLine = () => {
675 const line = Buffer.concat(pending, pendingBytes);
676 pending = [];
677 pendingBytes = 0;
678 return line;
679 };
680 return stdout.pipe(
681 Stream.mapEffect(
682 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
683 const lines: Uint8Array[] = [];
684 let offset = 0;
685 while (offset < chunk.byteLength) {
686 const newline = chunk.indexOf(10, offset);
687 const end = newline === -1 ? chunk.byteLength : newline + 1;
688 const part = chunk.subarray(offset, end);
689 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
690 return yield* authSupportError(
691 "Antigravity sent a protocol line that is too large.",
692 );
693 }
694 pending.push(part);
695 pendingBytes += part.byteLength;
696 if (newline !== -1) lines.push(finishLine());
697 offset = end;
698 }
699 return lines;
700 }),
701 ),
702 Stream.flatMap(Stream.fromIterable),
703 Stream.concat(
704 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
705 ),
706 Stream.mapEffect(handleLine),
707 Stream.flatMap(Stream.fromIterable),
708 );
709 });
710 }
711
712 export function makeAntigravityStderrHandler(
713 input: {
714 readonly onAuthorizationUrl?: (
715 authorizationUrl: string,
716 ) => Effect.Effect<void, AcpErrors.AcpError>;
717 } = {},
718 ) {
719 let pending = "";
720 // Untraced: this runs for every stderr line.
721 const handleLine = Effect.fnUntraced(function* (line: string) {
722 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
723 if (message.length > maxBrowserHelperLineLength) return;
724 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
725 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
726 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
727 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
728 : undefined;
729 if (url === undefined) return;
730 yield* url.pipe(
731 Effect.flatMap(parseAntigravityAuthorizationUrl),
732 Effect.matchEffect({
733 onFailure: () => Effect.void,
734 onSuccess: (request) =>
735 input.onAuthorizationUrl
736 ? input.onAuthorizationUrl(request.authorizationUrl)
737 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
738 }),
739 );
740 });
741
742 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
743 const lines = `${pending}${text}`.split("\n");
744 pending = lines.pop() ?? "";
745 if (pending.length > maxBrowserHelperLineLength) pending = "";
746 yield* Effect.forEach(lines, handleLine, { discard: true });
747 });
748 }