TypeScript
fix(antigravity): handle native sign-in URLs on stderr (#9514)
Theo Browneeb334ca57448
diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.tsindex cb8355881eb..57323e2675e 100644--- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts+++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts@@ -18,6 +18,7 @@ import { describe, expect } from "vite-plus/test";import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";import type * as EffectAcpProtocol from "effect-acp/protocol";+import * as EffectAcpErrors from "effect-acp/errors";const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");@@ -345,6 +346,28 @@ describe("AcpSessionRuntime", () => {}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);+ it.effect("fails a pending request when the stderr handler rejects the runtime", () =>+ Effect.gen(function* () {+ const failure = new EffectAcpErrors.AcpTransportError({+ detail: "Sign in before continuing.",+ cause: undefined,+ });+ const runtime = yield* AcpSessionRuntime.make({+ ...mockRuntimeOptions,+ spawn: { ...mockRuntimeOptions.spawn, env: { T3_ACP_FLOOD_STDERR: "1" } },+ onStderr: () => Effect.fail(failure),+ });+ expect(yield* runtime.start().pipe(Effect.flip)).toBe(failure);+ const events = yield* runtime.getEvents().pipe(+ Stream.filter((event) => event._tag === "ConnectionTerminated"),+ Stream.take(1),+ Stream.runCollect,+ );+ expect(events[0]?.error).toBe(failure);+ expect(yield* runtime.initialize().pipe(Effect.flip)).toBe(failure);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+it.effect("drains large stderr output and keeps auth-sized logging chunks", () =>Effect.gen(function* () {const lengths: Array<number> = [];diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.tsindex 10fa76aa74d..b5894192eed 100644--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts@@ -102,8 +102,8 @@ export interface AcpSessionRuntimeOptions {readonly transformSessionUpdate?: (notification: EffectAcpSchema.SessionNotification,) => EffectAcpSchema.SessionNotification;- /** Receives bounded stderr chunks. The provider must redact any secrets before logging. */- readonly onStderr?: (text: string) => Effect.Effect<void, never>;+ /** Receives bounded stderr chunks. Redact secrets before logging. A failure closes the runtime. */+ readonly onStderr?: (text: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;readonly protocolLogging?: {readonly logIncoming?: boolean;@@ -353,6 +353,7 @@ export const make = (Option.none(),);const stoppingRef = yield* Ref.make(false);+ const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>();const runtimeClosed = yield* Deferred.make<void>();const promptSerializationSemaphore = yield* Semaphore.make(1);const promptDispatchSemaphore = yield* Semaphore.make(1);@@ -400,7 +401,10 @@ export const make = (): Effect.Effect<A, EffectAcpErrors.AcpError> =>logRequest({ method, payload, status: "started" }).pipe(Effect.flatMap(() =>- effect.pipe(+ (options.onStderr+ ? Effect.raceFirst(effect, Deferred.await(stderrFailure))+ : effect+ ).pipe(Effect.tap((result) =>logRequest({method,@@ -448,7 +452,18 @@ export const make = (yield* child.stderr.pipe(Stream.decodeText(),Stream.runForEach((chunk) =>- options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void,+ (options.onStderr+ ? options.onStderr(chunk.slice(-maxStderrChunkLength))+ : Effect.void+ ).pipe(+ Effect.catch((error) =>+ Effect.gen(function* () {+ yield* Deferred.fail(stderrFailure, error);+ yield* recordTermination(error);+ yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);+ }),+ ),+ ),),Effect.ignore,Effect.forkIn(runtimeScope),diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.tsindex d89aa421073..cb37df00658 100644--- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts+++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts@@ -73,13 +73,9 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(transformStdout: makeAntigravityStdoutTransform(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},),- ...(input.onAuthorizationUrl- ? {- onStderr: makeAntigravityStderrHandler({- onAuthorizationUrl: input.onAuthorizationUrl,- }),- }- : {}),+ onStderr: makeAntigravityStderrHandler(+ input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},+ ),transformSessionUpdate: normalizeAntigravitySessionUpdate,}).pipe(Layer.provide(diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.tsindex 5bac0847986..03189018bd3 100644--- a/apps/server/src/provider/antigravityAuthSupport.test.ts+++ b/apps/server/src/provider/antigravityAuthSupport.test.ts@@ -391,6 +391,46 @@ describe("Antigravity stdout compatibility", () => {});describe("Antigravity stderr compatibility", () => {+ it.effect("forwards fragmented native sign-in URLs from runtime 1.1.1", () =>+ Effect.gen(function* () {+ const urls: string[] = [];+ const line = `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\r\n`;+ const handleStderr = makeAntigravityStderrHandler({+ onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),+ });+ yield* handleStderr(`native log\n${line.slice(0, 40)}`);+ yield* handleStderr(line.slice(40, 90));+ yield* handleStderr(`${line.slice(90)}another native log\n`);+ expect(urls).toEqual([authorizationUrl]);+ }),+ );++ it.effect("rejects interactive sign-in during normal work", () =>+ Effect.gen(function* () {+ const handleStderr = makeAntigravityStderrHandler();+ const error = yield* handleStderr(+ `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`,+ ).pipe(Effect.flip);+ expect(isAntigravitySignInRequiredError(error)).toBe(true);+ }),+ );++ it.effect("preserves failures from the sign-in flow owner", () =>+ Effect.gen(function* () {+ const failure = new AcpErrors.AcpTransportError({+ detail: "The sign-in flow stopped.",+ cause: undefined,+ });+ const handleStderr = makeAntigravityStderrHandler({+ onAuthorizationUrl: () => Effect.fail(failure),+ });+ const error = yield* handleStderr(+ `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`,+ ).pipe(Effect.flip);+ expect(error).toBe(failure);+ }),+ );+it.effect("forwards an accepted browser-helper URL larger than 8 KiB", () =>Effect.gen(function* () {const urls: string[] = [];@@ -438,6 +478,8 @@ describe("Antigravity stderr compatibility", () => {yield* handleStderr(`${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson("https://example.com")}\n`,);+ yield* handleStderr(`${ANTIGRAVITY_AUTH_STDOUT_PREFIX}https://example.com\n`);+ yield* handleStderr(` ${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`);expect(urls).toEqual([]);}),diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.tsindex 80116120e6a..dd55df5973b 100644--- a/apps/server/src/provider/antigravityAuthSupport.ts+++ b/apps/server/src/provider/antigravityAuthSupport.ts@@ -25,7 +25,9 @@ export const ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE =const maxAuthorizationUrlLength = 16_384;const maxBrowserHelperLineLength =- ANTIGRAVITY_AUTH_BROWSER_MARKER.length + maxAuthorizationUrlLength + 2;+ Math.max(ANTIGRAVITY_AUTH_BROWSER_MARKER.length, ANTIGRAVITY_AUTH_STDOUT_PREFIX.length) ++ maxAuthorizationUrlLength ++ 2;const maxStdoutLineBytes = 16 * 1024 * 1024;const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX);const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);@@ -458,25 +460,35 @@ export function makeAntigravityStdoutTransform(});}-/** Receives the URL emitted by T3's no-browser helper on stderr. */-export function makeAntigravityStderrHandler(input: {- readonly onAuthorizationUrl: (- authorizationUrl: string,- ) => Effect.Effect<void, AcpErrors.AcpError>;-}) {+/** Receives native 1.1.1 sign-in URLs and T3 browser-helper URLs without logging stderr. */+export function makeAntigravityStderrHandler(+ input: {+ readonly onAuthorizationUrl?: (+ authorizationUrl: string,+ ) => Effect.Effect<void, AcpErrors.AcpError>;+ } = {},+) {let pending = "";const handleLine = (line: string) => {const message = line.endsWith("\r") ? line.slice(0, -1) : line;- if (- message.length > maxBrowserHelperLineLength ||- !message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)- ) {+ if (message.length > maxBrowserHelperLineLength) {return Effect.void;}- return decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length)).pipe(+ const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)+ ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))+ : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)+ ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))+ : undefined;+ if (url === undefined) return Effect.void;+ return url.pipe(Effect.flatMap(parseAntigravityAuthorizationUrl),- Effect.flatMap((request) => input.onAuthorizationUrl(request.authorizationUrl)),- Effect.ignore,+ Effect.matchEffect({+ onFailure: () => Effect.void,+ onSuccess: (request) =>+ input.onAuthorizationUrl+ ? input.onAuthorizationUrl(request.authorizationUrl)+ : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),+ }),);};diff --git a/docs/internals/providers.md b/docs/internals/providers.mdindex d29dd107920..4e1a7b77407 100644--- a/docs/internals/providers.md+++ b/docs/internals/providers.md@@ -104,11 +104,13 @@ environment extension, sets `PYTHONUNBUFFERED=1`, and controls `BROWSER`. A testElectron-as-Node helper prevents the official agent from opening a browser on the environment.The same launch factory serves setup, health checks, chat, and text generation.-The official agent prints one non-JSON OAuth line on stdout. Only the exact known prefix is-filtered before ACP decoding. Fragmented lines are joined and bounded. Other malformed-protocol output remains fatal. Authorization URLs are validated before use. Native stderr is-drained without logging because it can contain OAuth data. Normal work rejects an interactive-login request with a sign-in-required error instead of waiting for consent.+The official agent prints a non-JSON OAuth line on stderr in version 1.1.1. Earlier versions+print it on stdout. T3 accepts the exact native prefix on either stream and its browser-helper+marker on stderr. Fragmented lines are joined and bounded. Other malformed protocol output+remains fatal. Authorization URLs are validated before use. Other stderr is discarded because+it can contain OAuth data. Normal work rejects an interactive login request with a+sign-in-required error instead of waiting for consent. A rejected stderr callback fails pending+ACP requests and closes the owned process.[`AntigravityAuth`][antigravity-auth] owns each sign-in process and deadline in the instancescope. Only the initiating T3 auth session receives its URL and flow ID or can complete or