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 antigravityLoginResponse,
25 parseAntigravityAuthorizationUrl,
26 type AntigravityAuthorizationUrl,
27} from "./antigravityAuthSupport.ts";
28import {
29 forwardAntigravityCallback,
30 validateAntigravityCallbackUrl,
31} from "./antigravityCallback.ts";
32import type { ProviderAuthController } from "./ProviderAuthService.ts";
33
34const AUTH_TIMEOUT_MS = 300_000;
35// Once initialized, a healthy agent shows the Google link within seconds; its bundled Python has no
36// IPv4 fallback, so broken IPv6 stalls each Google request. Startup is timed separately: the
37// one-file runtime unpacks on every launch (about a minute on Windows) before it answers initialize.
38const NO_RESPONSE_HINT_MS = 30_000;
39const STARTUP_HINT_MS = 90_000;
40const NOT_STARTED_MESSAGE =
41 "Antigravity has not started after 90 seconds. Its runtime may be stuck starting on this machine.";
42const NOT_RESPONDING_MESSAGE =
43 "Antigravity did not respond. Its runtime may not run on this machine.";
44const NO_RESPONSE_MESSAGE =
45 "Antigravity has not reached Google after 30 seconds. Check this machine's network connection. Broken IPv6 is a common cause.";
46const UNREACHABLE_MESSAGE =
47 "Antigravity could not reach Google. Check this machine's network connection, then start sign-in again.";
48const FORWARDING_FAILED_MESSAGE = "Could not deliver the sign-in response. Start sign-in again.";
49const LOGIN_CODE_FIELD = "code";
50const isSetupError = Schema.is(ProviderSetupError);
51const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
52const isAcpProcessExitedError = Schema.is(AcpErrors.AcpProcessExitedError);
53const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError);
54
55interface AuthSnapshot {
56 readonly ownerSessionId: string | null;
57 readonly state: ProviderAuthState;
58 readonly codeLogin?: boolean;
59}
60
61interface AuthFlow {
62 readonly id: string;
63 readonly ownerSessionId: string;
64 readonly expiresAtMillis: number;
65 state: ProviderAuthState;
66 pending: AntigravityAuthorizationUrl | undefined;
67 initialized: boolean;
68 callbackSent: boolean;
69 codeLogin: boolean;
70 submitCode: ((response: string) => Effect.Effect<void>) | undefined;
71 fiber: Fiber.Fiber<void> | undefined;
72 forwarding: Fiber.Fiber<void, ProviderSetupError> | undefined;
73}
74
75interface OwnedProcess {
76 readonly stop: Effect.Effect<void>;
77 startup: Fiber.Fiber<unknown, unknown> | undefined;
78}
79
80export interface AntigravityAuth {
81 readonly controller: ProviderAuthController;
82 readonly withProcess: <A, E, R>(
83 stop: Effect.Effect<void>,
84 task: Effect.Effect<A, E, R>,
85 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
86 /** A session started outside a flow, so an earlier flow's failure no longer describes sign-in. */
87 readonly onSignedInElsewhere: Effect.Effect<void>;
88}
89
90/** `agy acp --login`: it prints a Google link and reads the code the Antigravity page shows. */
91export interface AntigravityCodeLogin {
92 readonly submit: (response: string) => Effect.Effect<void>;
93 /** Succeeds once the runtime has stored the sign-in. */
94 readonly completed: Effect.Effect<void, ProviderSetupError>;
95}
96
97export type AntigravityAuthRuntime = Pick<
98 AcpSessionRuntime.AcpSessionRuntime["Service"],
99 "initialize" | "start" | "request"
100>;
101
102export interface AntigravityAuthOptions<
103 Runtime extends AntigravityAuthRuntime = AcpSessionRuntime.AcpSessionRuntime["Service"],
104> {
105 readonly instanceId: ProviderInstanceId;
106 readonly makeRuntime: (input: {
107 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
108 }) => Effect.Effect<Runtime, AcpErrors.AcpError | ProviderSetupError, Scope.Scope>;
109 readonly onAuthenticated: (
110 result: AcpSessionRuntime.AcpSessionRuntimeStartResult,
111 runtime: Runtime,
112 ) => Effect.Effect<void>;
113 readonly onSignedOut: Effect.Effect<void>;
114 readonly forwardCallback?: (callback: URL) => Effect.Effect<void, ProviderSetupError>;
115 readonly usesBrowser?: boolean;
116 /** Undefined when the runtime signs in through ACP `authenticate` and T3's browser helper. */
117 readonly codeLogin?: (input: {
118 readonly onAuthorizationUrl: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
119 }) => Effect.Effect<
120 AntigravityCodeLogin | undefined,
121 AcpErrors.AcpError | ProviderSetupError,
122 Scope.Scope
123 >;
124}
125
126function visibleSnapshot(snapshot: AuthSnapshot, ownerSessionId: string): ProviderAuthState {
127 if (snapshot.ownerSessionId === null || snapshot.ownerSessionId === ownerSessionId) {
128 return snapshot.state;
129 }
130 const busy = ["starting", "waiting", "verifying"].includes(snapshot.state.phase);
131 return {
132 ...snapshot.state,
133 flowId: null,
134 authorizationUrl: null,
135 interaction: null,
136 expiresAt: null,
137 ...(busy ? { message: "Sign-in is in progress in another client." } : {}),
138 };
139}
140
141function safeAuthFailure(cause: Cause.Cause<unknown>, usesBrowser: boolean): string {
142 const error = Cause.findErrorOption(cause);
143 if (Option.isSome(error)) {
144 if (isSetupError(error.value)) {
145 return error.value.detail;
146 }
147 // The driver wraps a refused runtime's update instruction in a transport error.
148 if (isAcpTransportError(error.value) && isSetupError(error.value.cause)) {
149 return error.value.cause.detail;
150 }
151 if (isAcpProcessExitedError(error.value)) {
152 const { code, signal } = error.value;
153 const reason =
154 signal !== undefined
155 ? ` after signal ${signal}`
156 : code !== undefined
157 ? ` with code ${code}`
158 : "";
159 return `Antigravity exited unexpectedly${reason}. Start sign-in again.`;
160 }
161 if (isAcpRequestError(error.value)) {
162 if (error.value.errorMessage.includes("SUBSCRIPTION_REQUIRED")) {
163 return "Google requires an eligible Antigravity subscription for this account.";
164 }
165 if (/access_denied|denied access|cancelled/i.test(error.value.errorMessage)) {
166 return "Google sign-in was not approved. Start sign-in again.";
167 }
168 if (error.value.method === "session/new" && error.value.code === -32603) {
169 return "Antigravity authenticated, but could not initialize a session or load models.";
170 }
171 if (!usesBrowser && error.value.code === -32602) {
172 return "Antigravity rejected the configured credentials. Check the provider settings.";
173 }
174 }
175 }
176 return usesBrowser
177 ? "Google sign-in failed. Start sign-in again."
178 : "Antigravity could not authenticate with the configured credentials.";
179}
180
181export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
182 Runtime extends AntigravityAuthRuntime,
183>(
184 options: AntigravityAuthOptions<Runtime>,
185): Effect.fn.Return<AntigravityAuth, never, SecureRandom.SecureRandom | Scope.Scope> {
186 const random = yield* SecureRandom.SecureRandom;
187 const instanceScope = yield* Scope.Scope;
188 const usesBrowser = options.usesBrowser ?? true;
189 const lock = yield* Semaphore.make(1);
190 const closed = yield* Deferred.make<void>();
191 const emptyState: ProviderAuthState = {
192 instanceId: options.instanceId,
193 phase: "idle",
194 flowId: null,
195 authorizationUrl: null,
196 expiresAt: null,
197 message: null,
198 };
199 const snapshot = yield* SubscriptionRef.make<AuthSnapshot>({
200 ownerSessionId: null,
201 state: emptyState,
202 });
203 const processes = new Set<OwnedProcess>();
204 let activeFlow: AuthFlow | undefined;
205 let operation: "idle" | "auth" | "logout" | "cancel" | "closed" = "idle";
206
207 const setupError = (name: string, detail: string) =>
208 new ProviderSetupError({ instanceId: options.instanceId, operation: name, detail });
209 const currentState = (ownerSessionId: string) =>
210 SubscriptionRef.get(snapshot).pipe(
211 Effect.map((value) => visibleSnapshot(value, ownerSessionId)),
212 );
213 const publishFlow = (flow: AuthFlow, state: ProviderAuthState) => {
214 flow.state = state;
215 return SubscriptionRef.set(snapshot, {
216 ownerSessionId: flow.ownerSessionId,
217 state,
218 codeLogin: flow.codeLogin,
219 });
220 };
221 const stopOwnedProcesses = Effect.suspend(() =>
222 Effect.forEach(
223 Array.from(processes),
224 (owned) =>
225 Effect.gen(function* () {
226 if (owned.startup) {
227 yield* Fiber.interrupt(owned.startup);
228 }
229 yield* owned.stop;
230 }),
231 { discard: true, concurrency: "unbounded" },
232 ),
233 );
234
235 const withProcess: AntigravityAuth["withProcess"] = (stop, task) =>
236 Effect.uninterruptibleMask((restore) =>
237 Effect.gen(function* () {
238 const scope = yield* Scope.Scope;
239 const owned: OwnedProcess = { stop, startup: undefined };
240 const fiber = yield* lock.withPermits(1)(
241 Effect.gen(function* () {
242 if (operation !== "idle") {
243 return yield* setupError(
244 "startProcess",
245 operation === "closed"
246 ? "This Antigravity session belongs to a provider instance that was reconfigured. Send the message again to start a new session."
247 : "Antigravity sign-in or sign-out is in progress. Try again after it finishes.",
248 );
249 }
250 processes.add(owned);
251 yield* Scope.addFinalizer(
252 scope,
253 Effect.sync(() => {
254 processes.delete(owned);
255 }),
256 );
257 const child = yield* restore(task).pipe(Effect.forkIn(scope));
258 owned.startup = child;
259 return child;
260 }),
261 );
262 // Propagate interruption after the exit wait so concurrent stop waiters stay attached.
263 return yield* restore(Fiber.await(fiber)).pipe(
264 Effect.flatten,
265 Effect.ensuring(Fiber.interrupt(fiber)),
266 Effect.ensuring(
267 Effect.sync(() => {
268 owned.startup = undefined;
269 }),
270 ),
271 );
272 }),
273 );
274
275 const finishFlow = (flow: AuthFlow, result: Exit.Exit<void, unknown>) =>
276 lock.withPermits(1)(
277 Effect.gen(function* () {
278 if (activeFlow !== flow) return;
279 activeFlow = undefined;
280 operation = "idle";
281 flow.pending = undefined;
282 yield* publishFlow(flow, {
283 ...flow.state,
284 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
285 authorizationUrl: null,
286 expiresAt: null,
287 message: Exit.isSuccess(result)
288 ? usesBrowser
289 ? "Signed in with Google."
290 : "Connected to Antigravity."
291 : safeAuthFailure(result.cause, usesBrowser),
292 });
293 }),
294 );
295
296 const receiveAuthorizationUrl = (flow: AuthFlow, url: string, redirect: "loopback" | "code") =>
297 parseAntigravityAuthorizationUrl(url, redirect).pipe(
298 Effect.flatMap((authorization) =>
299 lock.withPermits(1)(
300 Effect.gen(function* () {
301 if (activeFlow !== flow || operation !== "auth") return;
302 if (flow.pending) {
303 if (flow.pending.authorizationUrl === authorization.authorizationUrl) return;
304 return yield* new AcpErrors.AcpTransportError({
305 detail: "Antigravity started more than one Google sign-in request.",
306 cause: undefined,
307 });
308 }
309 flow.pending = authorization;
310 flow.codeLogin = redirect === "code";
311 yield* publishFlow(flow, {
312 ...flow.state,
313 phase: "waiting",
314 authorizationUrl: authorization.authorizationUrl,
315 message:
316 redirect === "loopback"
317 ? "Open the Google sign-in link. If you are remote, paste the redirect URL here."
318 : "Open the Google sign-in link, then paste the code from the Antigravity page here.",
319 });
320 }),
321 ),
322 ),
323 );
324
325 const publishStartingHint = (flow: AuthFlow, delayMs: number, message: string) =>
326 Effect.sleep(delayMs).pipe(
327 Effect.andThen(
328 lock.withPermits(1)(
329 Effect.gen(function* () {
330 if (activeFlow !== flow || flow.state.phase !== "starting") return;
331 yield* publishFlow(flow, { ...flow.state, message });
332 }),
333 ),
334 ),
335 Effect.forkScoped,
336 );
337
338 const runSignIn = Effect.fn("AntigravityAuth.runSignIn")(
339 function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
340 yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses));
341 const signedIn = yield* Effect.scoped(
342 Effect.gen(function* () {
343 const login = yield* (
344 options.codeLogin?.({
345 onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url, "code"),
346 }) ?? Effect.undefined
347 );
348 if (login === undefined) return false;
349 flow.submitCode = login.submit;
350 yield* login.completed;
351 return true;
352 }),
353 );
354 const runtime = yield* options.makeRuntime(
355 signedIn
356 ? {}
357 : { onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url, "loopback") },
358 );
359 const startupHint = yield* publishStartingHint(flow, STARTUP_HINT_MS, NOT_STARTED_MESSAGE);
360 // `start` reuses this memoized handshake.
361 yield* runtime.initialize();
362 flow.initialized = true;
363 yield* Fiber.interrupt(startupHint);
364 yield* publishStartingHint(flow, NO_RESPONSE_HINT_MS, NO_RESPONSE_MESSAGE);
365 const started = yield* runtime.start();
366 yield* lock.withPermits(1)(
367 Effect.gen(function* () {
368 if (activeFlow !== flow) return;
369 flow.pending = undefined;
370 yield* publishFlow(flow, {
371 ...flow.state,
372 phase: "verifying",
373 authorizationUrl: null,
374 message: "Checking Antigravity access and models.",
375 });
376 }),
377 );
378 yield* options.onAuthenticated(started, runtime);
379 },
380 (effect, flow, _stopSessions) =>
381 effect.pipe(
382 Effect.scoped,
383 Effect.timeoutOrElse({
384 duration: AUTH_TIMEOUT_MS,
385 orElse: () =>
386 Effect.fail(
387 setupError(
388 "start",
389 flow.state.phase !== "starting"
390 ? "Google sign-in expired. Start sign-in again."
391 : flow.initialized
392 ? UNREACHABLE_MESSAGE
393 : NOT_RESPONDING_MESSAGE,
394 ),
395 ),
396 }),
397 Effect.exit,
398 Effect.flatMap((result) => finishFlow(flow, result)),
399 ),
400 );
401
402 const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>
403 Effect.uninterruptible(
404 Effect.gen(function* () {
405 const detached = yield* lock.withPermits(1)(
406 Effect.gen(function* () {
407 if (activeFlow !== flow) return false;
408 activeFlow = undefined;
409 operation = "cancel";
410 flow.pending = undefined;
411 yield* publishFlow(flow, {
412 ...flow.state,
413 phase,
414 authorizationUrl: null,
415 expiresAt: null,
416 message,
417 });
418 return true;
419 }),
420 );
421 if (!detached) return;
422 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
423 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
424 yield* lock.withPermits(1)(
425 Effect.sync(() => {
426 if (operation === "cancel") operation = "idle";
427 }),
428 );
429 }),
430 );
431
432 const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* (
433 ownerSessionId: string,
434 flowId: string,
435 name: string,
436 ) {
437 const flow = activeFlow;
438 if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
439 return yield* setupError(name, "This sign-in is no longer active in this client.");
440 }
441 const now = yield* Clock.currentTimeMillis;
442 if (now >= flow.expiresAtMillis) {
443 return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
444 }
445 return flow;
446 });
447
448 const controller: ProviderAuthController = {
449 start: (ownerSessionId, stopSessions = Effect.void) =>
450 lock.withPermits(1)(
451 Effect.uninterruptible(
452 Effect.gen(function* () {
453 if (activeFlow?.ownerSessionId === ownerSessionId && operation === "auth") {
454 return activeFlow.state;
455 }
456 if (operation !== "idle") {
457 return yield* setupError("start", "Antigravity setup is already in progress.");
458 }
459 const flowId = yield* random
460 .uuidV4()
461 .pipe(
462 Effect.mapError(() =>
463 setupError("start", "Could not start Google sign-in. Try again."),
464 ),
465 );
466 const expiresAtMillis = (yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS;
467 const state: ProviderAuthState = {
468 ...emptyState,
469 phase: "starting",
470 flowId,
471 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAtMillis)),
472 message: usesBrowser ? "Starting Google sign-in." : "Checking credentials.",
473 };
474 const flow: AuthFlow = {
475 id: flowId,
476 ownerSessionId,
477 expiresAtMillis,
478 state,
479 pending: undefined,
480 initialized: false,
481 callbackSent: false,
482 codeLogin: false,
483 submitCode: undefined,
484 fiber: undefined,
485 forwarding: undefined,
486 };
487 activeFlow = flow;
488 operation = "auth";
489 yield* publishFlow(flow, state);
490 flow.fiber = yield* runSignIn(flow, stopSessions).pipe(
491 Effect.interruptible,
492 Effect.forkIn(instanceScope),
493 );
494 return state;
495 }),
496 ),
497 ),
498 complete: Effect.fn("AntigravityAuth.complete")(function* (ownerSessionId, input) {
499 const pending = yield* lock.withPermits(1)(
500 Effect.gen(function* () {
501 const flow = yield* requireFlow(ownerSessionId, input.flowId, "complete");
502 if (!flow.pending || flow.callbackSent) {
503 return yield* setupError(
504 "complete",
505 flow.callbackSent
506 ? "The sign-in response was already sent. Wait for Google to finish."
507 : "Wait for the Google sign-in link before you send a redirect URL.",
508 );
509 }
510 const callback = yield* validateAntigravityCallbackUrl(
511 options.instanceId,
512 flow.pending,
513 input.callbackUrl,
514 );
515 flow.callbackSent = true;
516 yield* publishFlow(flow, {
517 ...flow.state,
518 phase: "verifying",
519 authorizationUrl: null,
520 message: "Waiting for Google to finish sign-in.",
521 });
522 const forwarding = yield* (
523 options.forwardCallback?.(callback) ??
524 forwardAntigravityCallback(options.instanceId, callback)
525 ).pipe(
526 // stopFlow interrupts this fiber, so it runs from a sibling fiber.
527 Effect.tapError(() =>
528 stopFlow(flow, "failed", FORWARDING_FAILED_MESSAGE).pipe(
529 Effect.forkIn(instanceScope),
530 ),
531 ),
532 Effect.interruptible,
533 Effect.forkIn(instanceScope),
534 );
535 flow.forwarding = forwarding;
536 return { flow, forwarding };
537 }),
538 );
539 const forwarded = yield* Fiber.await(pending.forwarding);
540 if (Exit.isFailure(forwarded)) {
541 return yield* setupError("complete", FORWARDING_FAILED_MESSAGE);
542 }
543 return pending.flow.state;
544 }),
545 respond: Effect.fn("AntigravityAuth.respond")(function* (ownerSessionId, input) {
546 return yield* lock.withPermits(1)(
547 Effect.gen(function* () {
548 const flow = yield* requireFlow(ownerSessionId, input.flowId, "respond");
549 if (!flow.pending || !flow.submitCode || flow.callbackSent) {
550 return yield* setupError(
551 "respond",
552 flow.callbackSent
553 ? "The sign-in response was already sent. Wait for Google to finish."
554 : "Wait for the Google sign-in link before you send a code.",
555 );
556 }
557 const response =
558 input.interactionId === flow.id && input.response.type === "credentials"
559 ? antigravityLoginResponse(
560 flow.pending,
561 input.response.values[LOGIN_CODE_FIELD] ?? "",
562 )
563 : undefined;
564 if (response === undefined) {
565 return yield* setupError(
566 "respond",
567 "Paste the code from the Antigravity page, or that page's full URL.",
568 );
569 }
570 flow.callbackSent = true;
571 yield* flow.submitCode(response);
572 yield* publishFlow(flow, {
573 ...flow.state,
574 phase: "verifying",
575 authorizationUrl: null,
576 message: "Waiting for Google to finish sign-in.",
577 });
578 return flow.state;
579 }),
580 );
581 }),
582 cancel: Effect.fn("AntigravityAuth.cancel")(function* (ownerSessionId, flowId) {
583 const flow = yield* lock.withPermits(1)(requireFlow(ownerSessionId, flowId, "cancel"));
584 yield* stopFlow(flow, "cancelled", "Google sign-in was cancelled.");
585 return flow.state;
586 }),
587 logout: Effect.fn("AntigravityAuth.logout")(function* (stopSessions) {
588 const task = Effect.uninterruptibleMask((restore) =>
589 Effect.gen(function* () {
590 const flow = yield* lock.withPermits(1)(
591 Effect.gen(function* () {
592 if (operation !== "idle" && operation !== "auth") {
593 return yield* setupError("logout", "Antigravity setup is already stopping.");
594 }
595 operation = "logout";
596 const currentFlow = activeFlow;
597 activeFlow = undefined;
598 if (currentFlow) {
599 currentFlow.pending = undefined;
600 yield* publishFlow(currentFlow, {
601 ...currentFlow.state,
602 phase: "cancelled",
603 authorizationUrl: null,
604 expiresAt: null,
605 message: "Google sign-in was cancelled by sign-out.",
606 });
607 }
608 return currentFlow;
609 }),
610 );
611 const stopRemaining = Effect.gen(function* () {
612 if (flow?.forwarding) yield* Fiber.interrupt(flow.forwarding);
613 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
614 yield* stopOwnedProcesses;
615 });
616 const result = yield* restore(
617 Effect.gen(function* () {
618 yield* stopSessions.pipe(Effect.ensuring(stopRemaining));
619 const runtime = yield* options.makeRuntime({});
620 const initialized = yield* runtime.initialize();
621 if (!initialized.agentCapabilities?.auth?.logout) {
622 return yield* setupError(
623 "logout",
624 "This Antigravity version does not support sign-out. Update the provider.",
625 );
626 }
627 yield* runtime.request("logout", {});
628 yield* options.onSignedOut;
629 }).pipe(
630 Effect.scoped,
631 Effect.timeoutOrElse({
632 duration: "90 seconds",
633 orElse: () => Effect.fail(setupError("logout", "Antigravity sign-out timed out.")),
634 }),
635 ),
636 ).pipe(Effect.exit);
637 yield* lock.withPermits(1)(
638 Effect.gen(function* () {
639 operation = "idle";
640 yield* SubscriptionRef.set(snapshot, {
641 ownerSessionId: null,
642 state: {
643 ...emptyState,
644 phase: Exit.isSuccess(result) ? "idle" : "failed",
645 message: Exit.isSuccess(result)
646 ? "Signed out of Google."
647 : "Antigravity sign-out failed. Try again.",
648 },
649 });
650 }),
651 );
652 if (Exit.isFailure(result)) {
653 const failure = Cause.findErrorOption(result.cause);
654 return yield* Option.isSome(failure) && isSetupError(failure.value)
655 ? failure.value
656 : setupError("logout", "Antigravity sign-out failed. Try again.");
657 }
658 return yield* currentState("");
659 }),
660 );
661 const worker = yield* task.pipe(Effect.forkIn(instanceScope));
662 return yield* Fiber.await(worker).pipe(Effect.flatten);
663 }),
664 subscribe: (ownerSessionId) =>
665 SubscriptionRef.changes(snapshot).pipe(
666 Stream.map((value) => {
667 const state = visibleSnapshot(value, ownerSessionId);
668 return {
669 ...state,
670 credentialOwner: "provider" as const,
671 interaction:
672 state.phase === "waiting" && state.authorizationUrl && state.flowId
673 ? value.codeLogin
674 ? {
675 type: "credentials" as const,
676 id: state.flowId,
677 fields: [
678 {
679 name: LOGIN_CODE_FIELD,
680 label: "Code from the Antigravity page",
681 secret: false,
682 },
683 ],
684 }
685 : {
686 type: "browser" as const,
687 id: state.flowId,
688 url: state.authorizationUrl,
689 requiresConsent: false,
690 acceptsCallback: true,
691 }
692 : null,
693 };
694 }),
695 Stream.interruptWhen(Deferred.await(closed)),
696 ),
697 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
698 };
699
700 yield* Effect.addFinalizer(() =>
701 Effect.gen(function* () {
702 operation = "closed";
703 const flow = activeFlow;
704 activeFlow = undefined;
705 if (flow) {
706 flow.pending = undefined;
707 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
708 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
709 }
710 yield* stopOwnedProcesses;
711 yield* Deferred.succeed(closed, undefined);
712 }),
713 );
714
715 const onSignedInElsewhere = SubscriptionRef.update(snapshot, (value) =>
716 activeFlow === undefined &&
717 operation === "idle" &&
718 (value.state.phase === "failed" || value.state.phase === "cancelled")
719 ? { ownerSessionId: null, state: emptyState }
720 : value,
721 );
722
723 return { controller, withProcess, onSignedInElsewhere };
724});