Open History to see the last commit
1import {
2 ProviderSetupError,
3 type ProviderAuthState,
4 type ProviderInstanceId,
5} from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import * as Clock from "effect/Clock";
8import * as SecureRandom from "effect/crypto/SecureRandom";
9import * as DateTime from "effect/DateTime";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Fiber from "effect/Fiber";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Semaphore from "effect/Semaphore";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import * as AcpErrors from "effect-acp/errors";
21
22import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
23import {
24 parseAntigravityAuthorizationUrl,
25 type AntigravityAuthorizationUrl,
26} from "./antigravityAuthSupport.ts";
27import {
28 forwardAntigravityCallback,
29 validateAntigravityCallbackUrl,
30} from "./antigravityCallback.ts";
31import type { ProviderAuthController } from "./ProviderAuthService.ts";
32
33const AUTH_TIMEOUT_MS = 300_000;
34// A healthy agent shows the Google link or finishes within seconds. Its bundled Python has no
35// IPv4 fallback race, so a host with broken IPv6 waits about two minutes per Google request.
36const NO_RESPONSE_HINT_MS = 30_000;
37const NO_RESPONSE_MESSAGE =
38 "Antigravity has not reached Google after 30 seconds. Check this machine's network connection. Broken IPv6 is a common cause.";
39const UNREACHABLE_MESSAGE =
40 "Antigravity could not reach Google. Check this machine's network connection, then start sign-in again.";
41const FORWARDING_FAILED_MESSAGE = "Could not deliver the sign-in response. Start sign-in again.";
42const isSetupError = Schema.is(ProviderSetupError);
43const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
44
45interface AuthSnapshot {
46 readonly ownerSessionId: string | null;
47 readonly state: ProviderAuthState;
48}
49
50interface AuthFlow {
51 readonly id: string;
52 readonly ownerSessionId: string;
53 readonly expiresAtMillis: number;
54 state: ProviderAuthState;
55 pending: AntigravityAuthorizationUrl | undefined;
56 callbackSent: boolean;
57 fiber: Fiber.Fiber<void> | undefined;
58 forwarding: Fiber.Fiber<void, ProviderSetupError> | undefined;
59}
60
61interface OwnedProcess {
62 readonly stop: Effect.Effect<void>;
63 startup: Fiber.Fiber<unknown, unknown> | undefined;
64}
65
66export interface AntigravityAuth {
67 readonly controller: ProviderAuthController;
68 readonly withProcess: <A, E, R>(
69 stop: Effect.Effect<void>,
70 task: Effect.Effect<A, E, R>,
71 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
72}
73
74export type AntigravityAuthRuntime = Pick<
75 AcpSessionRuntime.AcpSessionRuntime["Service"],
76 "initialize" | "start" | "request"
77>;
78
79export interface AntigravityAuthOptions<
80 Runtime extends AntigravityAuthRuntime = AcpSessionRuntime.AcpSessionRuntime["Service"],
81> {
82 readonly instanceId: ProviderInstanceId;
83 readonly makeRuntime: (input: {
84 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
85 }) => Effect.Effect<Runtime, AcpErrors.AcpError | ProviderSetupError, Scope.Scope>;
86 readonly onAuthenticated: (
87 result: AcpSessionRuntime.AcpSessionRuntimeStartResult,
88 runtime: Runtime,
89 ) => Effect.Effect<void>;
90 readonly onSignedOut: Effect.Effect<void>;
91 readonly forwardCallback?: (callback: URL) => Effect.Effect<void, ProviderSetupError>;
92 readonly usesBrowser?: boolean;
93}
94
95function visibleSnapshot(snapshot: AuthSnapshot, ownerSessionId: string): ProviderAuthState {
96 if (snapshot.ownerSessionId === null || snapshot.ownerSessionId === ownerSessionId) {
97 return snapshot.state;
98 }
99 const busy = ["starting", "waiting", "verifying"].includes(snapshot.state.phase);
100 return {
101 ...snapshot.state,
102 flowId: null,
103 authorizationUrl: null,
104 interaction: null,
105 expiresAt: null,
106 ...(busy ? { message: "Sign-in is in progress in another client." } : {}),
107 };
108}
109
110function safeAuthFailure(cause: Cause.Cause<unknown>, usesBrowser: boolean): string {
111 const error = Cause.findErrorOption(cause);
112 if (Option.isSome(error)) {
113 if (isSetupError(error.value)) {
114 return error.value.detail;
115 }
116 if (isAcpRequestError(error.value)) {
117 if (error.value.errorMessage.includes("SUBSCRIPTION_REQUIRED")) {
118 return "Google requires an eligible Antigravity subscription for this account.";
119 }
120 if (/access_denied|denied access|cancelled/i.test(error.value.errorMessage)) {
121 return "Google sign-in was not approved. Start sign-in again.";
122 }
123 if (error.value.method === "session/new" && error.value.code === -32603) {
124 return "Antigravity authenticated, but could not initialize a session or load models.";
125 }
126 if (!usesBrowser && error.value.code === -32602) {
127 return "Antigravity rejected the configured credentials. Check the provider settings.";
128 }
129 }
130 }
131 return usesBrowser
132 ? "Google sign-in failed. Start sign-in again."
133 : "Antigravity could not authenticate with the configured credentials.";
134}
135
136export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
137 Runtime extends AntigravityAuthRuntime,
138>(
139 options: AntigravityAuthOptions<Runtime>,
140): Effect.fn.Return<AntigravityAuth, never, SecureRandom.SecureRandom | Scope.Scope> {
141 const random = yield* SecureRandom.SecureRandom;
142 const instanceScope = yield* Scope.Scope;
143 const usesBrowser = options.usesBrowser ?? true;
144 const lock = yield* Semaphore.make(1);
145 const closed = yield* Deferred.make<void>();
146 const emptyState: ProviderAuthState = {
147 instanceId: options.instanceId,
148 phase: "idle",
149 flowId: null,
150 authorizationUrl: null,
151 expiresAt: null,
152 message: null,
153 };
154 const snapshot = yield* SubscriptionRef.make<AuthSnapshot>({
155 ownerSessionId: null,
156 state: emptyState,
157 });
158 const processes = new Set<OwnedProcess>();
159 let activeFlow: AuthFlow | undefined;
160 let operation: "idle" | "auth" | "logout" | "cancel" | "closed" = "idle";
161
162 const setupError = (name: string, detail: string) =>
163 new ProviderSetupError({ instanceId: options.instanceId, operation: name, detail });
164 const currentState = (ownerSessionId: string) =>
165 SubscriptionRef.get(snapshot).pipe(
166 Effect.map((value) => visibleSnapshot(value, ownerSessionId)),
167 );
168 const publishFlow = (flow: AuthFlow, state: ProviderAuthState) => {
169 flow.state = state;
170 return SubscriptionRef.set(snapshot, { ownerSessionId: flow.ownerSessionId, state });
171 };
172 const stopOwnedProcesses = Effect.suspend(() =>
173 Effect.forEach(
174 Array.from(processes),
175 (owned) =>
176 Effect.gen(function* () {
177 if (owned.startup) {
178 yield* Fiber.interrupt(owned.startup);
179 }
180 yield* owned.stop;
181 }),
182 { discard: true, concurrency: "unbounded" },
183 ),
184 );
185
186 const withProcess: AntigravityAuth["withProcess"] = (stop, task) =>
187 Effect.uninterruptibleMask((restore) =>
188 Effect.gen(function* () {
189 const scope = yield* Scope.Scope;
190 const owned: OwnedProcess = { stop, startup: undefined };
191 const fiber = yield* lock.withPermits(1)(
192 Effect.gen(function* () {
193 if (operation !== "idle") {
194 return yield* setupError(
195 "startProcess",
196 "Antigravity sign-in or sign-out is in progress. Try again after it finishes.",
197 );
198 }
199 processes.add(owned);
200 yield* Scope.addFinalizer(
201 scope,
202 Effect.sync(() => {
203 processes.delete(owned);
204 }),
205 );
206 const child = yield* restore(task).pipe(Effect.forkIn(scope));
207 owned.startup = child;
208 return child;
209 }),
210 );
211 // Propagate interruption after the exit wait so concurrent stop waiters stay attached.
212 return yield* restore(Fiber.await(fiber)).pipe(
213 Effect.flatMap((result) => result),
214 Effect.ensuring(Fiber.interrupt(fiber)),
215 Effect.ensuring(
216 Effect.sync(() => {
217 owned.startup = undefined;
218 }),
219 ),
220 );
221 }),
222 );
223
224 const finishFlow = (flow: AuthFlow, result: Exit.Exit<void, unknown>) =>
225 lock.withPermits(1)(
226 Effect.gen(function* () {
227 if (activeFlow !== flow) return;
228 activeFlow = undefined;
229 operation = "idle";
230 flow.pending = undefined;
231 yield* publishFlow(flow, {
232 ...flow.state,
233 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
234 authorizationUrl: null,
235 expiresAt: null,
236 message: Exit.isSuccess(result)
237 ? usesBrowser
238 ? "Signed in with Google."
239 : "Connected to Antigravity."
240 : safeAuthFailure(result.cause, usesBrowser),
241 });
242 }),
243 );
244
245 const receiveAuthorizationUrl = (flow: AuthFlow, url: string) =>
246 parseAntigravityAuthorizationUrl(url).pipe(
247 Effect.flatMap((authorization) =>
248 lock.withPermits(1)(
249 Effect.gen(function* () {
250 if (activeFlow !== flow || operation !== "auth") return;
251 if (flow.pending) {
252 if (flow.pending.authorizationUrl === authorization.authorizationUrl) return;
253 return yield* new AcpErrors.AcpTransportError({
254 detail: "Antigravity started more than one Google sign-in request.",
255 cause: undefined,
256 });
257 }
258 flow.pending = authorization;
259 yield* publishFlow(flow, {
260 ...flow.state,
261 phase: "waiting",
262 authorizationUrl: authorization.authorizationUrl,
263 message:
264 "Open the Google sign-in link. If you are remote, paste the redirect URL here.",
265 });
266 }),
267 ),
268 ),
269 );
270
271 const runSignIn = Effect.fn("AntigravityAuth.runSignIn")(
272 function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
273 yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses));
274 yield* Effect.sleep(NO_RESPONSE_HINT_MS).pipe(
275 Effect.andThen(
276 lock.withPermits(1)(
277 Effect.gen(function* () {
278 if (activeFlow !== flow || flow.state.phase !== "starting") return;
279 yield* publishFlow(flow, { ...flow.state, message: NO_RESPONSE_MESSAGE });
280 }),
281 ),
282 ),
283 Effect.forkScoped,
284 );
285 const runtime = yield* options.makeRuntime({
286 onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url),
287 });
288 const started = yield* runtime.start();
289 yield* lock.withPermits(1)(
290 Effect.gen(function* () {
291 if (activeFlow !== flow) return;
292 flow.pending = undefined;
293 yield* publishFlow(flow, {
294 ...flow.state,
295 phase: "verifying",
296 authorizationUrl: null,
297 message: "Checking Antigravity access and models.",
298 });
299 }),
300 );
301 yield* options.onAuthenticated(started, runtime);
302 },
303 (effect, flow, _stopSessions) =>
304 effect.pipe(
305 Effect.scoped,
306 Effect.timeoutOrElse({
307 duration: AUTH_TIMEOUT_MS,
308 orElse: () =>
309 Effect.fail(
310 setupError(
311 "start",
312 flow.state.phase === "starting"
313 ? UNREACHABLE_MESSAGE
314 : "Google sign-in expired. Start sign-in again.",
315 ),
316 ),
317 }),
318 Effect.exit,
319 Effect.flatMap((result) => finishFlow(flow, result)),
320 ),
321 );
322
323 const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>
324 Effect.uninterruptible(
325 Effect.gen(function* () {
326 const detached = yield* lock.withPermits(1)(
327 Effect.gen(function* () {
328 if (activeFlow !== flow) return false;
329 activeFlow = undefined;
330 operation = "cancel";
331 flow.pending = undefined;
332 yield* publishFlow(flow, {
333 ...flow.state,
334 phase,
335 authorizationUrl: null,
336 expiresAt: null,
337 message,
338 });
339 return true;
340 }),
341 );
342 if (!detached) return;
343 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
344 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
345 yield* lock.withPermits(1)(
346 Effect.sync(() => {
347 if (operation === "cancel") operation = "idle";
348 }),
349 );
350 }),
351 );
352
353 const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* (
354 ownerSessionId: string,
355 flowId: string,
356 name: string,
357 ) {
358 const flow = activeFlow;
359 if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
360 return yield* setupError(name, "This sign-in is no longer active in this client.");
361 }
362 const now = yield* Clock.currentTimeMillis;
363 if (now >= flow.expiresAtMillis) {
364 return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
365 }
366 return flow;
367 });
368
369 const controller: ProviderAuthController = {
370 start: (ownerSessionId, stopSessions = Effect.void) =>
371 lock.withPermits(1)(
372 Effect.uninterruptible(
373 Effect.gen(function* () {
374 if (activeFlow?.ownerSessionId === ownerSessionId && operation === "auth") {
375 return activeFlow.state;
376 }
377 if (operation !== "idle") {
378 return yield* setupError("start", "Antigravity setup is already in progress.");
379 }
380 const flowId = yield* random
381 .uuidV4()
382 .pipe(
383 Effect.mapError(() =>
384 setupError("start", "Could not start Google sign-in. Try again."),
385 ),
386 );
387 const expiresAtMillis = (yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS;
388 const state: ProviderAuthState = {
389 ...emptyState,
390 phase: "starting",
391 flowId,
392 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAtMillis)),
393 message: usesBrowser ? "Starting Google sign-in." : "Checking credentials.",
394 };
395 const flow: AuthFlow = {
396 id: flowId,
397 ownerSessionId,
398 expiresAtMillis,
399 state,
400 pending: undefined,
401 callbackSent: false,
402 fiber: undefined,
403 forwarding: undefined,
404 };
405 activeFlow = flow;
406 operation = "auth";
407 yield* publishFlow(flow, state);
408 flow.fiber = yield* runSignIn(flow, stopSessions).pipe(
409 Effect.interruptible,
410 Effect.forkIn(instanceScope),
411 );
412 return state;
413 }),
414 ),
415 ),
416 complete: Effect.fn("AntigravityAuth.complete")(function* (ownerSessionId, input) {
417 const pending = yield* lock.withPermits(1)(
418 Effect.gen(function* () {
419 const flow = yield* requireFlow(ownerSessionId, input.flowId, "complete");
420 if (!flow.pending || flow.callbackSent) {
421 return yield* setupError(
422 "complete",
423 flow.callbackSent
424 ? "The sign-in response was already sent. Wait for Google to finish."
425 : "Wait for the Google sign-in link before you send a redirect URL.",
426 );
427 }
428 const callback = yield* validateAntigravityCallbackUrl(
429 options.instanceId,
430 flow.pending,
431 input.callbackUrl,
432 );
433 flow.callbackSent = true;
434 yield* publishFlow(flow, {
435 ...flow.state,
436 phase: "verifying",
437 authorizationUrl: null,
438 message: "Waiting for Google to finish sign-in.",
439 });
440 const forwarding = yield* (
441 options.forwardCallback?.(callback) ??
442 forwardAntigravityCallback(options.instanceId, callback)
443 ).pipe(
444 // stopFlow interrupts this fiber, so it runs from a sibling fiber.
445 Effect.tapError(() =>
446 stopFlow(flow, "failed", FORWARDING_FAILED_MESSAGE).pipe(
447 Effect.forkIn(instanceScope),
448 ),
449 ),
450 Effect.interruptible,
451 Effect.forkIn(instanceScope),
452 );
453 flow.forwarding = forwarding;
454 return { flow, forwarding };
455 }),
456 );
457 const forwarded = yield* Fiber.await(pending.forwarding);
458 if (Exit.isFailure(forwarded)) {
459 return yield* setupError("complete", FORWARDING_FAILED_MESSAGE);
460 }
461 return pending.flow.state;
462 }),
463 cancel: Effect.fn("AntigravityAuth.cancel")(function* (ownerSessionId, flowId) {
464 const flow = yield* lock.withPermits(1)(requireFlow(ownerSessionId, flowId, "cancel"));
465 yield* stopFlow(flow, "cancelled", "Google sign-in was cancelled.");
466 return flow.state;
467 }),
468 logout: Effect.fn("AntigravityAuth.logout")(function* (stopSessions) {
469 const task = Effect.uninterruptibleMask((restore) =>
470 Effect.gen(function* () {
471 const flow = yield* lock.withPermits(1)(
472 Effect.gen(function* () {
473 if (operation !== "idle" && operation !== "auth") {
474 return yield* setupError("logout", "Antigravity setup is already stopping.");
475 }
476 operation = "logout";
477 const currentFlow = activeFlow;
478 activeFlow = undefined;
479 if (currentFlow) {
480 currentFlow.pending = undefined;
481 yield* publishFlow(currentFlow, {
482 ...currentFlow.state,
483 phase: "cancelled",
484 authorizationUrl: null,
485 expiresAt: null,
486 message: "Google sign-in was cancelled by sign-out.",
487 });
488 }
489 return currentFlow;
490 }),
491 );
492 const stopRemaining = Effect.gen(function* () {
493 if (flow?.forwarding) yield* Fiber.interrupt(flow.forwarding);
494 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
495 yield* stopOwnedProcesses;
496 });
497 const result = yield* restore(
498 Effect.gen(function* () {
499 yield* stopSessions.pipe(Effect.ensuring(stopRemaining));
500 const runtime = yield* options.makeRuntime({});
501 const initialized = yield* runtime.initialize();
502 if (!initialized.agentCapabilities?.auth?.logout) {
503 return yield* setupError(
504 "logout",
505 "This Antigravity version does not support sign-out. Update the provider.",
506 );
507 }
508 yield* runtime.request("logout", {});
509 yield* options.onSignedOut;
510 }).pipe(
511 Effect.scoped,
512 Effect.timeoutOrElse({
513 duration: "90 seconds",
514 orElse: () => Effect.fail(setupError("logout", "Antigravity sign-out timed out.")),
515 }),
516 ),
517 ).pipe(Effect.exit);
518 yield* lock.withPermits(1)(
519 Effect.gen(function* () {
520 operation = "idle";
521 yield* SubscriptionRef.set(snapshot, {
522 ownerSessionId: null,
523 state: {
524 ...emptyState,
525 phase: Exit.isSuccess(result) ? "idle" : "failed",
526 message: Exit.isSuccess(result)
527 ? "Signed out of Google."
528 : "Antigravity sign-out failed. Try again.",
529 },
530 });
531 }),
532 );
533 if (Exit.isFailure(result)) {
534 const failure = Cause.findErrorOption(result.cause);
535 return yield* Option.isSome(failure) && isSetupError(failure.value)
536 ? failure.value
537 : setupError("logout", "Antigravity sign-out failed. Try again.");
538 }
539 return yield* currentState("");
540 }),
541 );
542 const worker = yield* task.pipe(Effect.forkIn(instanceScope));
543 return yield* Fiber.await(worker).pipe(Effect.flatMap((result) => result));
544 }),
545 subscribe: (ownerSessionId) =>
546 SubscriptionRef.changes(snapshot).pipe(
547 Stream.map((value) => {
548 const state = visibleSnapshot(value, ownerSessionId);
549 return {
550 ...state,
551 credentialOwner: "provider" as const,
552 interaction:
553 state.phase === "waiting" && state.authorizationUrl && state.flowId
554 ? {
555 type: "browser" as const,
556 id: state.flowId,
557 url: state.authorizationUrl,
558 requiresConsent: false,
559 acceptsCallback: true,
560 }
561 : null,
562 };
563 }),
564 Stream.interruptWhen(Deferred.await(closed)),
565 ),
566 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
567 };
568
569 yield* Effect.addFinalizer(() =>
570 Effect.gen(function* () {
571 operation = "closed";
572 const flow = activeFlow;
573 activeFlow = undefined;
574 if (flow) {
575 flow.pending = undefined;
576 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
577 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
578 }
579 yield* stopOwnedProcesses;
580 yield* Deferred.succeed(closed, undefined);
581 }),
582 );
583
584 return { controller, withProcess };
585});