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