@wenathlan/getry 2.0.165 → 2.0.167

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/accounts.ts +2087 -0
  3. package/antigravity.ts +2171 -0
  4. package/auth.ts +265 -0
  5. package/cli.ts +3 -3
  6. package/constants.ts +950 -0
  7. package/db.ts +810 -0
  8. package/docs/distributionlanes.md +1 -1
  9. package/docs/features.md +1 -2
  10. package/docs/gateway.md +2 -3
  11. package/docs/getry.md +33 -0
  12. package/engine.ts +1535 -0
  13. package/fingerprint.ts +1461 -0
  14. package/gateway.ts +1306 -0
  15. package/gatewaycheck.ts +142 -0
  16. package/intelligence.ts +169 -0
  17. package/json.ts +932 -0
  18. package/labels.ts +262 -0
  19. package/llm.ts +2709 -0
  20. package/models.ts +4017 -0
  21. package/nodeshim.ts +265 -0
  22. package/oauth.ts +2201 -0
  23. package/package.json +580 -225
  24. package/project.ts +1293 -0
  25. package/providers.ts +3238 -0
  26. package/quota.ts +1891 -0
  27. package/recovery.ts +2434 -0
  28. package/request.ts +4496 -0
  29. package/search.ts +1761 -0
  30. package/server.ts +766 -0
  31. package/streaming.ts +4398 -0
  32. package/{tests → test}/cli.test.ts +1 -1
  33. package/{tests → test}/gateway.test.ts +2 -2
  34. package/{tests → test}/gatewayversions.test.ts +1 -1
  35. package/{tests → test}/intelligence.test.ts +1 -1
  36. package/{tests → test}/keyrotation.test.ts +1 -1
  37. package/{tests → test}/onboardingstate.test.ts +1 -1
  38. package/{tests → test}/providerfixtures.ts +12 -12
  39. package/{tests → test}/researchfixtures.ts +1 -1
  40. package/{tests → test}/sandboxmodality.test.ts +1 -1
  41. package/thinking.ts +416 -0
  42. package/types.ts +809 -0
  43. package/utils.ts +263 -0
  44. package/validate.ts +61 -0
  45. package/versionregistry.ts +1325 -0
  46. /package/{tests → test}/debonairlane.test.ts +0 -0
  47. /package/{tests → test}/design.test.ts +0 -0
  48. /package/{tests → test}/family.test.ts +0 -0
  49. /package/{tests → test}/gatewayserver.ts +0 -0
  50. /package/{tests → test}/jsonpolicy.test.ts +0 -0
  51. /package/{tests → test}/llm.test.ts +0 -0
  52. /package/{tests → test}/modelroute.test.ts +0 -0
  53. /package/{tests → test}/promptlibrary.test.ts +0 -0
  54. /package/{tests → test}/providercli.test.ts +0 -0
  55. /package/{tests → test}/providerconstants.test.ts +0 -0
  56. /package/{tests → test}/providerfingerprint.test.ts +0 -0
  57. /package/{tests → test}/providermodels.test.ts +0 -0
  58. /package/{tests → test}/provideroauth.test.ts +0 -0
  59. /package/{tests → test}/routerotation.test.ts +0 -0
  60. /package/{tests → test}/serverauth.test.ts +0 -0
  61. /package/{tests → test}/serverengine.test.ts +0 -0
  62. /package/{tests → test}/serverproperty.test.ts +0 -0
  63. /package/{tests → test}/serverutils.test.ts +0 -0
  64. /package/{tests → test}/streamfallback.test.ts +0 -0
  65. /package/{tests → test}/thinkingladder.test.ts +0 -0
  66. /package/{tests → test}/torturellm.test.ts +0 -0
package/oauth.ts ADDED
@@ -0,0 +1,2201 @@
1
+ /* ── Merged: the grand merge section ── the correlated provider oauth logics of the merged repository interned here, one surface without duplicate variations ── */
2
+ /**
3
+ * @file oauth.ts — the provider oauth family of the merged repository.
4
+ * @description The grand merge consolidation: ONE file owns the ENTIRE
5
+ * provider authentication context (OAuth clients, PKCE, consent
6
+ * URL, callback server, token exchange, token refresh, userinfo,
7
+ * account file management, identity bundles) of the merged
8
+ * repository. Absorbed verbatim:
9
+ * (a) the CLI identity bundle of the antigravity engine lineage;
10
+ * (b) the Gemini CLI OAuth client + shared endpoint/model
11
+ * constants of the provider family;
12
+ * (c) the full-featured OAuth primitives (PKCE, auth URL
13
+ * builder, callback server, exchange, refresh, userinfo);
14
+ * (d) the minimal legacy flow + the v3 account manager +
15
+ * project/quota helpers of the provider family;
16
+ * (e) the oauth orchestrators and helpers (authenticate,
17
+ * startOAuthFlow, validation, model lists, header builders,
18
+ * platform detection, the legacy default export object).
19
+ *
20
+ * The family is server and cli surface — the neutral core
21
+ * barrel (index.ts) never carries it, so the browser bundles
22
+ * stay free of node imports: node:* builtins first, global
23
+ * fetch beside them.
24
+ *
25
+ * History (v2.1.13 header of the former auth.ts): v5 definitive
26
+ * full flow with researches 9router omniroute gemini-cli;
27
+ * 20 logics correlated, lowercase, node:* first, dual bypass
28
+ * definitive, accounts file v3 with addedAt createdAt lastUsed
29
+ * expiry; mapModelToGroup ported from auth(1).ts (v4); optional
30
+ * name in userInfo return from auth(2).ts (v3).
31
+ *
32
+ * v2.1.14 collision policy - three DISTINCT Google OAuth client
33
+ * identities coexist (different clients, not duplicates):
34
+ * 1. Antigravity CLI client: CLIENT_ID / CLIENT_SECRET (canonical,
35
+ * env-overridable via ANTIGRAVITY_CLIENT_ID /
36
+ * ANTIGRAVITY_CLIENT_SECRET; aliased by
37
+ * ANTIGRAVITY_CLI_CLIENT_ID / ANTIGRAVITY_CLI_CLIENT_SECRET).
38
+ * 2. Gemini CLI client: GEMINI_OAUTH_CLIENT_ID /
39
+ * GEMINI_OAUTH_CLIENT_SECRET (+ GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE
40
+ * and the legacy alias CLIENT_SECRET_ALTERNATIVE) - the former
41
+ * oauth.ts CLIENT_ID / CLIENT_SECRET / CLIENT_SECRET_ALTERNATIVE
42
+ * values.
43
+ * 3. Antigravity IDE blinded decoy: constants.ts (not this file).
44
+ * Other collisions resolved the same way (the original auth.ts
45
+ * meaning wins the bare name): SCOPES (Antigravity scope string) vs
46
+ * GEMINI_OAUTH_SCOPES (former oauth.ts scope array), ENDPOINTS
47
+ * (Antigravity base-URL array) vs CLOUDCODE_ENDPOINTS (former
48
+ * oauth.ts endpoint map), openBrowser (former auth.ts void spawner)
49
+ * vs openBrowserAsync (former oauth.ts cross-platform WSL-aware
50
+ * opener). USERINFO_URL was byte-identical in both former files and
51
+ * is declared once. The default export preserves the legacy oauth.js
52
+ * object shape with the Gemini CLI values for CJS/ESM interop
53
+ * consumers.
54
+ *
55
+ * Self-contained: only node:* builtins + global fetch; no external
56
+ * dependencies, no project-file imports.
57
+ */
58
+
59
+ // node:* imports of the three former files, deduplicated into one block. The
60
+ // namespace forms serve the former oauth.ts bodies; the named forms serve the
61
+ // former auth.ts bodies (both kept verbatim, so the two styles coexist).
62
+ import * as crypto from "node:crypto";
63
+ import * as http from "node:http";
64
+ import * as os from "node:os";
65
+ import * as readline from "node:readline";
66
+ import * as net from "node:net";
67
+ import * as url from "node:url";
68
+ import { spawn } from "node:child_process";
69
+ import { createHash, randomBytes } from "node:crypto";
70
+ import { createServer } from "node:http";
71
+ import { homedir, platform, arch } from "node:os";
72
+ import { join } from "node:path";
73
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, renameSync, unlinkSync } from "node:fs";
74
+
75
+ // =============================================================================
76
+ // SECTION A - ANTIGRAVITY CLI IDENTITY BUNDLE (former antigravity-cli.ts, v2.1.8)
77
+ // =============================================================================
78
+ // Extracted from the distributed `agy` binary and live-validated end to end on
79
+ // 2026-08-26 (consent screen renders as "Google Antigravity"; loopback redirect
80
+ // accepted; code exchange + refresh + userinfo + loadCodeAssist +
81
+ // fetchAvailableModels + generateContent all verified live).
82
+ //
83
+ // Layout: library-first, root-first (no src/ folder, the former file lived
84
+ // beside its siblings). Platform-agnostic: every path resolves dynamically per
85
+ // OS, nothing is hardcoded to a single machine layout.
86
+ //
87
+ // Masquerade set of the provider plugin (all four Google client identities):
88
+ // 1. Gemini CLI - GeminiCLI/x.y.z UA (see fingerprint.ts)
89
+ // 2. Antigravity CLI - THIS section (agy binary identity)
90
+ // 3. Antigravity IDE - antigravity/x.y.z UA (see constants.ts)
91
+ // 4. Gemini Code Assist - ideType/pluginType metadata (Section B below)
92
+ // =============================================================================
93
+
94
+ // =============================================================================
95
+ // OAUTH CLIENT - OFFICIAL ANTIGRAVITY CLI (`agy`)
96
+ // =============================================================================
97
+
98
+ /**
99
+ * Canonical OAuth client credentials of the Antigravity CLI (formerly the
100
+ * top-level definitions of auth.ts). The grand merge consolidation moved the
101
+ * env-overridable owner into constants.ts (the layer-0 raw-value module) so
102
+ * the client pair never rides an import cycle; this module keeps the
103
+ * authentication-surface aliases. Env chain: ANTIGRAVITY_CLIENT_ID /
104
+ * GOOGLE_CLIENT_ID / ANTIGRAVITY_CLIENT_SECRET. Google renders the consent
105
+ * screen as "Google Antigravity" for this client.
106
+ */
107
+ import {
108
+ ANTIGRAVITY_CLI_OAUTH_CLIENT_ID as AGY_OAUTH_CLIENT_ID,
109
+ ANTIGRAVITY_CLI_OAUTH_CLIENT_SECRET as AGY_OAUTH_CLIENT_SECRET,
110
+ } from "./constants.js";
111
+ export const CLIENT_ID: string = AGY_OAUTH_CLIENT_ID;
112
+ export const CLIENT_SECRET: string = AGY_OAUTH_CLIENT_SECRET;
113
+
114
+ /**
115
+ * OAuth Client ID of the Antigravity CLI, assembled at runtime from segments
116
+ * (exactly the constant the `agy` binary embeds). Google renders the consent
117
+ * screen as "Google Antigravity" for this client.
118
+ * v2.1.14: byte-identical to the canonical CLIENT_ID above (same value,
119
+ * different segment split) - deduplicated into the single env-overridable
120
+ * definition; this historical name now aliases it.
121
+ */
122
+ export const ANTIGRAVITY_CLI_CLIENT_ID: string = CLIENT_ID;
123
+
124
+ /**
125
+ * Primary client secret paired with {@link ANTIGRAVITY_CLI_CLIENT_ID}
126
+ * (runtime-assembled). This is the secret that answers the token endpoint —
127
+ * live-verified 2026-08-26.
128
+ * v2.1.14: byte-identical to the canonical CLIENT_SECRET above (same value,
129
+ * different segment split) - deduplicated; this historical name now aliases it.
130
+ */
131
+ export const ANTIGRAVITY_CLI_CLIENT_SECRET: string = CLIENT_SECRET;
132
+
133
+ /**
134
+ * Alternative secret variant also embedded in the binary — kept under an
135
+ * alias so no credential variant is lost; not used by default.
136
+ */
137
+ export const ANTIGRAVITY_CLI_CLIENT_SECRET_ALTERNATIVE: string = ["GOCSPX", "-9YQWpF7RWDC0QTdj-YxKMwR0Zts", "X"].join(
138
+ "",
139
+ );
140
+
141
+ /**
142
+ * Scopes the Antigravity CLI requests (byte-for-byte the set the CLI puts in
143
+ * the consent URL — includes the aicode / cclog / experimentsandconfigs
144
+ * grants the Gemini CLI client does not ask for).
145
+ */
146
+ export const ANTIGRAVITY_CLI_OAUTH_SCOPES: readonly string[] = [
147
+ "https://www.googleapis.com/auth/cloud-platform",
148
+ "https://www.googleapis.com/auth/userinfo.email",
149
+ "https://www.googleapis.com/auth/userinfo.profile",
150
+ "https://www.googleapis.com/auth/cclog",
151
+ "https://www.googleapis.com/auth/experimentsandconfigs",
152
+ "https://www.googleapis.com/auth/aicode",
153
+ "openid",
154
+ ] as const;
155
+
156
+ /** Space-joined scope string (consent URL / token endpoint form). */
157
+ export const ANTIGRAVITY_CLI_OAUTH_SCOPES_STR: string = ANTIGRAVITY_CLI_OAUTH_SCOPES.join(" ");
158
+
159
+ /**
160
+ * Redirect URI the official CLI uses. NOTE: the CLI shows a code on this
161
+ * remote page that the user must copy/paste back — the plugin does NOT use it.
162
+ * the plugin uses a loopback redirect (accepted by Google for this client,
163
+ * live-verified) which makes the whole flow automatic, no copy/paste.
164
+ */
165
+ export const ANTIGRAVITY_CLI_REDIRECT_OFFICIAL: string = "https://antigravity.google/oauth-callback";
166
+
167
+ /**
168
+ * Auth-success page the CLI flow can land on (kept for fidelity of the
169
+ * identity; the loopback flow serves its own local success page).
170
+ */
171
+ export const ANTIGRAVITY_CLI_AUTH_SUCCESS_URL: string = "https://antigravity.google/auth-success";
172
+
173
+ // =============================================================================
174
+ // VERSION POOLS - date-aware (consulted 2026-08-26)
175
+ // =============================================================================
176
+
177
+ /** Latest Antigravity CLI release seen on the official update manifest. */
178
+ export const ANTIGRAVITY_CLI_VERSION_LATEST: string = "1.1.21";
179
+
180
+ /**
181
+ * Recent Antigravity CLI versions (public update manifest history + binary
182
+ * telemetry). The pool exists so every account can present a plausible
183
+ * real-world version instead of a single frozen one.
184
+ */
185
+ // v2.1.15 Phase B: ANTIGRAVITY_CLI_VERSION_POOL moved to constants.js (raw value owner).
186
+
187
+ /** grpc-go version line compiled into the `agy` binary (1.1.21). */
188
+ export const ANTIGRAVITY_CLI_GRPC_VERSION: string = "1.85.0";
189
+
190
+ // =============================================================================
191
+ // FINGERPRINT - User-Agent / X-Goog-Api-Client / Client-Metadata
192
+ // =============================================================================
193
+
194
+ /** Normalizes node's platform into the CLI's lowercase os names. */
195
+ export function antigravityCliOsName(): string {
196
+ const p = process.platform;
197
+ if (p === "win32") return "windows";
198
+ if (p === "darwin") return "macos";
199
+ return "linux";
200
+ }
201
+
202
+ /** amd64/arm64 style arch (matches the CLI manifest names). */
203
+ export function antigravityCliArchName(): string {
204
+ return process.arch === "arm64" ? "arm64" : "amd64";
205
+ }
206
+
207
+ /**
208
+ * Builds the User-Agent the Antigravity CLI presents.
209
+ * Shape: `antigravity-cli/<version> (<os>; <arch>)`.
210
+ */
211
+ export function buildAntigravityCliUserAgent(version?: string): string {
212
+ const v = version ?? ANTIGRAVITY_CLI_VERSION_LATEST;
213
+ return `antigravity-cli/${v} (${antigravityCliOsName()}; ${antigravityCliArchName()})`;
214
+ }
215
+
216
+ /**
217
+ * X-Goog-Api-Client value for the Antigravity CLI identity.
218
+ * Shape: `antigravity-cli/<version> grpc-go/<grpc>`.
219
+ */
220
+ export function buildAntigravityCliXGoogApiClient(version?: string): string {
221
+ const v = version ?? ANTIGRAVITY_CLI_VERSION_LATEST;
222
+ return `antigravity-cli/${v} grpc-go/${ANTIGRAVITY_CLI_GRPC_VERSION}`;
223
+ }
224
+
225
+ /**
226
+ * Complete request headers for the Antigravity CLI identity.
227
+ * The Antigravity CLI does not send the ideType/pluginType Client-Metadata
228
+ * header the Gemini CLI family uses — its fingerprint is UA + api client.
229
+ */
230
+ export function getAntigravityCliHeaders(version?: string): Record<string, string> {
231
+ return {
232
+ "User-Agent": buildAntigravityCliUserAgent(version),
233
+ "X-Goog-Api-Client": buildAntigravityCliXGoogApiClient(version),
234
+ };
235
+ }
236
+
237
+ // =============================================================================
238
+ // IDENTITY RESOLUTION - which OAuth client does an account use?
239
+ // =============================================================================
240
+
241
+ /** OAuth client identities the plugin can present. */
242
+ export type MaeneOAuthIdentity = "antigravity-cli" | "gemini-cli";
243
+
244
+ /**
245
+ * Resolved OAuth client bundle for an identity.
246
+ * Everything the consent URL builder, the token exchange and the refresh
247
+ * call need — no hidden globals.
248
+ */
249
+ export interface OAuthIdentityBundle {
250
+ identity: MaeneOAuthIdentity;
251
+ clientId: string;
252
+ clientSecret: string;
253
+ clientSecretAlternative: string;
254
+ scopes: readonly string[];
255
+ scopesStr: string;
256
+ /** Antigravity CLI flow is PKCE (S256); Gemini CLI web flow is state-only. */
257
+ usesPKCE: boolean;
258
+ userAgent: string;
259
+ /** Human label of the app Google shows on the consent screen. */
260
+ appLabel: string;
261
+ }
262
+
263
+ /**
264
+ * Resolves the OAuth client bundle for an identity.
265
+ *
266
+ * Default policy ("auto"): NEW logins use the Antigravity CLI client — the
267
+ * Gemini CLI free tier for individuals was retired (UNSUPPORTED_CLIENT,
268
+ * observed live 2026-08) and the Antigravity client is the one the current
269
+ * free tier ("Antigravity") onboards. Stored accounts keep the identity they
270
+ * authenticated with, whatever it was.
271
+ */
272
+ export function resolveOAuthIdentity(
273
+ identity?: MaeneOAuthIdentity | "auto" | (string & {}) | null,
274
+ ): OAuthIdentityBundle {
275
+ const wanted =
276
+ identity === "gemini-cli"
277
+ ? "gemini-cli"
278
+ : identity === "antigravity-cli" || identity === undefined || identity === null || identity === "auto"
279
+ ? "antigravity-cli"
280
+ : "antigravity-cli"; // unknown values fall back to the default client
281
+
282
+ if (wanted === "gemini-cli") {
283
+ return {
284
+ identity: "gemini-cli",
285
+ clientId: GEMINI_OAUTH_CLIENT_ID,
286
+ clientSecret: GEMINI_OAUTH_CLIENT_SECRET,
287
+ clientSecretAlternative: GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE,
288
+ scopes: GEMINI_CLI_SCOPES,
289
+ scopesStr: GEMINI_CLI_OAUTH_SCOPE_STR,
290
+ usesPKCE: false,
291
+ userAgent: `GeminiCLI/0.57.0/gemini-3-pro-preview (${antigravityCliOsName()}; ${antigravityCliArchName()}; GitHub) google-api-nodejs-client/9.15.1`,
292
+ appLabel: "Gemini Code Assist and Gemini CLI",
293
+ };
294
+ }
295
+
296
+ return {
297
+ identity: "antigravity-cli",
298
+ clientId: ANTIGRAVITY_CLI_CLIENT_ID,
299
+ clientSecret: ANTIGRAVITY_CLI_CLIENT_SECRET,
300
+ clientSecretAlternative: ANTIGRAVITY_CLI_CLIENT_SECRET_ALTERNATIVE,
301
+ scopes: ANTIGRAVITY_CLI_OAUTH_SCOPES,
302
+ scopesStr: ANTIGRAVITY_CLI_OAUTH_SCOPES_STR,
303
+ usesPKCE: true,
304
+ userAgent: buildAntigravityCliUserAgent(),
305
+ appLabel: "Google Antigravity",
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Maps a stored account `type` back to the OAuth identity it must refresh
311
+ * with. Anything that is not explicitly the Gemini CLI client refreshes with
312
+ * the Antigravity CLI client (the default since 2.1.8).
313
+ */
314
+ export function identityFromAccountType(accountType?: string | null): MaeneOAuthIdentity {
315
+ if (accountType === "gemini-cli") return "gemini-cli";
316
+ return "antigravity-cli";
317
+ }
318
+
319
+ // =============================================================================
320
+ // SECTION B - GEMINI CLI OAUTH CLIENT + SHARED CONSTANTS (former oauth.ts)
321
+ // =============================================================================
322
+ // Complete OAuth 2.0 with PKCE implementation for bypass via Gemini CLI
323
+ // identification. Production-ready, only node:* builtins + global fetch.
324
+ //
325
+ // Former oauth.ts header notes (preserved):
326
+ // - Base: oauth.ts v2.0.0 (full PKCE flow, WSL/SSH detection, manual input fallback).
327
+ // - Ported uniques from oauth(2).ts (the 2.0.0 lineage): extra scopes (openid,
328
+ // cloudcode, cloudaicompanion), CLOUDCODE_ORIGIN, SUPPORTED_MODELS_2026 entries
329
+ // (unprefixed claude models folded into MODELS_2026), StartOAuthFlowOptions /
330
+ // startOAuthFlow (injectable), refreshAndPreserve, invalid_grant
331
+ // re-authentication error, robust error wrapping with cause and non-JSON body
332
+ // snippet rejection, callback scope capture, multi-path callback server
333
+ // (/callback, /, /oauth/callback), ANTIGRAVITY_USER_AGENT.
334
+ // - Conflict resolution: client secret kept as GOCSPX-4uHgMPm...lXFsxl (matches
335
+ // package.json oauthClientSecretRef); alternative secret exported as
336
+ // CLIENT_SECRET_ALTERNATIVE so nothing is lost.
337
+ //
338
+ // v2.1.14 renames in this section (collision policy - the bare names keep the
339
+ // Antigravity meanings of the original auth.ts, see Section D):
340
+ // CLIENT_ID -> GEMINI_OAUTH_CLIENT_ID
341
+ // CLIENT_SECRET -> GEMINI_OAUTH_CLIENT_SECRET
342
+ // CLIENT_SECRET_ALTERNATIVE -> GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE
343
+ // SCOPES -> GEMINI_OAUTH_SCOPES
344
+ // ENDPOINTS -> CLOUDCODE_ENDPOINTS
345
+ // =============================================================================
346
+
347
+ // =============================================================================
348
+ // CONSTANTS - REQUIRED DATA (DO NOT ALTER PRIMARY CLIENT CREDENTIALS)
349
+ // =============================================================================
350
+
351
+ /**
352
+ * OAuth Client Credentials - Google Cloud SDK / Gemini CLI masquerade.
353
+ * v2.1.16 single-owner fix: the raw client pair is imported from constants.js
354
+ * (the raw-value owner); this module keeps only the historical names as
355
+ * aliases plus the alternative-secret decoy (defined nowhere else).
356
+ */
357
+ import {
358
+ GEMINI_CLI_OAUTH_CLIENT_ID as GEMINI_CLIENT_ID_RAW,
359
+ GEMINI_CLI_OAUTH_CLIENT_SECRET as GEMINI_CLIENT_SECRET_RAW,
360
+ } from "./constants.js";
361
+
362
+ export const GEMINI_OAUTH_CLIENT_ID: string = GEMINI_CLIENT_ID_RAW;
363
+
364
+ /**
365
+ * Primary client secret, paired with {@link GEMINI_OAUTH_CLIENT_ID} above.
366
+ * v2.1.16: alias of constants.GEMINI_CLI_OAUTH_CLIENT_SECRET.
367
+ */
368
+ export const GEMINI_OAUTH_CLIENT_SECRET: string = GEMINI_CLIENT_SECRET_RAW;
369
+
370
+ /**
371
+ * Alternative public client secret found in oauth(2).ts
372
+ * (GEMINI_OAUTH_CLIENT_SECRET there). Preserved under an alias so no
373
+ * credential variant is lost; not used by default.
374
+ * v2.1.14 rename: CLIENT_SECRET_ALTERNATIVE -> GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE.
375
+ */
376
+ export const GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE = ["GOCSPX", "-4uHgMPm", "-1o7Sk-geV6", "Cu5cWa_kRl"].join("");
377
+
378
+ /**
379
+ * Compatibility alias for the bare name used by oauth(2).ts / former oauth.ts:
380
+ * CLIENT_SECRET_ALTERNATIVE survives with its exact original value (the
381
+ * alternative secret). Note: per the v2.1.14 canonical naming,
382
+ * GEMINI_OAUTH_CLIENT_SECRET above points at the PRIMARY gemini secret.
383
+ */
384
+ export const CLIENT_SECRET_ALTERNATIVE = GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE;
385
+
386
+ /**
387
+ * Required scopes for Cloud Code + Userinfo + Antigravity.
388
+ * Merged: adds openid, cloudcode and cloudaicompanion (from
389
+ * oauth(2).ts GOOGLE_OAUTH_SCOPES) on top of the base set.
390
+ * v2.1.14 rename: SCOPES -> GEMINI_OAUTH_SCOPES (the bare SCOPES name keeps
391
+ * the Antigravity scope string of the original auth.ts, Section D).
392
+ */
393
+ export const GEMINI_OAUTH_SCOPES = [
394
+ "openid",
395
+ "https://www.googleapis.com/auth/cloud-platform",
396
+ "https://www.googleapis.com/auth/userinfo.email",
397
+ "https://www.googleapis.com/auth/userinfo.profile",
398
+ "https://www.googleapis.com/auth/cloudcode",
399
+ "https://www.googleapis.com/auth/cloudaicompanion",
400
+ ] as const;
401
+
402
+ /**
403
+ * Space-joined scope string alias (oauth(2).ts name preserved).
404
+ */
405
+ export const GOOGLE_OAUTH_SCOPES = GEMINI_OAUTH_SCOPES.join(" ");
406
+
407
+ /**
408
+ * OAuth 2.0 Google endpoints.
409
+ * v2.1.16 single-owner fix: alias of constants.OAUTH_AUTH_URL.
410
+ */
411
+ export const OAUTH_AUTHORIZE_URL = OAUTH_AUTH_URL;
412
+ // v2.1.15 Phase C: OAUTH_TOKEN_URL and USERINFO_URL moved to constants.js
413
+ // (raw value owner) — imported at the top of this file.
414
+
415
+ /** Endpoint aliases (oauth(2).ts names preserved). */
416
+ export const GOOGLE_AUTH_URL = OAUTH_AUTHORIZE_URL;
417
+ export const GOOGLE_TOKEN_URL = OAUTH_TOKEN_URL;
418
+ export const GOOGLE_USERINFO_URL = USERINFO_URL;
419
+
420
+ /**
421
+ * Cloud Code Assist endpoints (Antigravity bypass).
422
+ */
423
+ // v2.1.15 Phase B: CLOUDCODE_BASE moved to constants.js (raw value owner).
424
+ /** Alias (oauth(2).ts name preserved). */
425
+ export const CLOUDCODE_API_BASE = CLOUDCODE_BASE;
426
+ /**
427
+ * Origin required by some Cloud Code request headers.
428
+ * Ported from oauth(2).ts.
429
+ */
430
+ export const CLOUDCODE_ORIGIN = "https://cloud.google.com";
431
+
432
+ // v2.1.14 rename: former oauth.ts ENDPOINTS object -> CLOUDCODE_ENDPOINTS
433
+ // (the bare ENDPOINTS name keeps the former auth.ts base-URL array, Section D).
434
+ // v2.1.15 Phase B: CLOUDCODE_ENDPOINTS moved to constants.js (raw value owner).
435
+
436
+ export const SIGN_IN_SUCCESS_URL = "https://developers.google.com/gemini-code-assist/auth_success_gemini";
437
+ export const SIGN_IN_FAILURE_URL = "https://developers.google.com/gemini-code-assist/auth_failure_gemini";
438
+ export const HTTP_REDIRECT = 301;
439
+ // v2.1.15 Phase C: GEMINI_CLI_OAUTH_SCOPE (the 3-scope Gemini CLI set) is
440
+ // byte-identical to constants.GEMINI_CLI_SCOPES — imported from the owner.
441
+
442
+ export function getAvailablePort(): Promise<number> {
443
+ return new Promise((resolve, reject) => {
444
+ let port = 0;
445
+ try {
446
+ const portStr = process.env.OAUTH_CALLBACK_PORT;
447
+ if (portStr) {
448
+ port = parseInt(portStr, 10);
449
+ if (isNaN(port) || port <= 0 || port > 65535)
450
+ return reject(
451
+ new Error(
452
+ "Invalid value for OAUTH_CALLBACK_PORT (expected an integer between 1 and 65535); the raw value is intentionally not echoed to avoid leaking environment contents into logs",
453
+ ),
454
+ );
455
+ return resolve(port);
456
+ }
457
+ const server = net.createServer();
458
+ server.listen(0, () => {
459
+ const address = server.address();
460
+ if (address && typeof address === "object") port = (address as any).port;
461
+ });
462
+ server.on("listening", () => {
463
+ server.close();
464
+ (server as any).unref?.();
465
+ });
466
+ server.on("error", (e) => reject(e));
467
+ server.on("close", () => resolve(port));
468
+ } catch (e) {
469
+ reject(e);
470
+ }
471
+ });
472
+ }
473
+
474
+ /**
475
+ * Project fallback when no project is linked in Code Assist.
476
+ */
477
+ // v2.1.15 Phase B: PROJECT_FALLBACK moved to constants.js (raw value owner).
478
+
479
+ /**
480
+ * Available models 2026 - Antigravity + Gemini.
481
+ * Merged: unprefixed claude-opus-4-6-thinking and claude-sonnet-4-6 from
482
+ * oauth(2).ts SUPPORTED_MODELS_2026 are folded in here (all other entries
483
+ * were already covered).
484
+ */
485
+ // v2.1.15 Phase A: MODELS_2026 (this module's 13-id supported list = the
486
+ // legacy bypass list plus the two bare claude ids folded in from oauth(2).ts)
487
+ // and the SupportedModel2026 union moved to models.ts
488
+ // (SUPPORTED_MODELS_2026 / SupportedModel2026) — imported and re-exported
489
+ // under the historical names so both entry points stay valid.
490
+ import { SUPPORTED_MODELS_2026 } from "./models.js";
491
+ // v2.1.15 Phase B: generic retry predicate from core.js; identity UA builders
492
+ // from fingerprint.js; raw shared values from constants.js.
493
+ import { isRetryable, fetchWithTimeout } from "@wenathlan/devthink/core";
494
+ import { atomicWrite, cfgDir } from "@wenathlan/devthink/config";
495
+ import { apiClient, buildGeminiUserAgent, ua, X_GOOG_API_CLIENT_GEMINI_CLI } from "./fingerprint.js";
496
+ import {
497
+ ANTIGRAVITY_CLI_VERSION_POOL,
498
+ ANTIGRAVITY_USER_AGENT,
499
+ CLIENT_METADATA_STRING,
500
+ CLOUDCODE_BASE,
501
+ CLOUDCODE_ENDPOINTS,
502
+ GEMINI_CLI_SCOPES,
503
+ GEMINI_CLI_SCOPES_JOINED as GEMINI_CLI_OAUTH_SCOPE_STR,
504
+ OAUTH_AUTH_URL,
505
+ OAUTH_TOKEN_URL,
506
+ OAUTH_USERINFO_URL as USERINFO_URL,
507
+ PROJECT_FALLBACK,
508
+ } from "./constants.js";
509
+ import type { SupportedModel2026 } from "./models.js";
510
+ export { SUPPORTED_MODELS_2026 };
511
+ export { SUPPORTED_MODELS_2026 as OAUTH_MODELS_2026 };
512
+ export type { SupportedModel2026 };
513
+
514
+ /**
515
+ * Updated User-Agent of the 2.0.0 lineage (GPN:GeminiCLI style).
516
+ * Ported from oauth(2).ts; exported for callers that need to present it,
517
+ * while the default bypass headers below remain unchanged.
518
+ */
519
+ // v2.1.15 Phase B: ANTIGRAVITY_USER_AGENT moved to constants.js (raw value owner).
520
+
521
+ /**
522
+ * Gemini CLI identification headers for bypass.
523
+ * User-Agent varies per platform; base values below.
524
+ * v2.1.16 single-owner fix: every part is imported from its owner — the
525
+ * default UA model id from models.js (model identification owner), the
526
+ * client-metadata string from constants.js and the gl-node snapshot from
527
+ * fingerprint.js (identity masquerade owner).
528
+ */
529
+ import { UA_DEFAULT_MODEL } from "./models.js";
530
+ export const GEMINI_UA_BASE = {
531
+ cliVersion: "0.57.0",
532
+ defaultModel: UA_DEFAULT_MODEL,
533
+ googleApiClient: "google-api-nodejs-client/9.15.1",
534
+ xGoogApiClient: X_GOOG_API_CLIENT_GEMINI_CLI,
535
+ clientMetadata: CLIENT_METADATA_STRING,
536
+ } as const;
537
+
538
+ // =============================================================================
539
+ // SECTION C - SHARED OAUTH PRIMITIVES, FULL-FEATURED (former oauth.ts)
540
+ // =============================================================================
541
+ // Types, base64url utils, platform detection, Gemini header builders, PKCE
542
+ // generation, auth URL builder, cross-platform browser opener, manual input
543
+ // fallback, multi-path callback server, token exchange / refresh / userinfo.
544
+ // v2.1.14 renames: openBrowser -> openBrowserAsync (the bare openBrowser name
545
+ // keeps the former auth.ts void implementation in Section D); the private
546
+ // escapeHtml helper of the former oauth.ts -> escapeHtmlOauth (the former
547
+ // auth.ts escapeHtml stays in Section D).
548
+ // =============================================================================
549
+
550
+ // =============================================================================
551
+ // TYPES
552
+ // =============================================================================
553
+
554
+ export interface PKCEPair {
555
+ /** Verifier: random 43-128 char string for the proof */
556
+ verifier: string;
557
+ /** Challenge: BASE64URL(SHA256(verifier)) */
558
+ challenge: string;
559
+ /** Method is always S256 */
560
+ method: "S256";
561
+ }
562
+
563
+ export interface TokenResponse {
564
+ access_token: string;
565
+ refresh_token?: string;
566
+ id_token?: string;
567
+ token_type: string;
568
+ expires_in: number;
569
+ scope?: string;
570
+ /** Computed locally */
571
+ expires_at: number;
572
+ }
573
+
574
+ export interface UserInfo {
575
+ id: string;
576
+ email: string;
577
+ verified_email: boolean;
578
+ name: string;
579
+ given_name?: string;
580
+ family_name?: string;
581
+ picture?: string;
582
+ locale?: string;
583
+ hd?: string;
584
+ }
585
+
586
+ /**
587
+ * Result returned by the local callback server.
588
+ * Ported from oauth(2).ts: captures the granted `scope`.
589
+ */
590
+ export interface OAuthCallbackResult {
591
+ code: string;
592
+ state?: string | undefined;
593
+ scope?: string | undefined;
594
+ }
595
+
596
+ /**
597
+ * Complete OAuth flow result (oauth(2).ts shape, used by startOAuthFlow).
598
+ */
599
+ export interface OAuthResult {
600
+ tokens: TokenResponse;
601
+ userInfo: UserInfo;
602
+ state: string;
603
+ }
604
+
605
+ export interface OAuthServerResult {
606
+ server: http.Server;
607
+ /** Full callback URL (http://127.0.0.1:PORT/oauth-callback) */
608
+ callbackUrl: string;
609
+ /** Actually bound port */
610
+ port: number;
611
+ /** Promise resolving with the authorization code only */
612
+ waitForCode: () => Promise<string>;
613
+ /**
614
+ * Promise resolving with code + state + captured scope.
615
+ * Ported from oauth(2).ts.
616
+ */
617
+ waitForCallback: () => Promise<OAuthCallbackResult>;
618
+ /** Shuts the server down */
619
+ close: () => Promise<void>;
620
+ }
621
+
622
+ export interface AuthOptions {
623
+ /** When true, does not try to open the browser automatically */
624
+ noBrowser?: boolean;
625
+ /** Timeout waiting for the callback before manual fallback (ms). Default 30000 */
626
+ callbackTimeoutMs?: number;
627
+ /** Custom callback path; default /oauth-callback */
628
+ callbackPath?: string;
629
+ /** Log callback - allows integration with the opencode logger */
630
+ onLog?: (level: "info" | "warn" | "error", msg: string) => void;
631
+ /** OAuth client identity bundle (see antigravity-cli.ts). When provided the
632
+ * flow uses its clientId/clientSecret/scopes/PKCE policy instead of the
633
+ * legacy Gemini CLI web-flow defaults. */
634
+ identity?: {
635
+ identity: string;
636
+ clientId: string;
637
+ clientSecret: string;
638
+ scopesStr: string;
639
+ usesPKCE: boolean;
640
+ userAgent?: string;
641
+ appLabel?: string;
642
+ };
643
+ }
644
+
645
+ /**
646
+ * Injectable options for the direct startOAuthFlow orchestrator.
647
+ * Ported from oauth(2).ts: every external dependency can be injected for tests.
648
+ */
649
+ export interface StartOAuthFlowOptions {
650
+ /** Callback path - default /callback */
651
+ callbackPath?: string;
652
+ /** Total timeout in ms - default 5 minutes */
653
+ timeoutMs?: number;
654
+ /** Scopes - default GOOGLE_OAUTH_SCOPES */
655
+ scopes?: string;
656
+ /** ClientId - default GEMINI_OAUTH_CLIENT_ID (former oauth.ts CLIENT_ID) */
657
+ clientId?: string;
658
+ /** ClientSecret - default GEMINI_OAUTH_CLIENT_SECRET (former oauth.ts CLIENT_SECRET) */
659
+ clientSecret?: string;
660
+ /** Browser opener function - injectable for tests */
661
+ openBrowserFn?: (url: string) => void;
662
+ }
663
+
664
+ // =============================================================================
665
+ // UTILS - BASE64URL & PLATFORM DETECTION
666
+ // =============================================================================
667
+
668
+ /**
669
+ * Encodes Buffer/string to base64url (RFC 7636 - no padding, -_ instead of +/)
670
+ */
671
+ function base64urlEncode(input: Buffer | string): string {
672
+ const buf = typeof input === "string" ? Buffer.from(input) : input;
673
+ const b64 = buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_");
674
+ // v2.1.16 security (CodeQL js/polynomial-redos): the former `/=+$/g`
675
+ // trailing-padding strip is quadratic on adversarial input — strip the
676
+ // padding with a linear back-scan over '=' (0x3D) instead.
677
+ let end = b64.length;
678
+ while (end > 0 && b64.charCodeAt(end - 1) === 0x3d) end--;
679
+ return end === b64.length ? b64 : b64.slice(0, end);
680
+ }
681
+
682
+ /**
683
+ * Decodes base64url to Buffer
684
+ */
685
+ function base64urlDecode(input: string): Buffer {
686
+ let b64 = input.replace(/-/g, "+").replace(/_/g, "/");
687
+ const pad = b64.length % 4;
688
+ if (pad) b64 += "=".repeat(4 - pad);
689
+ return Buffer.from(b64, "base64");
690
+ }
691
+
692
+ /**
693
+ * Detects whether running inside WSL
694
+ */
695
+ export function isWSL(): boolean {
696
+ try {
697
+ if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) return true;
698
+ // Checks /proc/version for "microsoft" or "WSL" - best effort.
699
+ // Avoids fs import; uses os.release()
700
+ const release = os.release().toLowerCase();
701
+ if (release.includes("microsoft") || release.includes("wsl")) return true;
702
+ return false;
703
+ } catch {
704
+ return false;
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Detects an SSH session (no local display)
710
+ */
711
+ export function isSSH(): boolean {
712
+ return !!(process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION);
713
+ }
714
+
715
+ /**
716
+ * Detects whether a graphical display is available
717
+ */
718
+ export function hasDisplay(): boolean {
719
+ if (process.platform === "win32") return true;
720
+ if (process.platform === "darwin") return true;
721
+ // Linux: checks DISPLAY or WAYLAND_DISPLAY
722
+ return !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
723
+ }
724
+
725
+ /**
726
+ * Builds platform-specific User-Agent - Gemini CLI masquerade.
727
+ * Format: GeminiCLI/<version>/<model> (<platform>; <arch>; GitHub) <google-api-client>
728
+ */
729
+ // v2.1.15 Phase B: buildGeminiUserAgent moved to fingerprint.js (identity masquerade owner).
730
+
731
+ /**
732
+ * Returns the required bypass headers object with all identification headers.
733
+ */
734
+ export function getGeminiHeaders(): Record<string, string> {
735
+ return {
736
+ "User-Agent": buildGeminiUserAgent(),
737
+ "X-Goog-Api-Client": GEMINI_UA_BASE.xGoogApiClient,
738
+ "Client-Metadata": GEMINI_UA_BASE.clientMetadata,
739
+ };
740
+ }
741
+
742
+ // =============================================================================
743
+ // PKCE - RFC 7636
744
+ // =============================================================================
745
+
746
+ /**
747
+ * Generates a PKCE pair (verifier + challenge) per RFC 7636.
748
+ * - verifier: 32 bytes random -> base64url = 43 chars (within 43-128)
749
+ * - challenge: BASE64URL(SHA256(verifier))
750
+ *
751
+ * @returns {PKCEPair} verifier/challenge pair
752
+ * @example
753
+ * const { verifier, challenge } = generatePKCE();
754
+ */
755
+ export function generatePKCE(): PKCEPair {
756
+ // 32 bytes = 43 chars base64url, 64 bytes = 86 chars - we pick 64 for extra strength
757
+ const verifierBytes = crypto.randomBytes(64);
758
+ const verifier = base64urlEncode(verifierBytes);
759
+ // Challenge = BASE64URL(SHA256(verifier ASCII))
760
+ const challengeHash = crypto.createHash("sha256").update(verifier).digest();
761
+ const challenge = base64urlEncode(challengeHash);
762
+
763
+ return {
764
+ verifier,
765
+ challenge,
766
+ method: "S256",
767
+ };
768
+ }
769
+
770
+ // =============================================================================
771
+ // OAUTH URL BUILDER
772
+ // =============================================================================
773
+
774
+ /**
775
+ * Builds the OAuth 2.0 + PKCE authorization URL.
776
+ *
777
+ * @param pkce - Generated PKCE pair
778
+ * @param redirectUri - Redirect URI (e.g. http://127.0.0.1:PORT/oauth-callback)
779
+ * @param opts - Extra options (custom state, login_hint, etc.)
780
+ * @returns Full URL to redirect the user to
781
+ */
782
+ export function buildAuthUrl(
783
+ pkce: PKCEPair | null,
784
+ redirectUri: string,
785
+ opts?: {
786
+ state?: string;
787
+ loginHint?: string;
788
+ prompt?: "consent" | "select_account" | "none";
789
+ accessType?: "online" | "offline";
790
+ scopes?: string;
791
+ clientId?: string;
792
+ },
793
+ ): string {
794
+ const state = opts?.state ?? base64urlEncode(crypto.randomBytes(32));
795
+
796
+ const params = new URLSearchParams({
797
+ client_id: opts?.clientId ?? GEMINI_OAUTH_CLIENT_ID,
798
+ redirect_uri: redirectUri,
799
+ response_type: "code",
800
+ scope: opts?.scopes ?? GEMINI_OAUTH_SCOPES.join(" "),
801
+ state,
802
+ access_type: opts?.accessType ?? "offline",
803
+ });
804
+
805
+ // PKCE is optional: the Gemini CLI web flow does NOT use it (state-only).
806
+ if (pkce) {
807
+ params.set("code_challenge", pkce.challenge);
808
+ params.set("code_challenge_method", pkce.method);
809
+ }
810
+
811
+ // prompt is only sent when explicitly requested (Gemini CLI parity).
812
+ if (opts?.prompt) {
813
+ params.set("prompt", opts.prompt);
814
+ }
815
+
816
+ if (opts?.loginHint) {
817
+ params.set("login_hint", opts.loginHint);
818
+ }
819
+
820
+ return `${OAUTH_AUTHORIZE_URL}?${params.toString()}`;
821
+ }
822
+
823
+ // =============================================================================
824
+ // BROWSER OPENER - CROSS PLATFORM + WSL
825
+ // =============================================================================
826
+
827
+ /**
828
+ * Tries to open the URL in the default browser - cross-platform.
829
+ * Supports: darwin (open), win32 (start via cmd), linux (xdg-open), WSL (wslview/powershell)
830
+ * v2.1.14 rename: openBrowser -> openBrowserAsync (the bare openBrowser name
831
+ * keeps the former auth.ts void implementation, Section D).
832
+ *
833
+ * @param url - URL to open
834
+ * @returns true if the command was spawned, false if it failed
835
+ */
836
+ export async function openBrowserAsync(url: string): Promise<boolean> {
837
+ const platform = os.platform();
838
+
839
+ const trySpawn = (cmd: string, args: string[], env?: NodeJS.ProcessEnv): Promise<boolean> => {
840
+ return new Promise((resolve) => {
841
+ try {
842
+ const child = spawn(cmd, args, {
843
+ stdio: "ignore",
844
+ detached: true,
845
+ shell: false,
846
+ ...(env ? { env } : {}),
847
+ });
848
+ child.on("error", () => resolve(false));
849
+ child.on("spawn", () => {
850
+ child.unref();
851
+ resolve(true);
852
+ });
853
+ // Fallback if spawn emits nothing within 1s
854
+ setTimeout(() => resolve(true), 1000);
855
+ } catch {
856
+ resolve(false);
857
+ }
858
+ });
859
+ };
860
+
861
+ /**
862
+ * v2.1.16 security (CodeQL js/shell-command-constructed-from-input):
863
+ * launches PowerShell to open the URL WITHOUT ever embedding the URL in
864
+ * the command string — the static command reads it back from
865
+ * `$env:MAENE_OPEN_URL`, so no shell metacharacter inside the URL can
866
+ * alter what PowerShell executes. From WSL the variable is forwarded
867
+ * through WSLENV (the `/w` flag marks the WSL -> Win32 direction only);
868
+ * on native win32 the environment passes through directly.
869
+ */
870
+ const tryPowerShellOpen = (fromWSL: boolean): Promise<boolean> => {
871
+ const env: NodeJS.ProcessEnv = { ...process.env, MAENE_OPEN_URL: url };
872
+ if (fromWSL) {
873
+ env.WSLENV = `${env.WSLENV ? `${env.WSLENV}:` : ""}MAENE_OPEN_URL/w`;
874
+ }
875
+ return trySpawn("powershell.exe", ["-NoProfile", "-Command", "Start-Process -FilePath $env:MAENE_OPEN_URL"], env);
876
+ };
877
+
878
+ // WSL: tries wslview first, then powershell.exe start
879
+ if (isWSL()) {
880
+ // wslview (wslu)
881
+ if (await trySpawn("wslview", [url])) return true;
882
+ // powershell.exe — URL travels through the environment, never the command
883
+ if (await tryPowerShellOpen(true)) return true;
884
+ }
885
+
886
+ if (platform === "darwin") {
887
+ return trySpawn("open", [url]);
888
+ }
889
+
890
+ if (platform === "win32") {
891
+ // rundll32 bypasses cmd.exe parsing entirely - "&" inside the URL survives.
892
+ if (await trySpawn("rundll32", ["url.dll,FileProtocolHandler", url])) return true;
893
+ // Fallback: PowerShell with the URL forwarded through the environment
894
+ // (the former `cmd /c start "<url>"` form embedded the URL in the
895
+ // command line — flagged as shell-command-constructed-from-input).
896
+ if (await tryPowerShellOpen(false)) return true;
897
+ return false;
898
+ }
899
+
900
+ // Linux / fallback: xdg-open
901
+ if (await trySpawn("xdg-open", [url])) return true;
902
+ // Additional Linux attempts
903
+ if (await trySpawn("gio", ["open", url])) return true;
904
+ if (await trySpawn("gnome-open", [url])) return true;
905
+ if (await trySpawn("kde-open", [url])) return true;
906
+
907
+ return false;
908
+ }
909
+
910
+ // =============================================================================
911
+ // MANUAL INPUT FALLBACK
912
+ // =============================================================================
913
+
914
+ /**
915
+ * Asks the user for manual input via stdin.
916
+ * Supports pasting the full URL or just the code.
917
+ *
918
+ * @param promptMsg - Message displayed
919
+ * @returns extracted code
920
+ */
921
+ function askManualInput(promptMsg: string): Promise<string> {
922
+ return new Promise((resolve, reject) => {
923
+ const rl = readline.createInterface({
924
+ input: process.stdin,
925
+ output: process.stdout,
926
+ });
927
+
928
+ rl.question(promptMsg, (answer) => {
929
+ rl.close();
930
+ const trimmed = answer.trim();
931
+ if (!trimmed) {
932
+ reject(new Error("Empty input received. Authentication cancelled."));
933
+ return;
934
+ }
935
+
936
+ // User may paste the full URL - extract the 'code' param
937
+ try {
938
+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
939
+ const parsed = new URL(trimmed);
940
+ const codeFromUrl = parsed.searchParams.get("code");
941
+ if (codeFromUrl) {
942
+ resolve(codeFromUrl);
943
+ return;
944
+ }
945
+ // If the URL contains a fragment (#), try extracting from it too
946
+ if (parsed.hash) {
947
+ const hashParams = new URLSearchParams(parsed.hash.replace(/^#/, ""));
948
+ const codeFromHash = hashParams.get("code");
949
+ if (codeFromHash) {
950
+ resolve(codeFromHash);
951
+ return;
952
+ }
953
+ }
954
+ }
955
+ } catch {
956
+ // Not a valid URL - treat as direct code
957
+ }
958
+
959
+ // Treat as direct code (may contain pasted "code=XXXX")
960
+ const match = trimmed.match(/(?:code=)?([A-Za-z0-9\-_]+)/);
961
+ if (match) {
962
+ // If the input was "code=XYZ", take XYZ; if it was just XYZ, take the match
963
+ const maybeCode = trimmed.includes("code=") ? match[1]! : trimmed.split(/[&\s]/)[0]!;
964
+ resolve(maybeCode.trim());
965
+ } else {
966
+ resolve(trimmed);
967
+ }
968
+ });
969
+
970
+ // Handle Ctrl+C
971
+ rl.on("SIGINT", () => {
972
+ rl.close();
973
+ reject(new Error("Authentication interrupted by the user (SIGINT)"));
974
+ });
975
+ });
976
+ }
977
+
978
+ // =============================================================================
979
+ // OAUTH LOCAL SERVER
980
+ // =============================================================================
981
+
982
+ /**
983
+ * Creates a local HTTP server on 127.0.0.1:0 (random port) to receive the OAuth callback.
984
+ *
985
+ * Multi-path support (ported from oauth(2).ts): accepts the configured
986
+ * callbackPath, plus /oauth/callback, plus "/" when the request carries code /
987
+ * error query parameters. A bare "/" GET without OAuth params still serves the
988
+ * healthcheck info text (conflict resolved in favor of both behaviors).
989
+ *
990
+ * Validates state if provided, extracts code and the granted `scope`.
991
+ *
992
+ * @param options - options: callbackPath, timeout, logger
993
+ * @returns OAuthServerResult with server, callbackUrl, waitForCode, waitForCallback, close
994
+ */
995
+ export function createOAuthServer(options?: {
996
+ callbackPath?: string;
997
+ onLog?: AuthOptions["onLog"];
998
+ expectedState?: string;
999
+ }): OAuthServerResult {
1000
+ const callbackPath = options?.callbackPath ?? "/oauth2callback";
1001
+ const onLog = options?.onLog ?? (() => {});
1002
+ const expectedState = options?.expectedState;
1003
+
1004
+ let resolveCb!: (result: OAuthCallbackResult) => void;
1005
+ let rejectCode!: (err: Error) => void;
1006
+ let codeSettled = false;
1007
+
1008
+ const callbackPromise = new Promise<OAuthCallbackResult>((resolve, reject) => {
1009
+ resolveCb = (r: OAuthCallbackResult) => {
1010
+ if (!codeSettled) {
1011
+ codeSettled = true;
1012
+ resolve(r);
1013
+ }
1014
+ };
1015
+ rejectCode = (e: Error) => {
1016
+ if (!codeSettled) {
1017
+ codeSettled = true;
1018
+ reject(e);
1019
+ }
1020
+ };
1021
+ });
1022
+
1023
+ const server = http.createServer((req, res) => {
1024
+ try {
1025
+ onLog("info", `[callback-server] ${req.method} ${req.url}`);
1026
+ const rawUrl = req.url ?? "/";
1027
+ const isCallback = rawUrl.indexOf(callbackPath) !== -1 || rawUrl.indexOf("/oauth2callback") !== -1;
1028
+ if (!isCallback) {
1029
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
1030
+ res.end("devthink provider OAuth callback server running. Awaiting " + callbackPath);
1031
+ return;
1032
+ }
1033
+ const qs = new url.URL(rawUrl, "http://127.0.0.1:3000").searchParams;
1034
+ const code = qs.get("code");
1035
+ const state = qs.get("state") ?? undefined;
1036
+ const scope = qs.get("scope") ?? undefined;
1037
+ const error = qs.get("error");
1038
+ const errorDesc = qs.get("error_description");
1039
+ if (error) {
1040
+ onLog("error", `OAuth callback returned error: ${error} - ${errorDesc ?? ""}`);
1041
+ res.writeHead(HTTP_REDIRECT, { Location: SIGN_IN_FAILURE_URL });
1042
+ res.end();
1043
+ rejectCode(new Error(`Google OAuth error: ${error}. ${errorDesc ?? "No additional details"}`));
1044
+ try {
1045
+ (server as any).close?.();
1046
+ } catch {
1047
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1048
+ }
1049
+ return;
1050
+ }
1051
+ if (!code) {
1052
+ onLog("warn", "Callback hit without code - still waiting for real redirect.");
1053
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1054
+ res.end(
1055
+ `<!doctype html><html><head><meta charset="utf-8"/><title>devthink</title></head><body style="font-family:system-ui;background:#0a2a12;color:#e5e7eb;display:flex;align-items:center;justify-content:center;min-height:100vh"><div style="text-align:center"><h1>Waiting for authorization...</h1><p>Complete the login in the Google window.</p><p>Return to the terminal and try again.<br/>devthink \u2022 Gemini CLI bypass</p></div></body></html>`,
1056
+ );
1057
+ return;
1058
+ }
1059
+ if (expectedState && state !== expectedState) {
1060
+ onLog("error", `State mismatch. Expected ${expectedState}, received ${state}`);
1061
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
1062
+ res.end("State mismatch. Possible CSRF attack");
1063
+ rejectCode(new Error(`OAuth state mismatch. Possible CSRF attack or browser session issue.`));
1064
+ try {
1065
+ (server as any).close?.();
1066
+ } catch {
1067
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1068
+ }
1069
+ return;
1070
+ }
1071
+ onLog("info", `Authorization code received (${code.substring(0, 10)}...)`);
1072
+ res.writeHead(HTTP_REDIRECT, { Location: SIGN_IN_SUCCESS_URL });
1073
+ res.end();
1074
+ resolveCb({ code, state, scope });
1075
+ try {
1076
+ (server as any).close?.();
1077
+ } catch {
1078
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1079
+ }
1080
+ } catch (err) {
1081
+ onLog("error", `Error in OAuth server handler: ${(err as Error).message}`);
1082
+ try {
1083
+ res.writeHead(500, { "Content-Type": "text/plain" });
1084
+ res.end("Internal server error");
1085
+ } catch {
1086
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1087
+ }
1088
+ rejectCode(err as Error);
1089
+ try {
1090
+ (server as any).close?.();
1091
+ } catch {
1092
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1093
+ }
1094
+ }
1095
+ });
1096
+
1097
+ server.on("error", (err) => {
1098
+ onLog("error", `OAuth server error: ${err.message}`);
1099
+ rejectCode(err);
1100
+ });
1101
+
1102
+ let callbackUrl = "";
1103
+ let port = 0;
1104
+
1105
+ const envPort = Number(process.env.OAUTH_CALLBACK_PORT ?? "");
1106
+ const preferredPort = Number.isFinite(envPort) && envPort > 0 ? envPort : 0;
1107
+
1108
+ const listeningPromise = new Promise<{ port: number; url: string }>((resolve, reject) => {
1109
+ const host = process.env.OAUTH_CALLBACK_HOST ?? "127.0.0.1";
1110
+ server.listen(preferredPort, host, () => {
1111
+ const addr = server.address();
1112
+ if (addr && typeof addr === "object") {
1113
+ port = addr.port;
1114
+ callbackUrl = `http://127.0.0.1:${port}${callbackPath}`;
1115
+ resolve({ port, url: callbackUrl });
1116
+ } else {
1117
+ reject(new Error("Failed to obtain OAuth server address"));
1118
+ }
1119
+ });
1120
+ server.on("error", reject);
1121
+ });
1122
+
1123
+ return {
1124
+ server,
1125
+ get callbackUrl() {
1126
+ return callbackUrl;
1127
+ },
1128
+ get port() {
1129
+ return port;
1130
+ },
1131
+ waitForCode: async () => {
1132
+ if (!callbackUrl) {
1133
+ await listeningPromise;
1134
+ }
1135
+ return (await callbackPromise).code;
1136
+ },
1137
+ waitForCallback: async () => {
1138
+ if (!callbackUrl) {
1139
+ await listeningPromise;
1140
+ }
1141
+ return callbackPromise;
1142
+ },
1143
+ close: async () => {
1144
+ return new Promise<void>((resolve) => {
1145
+ server.close(() => resolve());
1146
+ setTimeout(() => {
1147
+ try {
1148
+ server.closeAllConnections?.();
1149
+ } catch {
1150
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1151
+ }
1152
+ resolve();
1153
+ }, 1000);
1154
+ });
1155
+ },
1156
+ };
1157
+ }
1158
+
1159
+ /**
1160
+ * Async helper version that already waits for the server to be listening and returns full info
1161
+ */
1162
+ export async function createOAuthServerAsync(opts?: {
1163
+ callbackPath?: string;
1164
+ onLog?: AuthOptions["onLog"];
1165
+ expectedState?: string;
1166
+ }): Promise<OAuthServerResult & { ready: true }> {
1167
+ const srv = createOAuthServer(opts);
1168
+ // Force listening
1169
+ await new Promise<void>((resolve, reject) => {
1170
+ // If already listening, server.address() already has the port; but we wait for a tick
1171
+ if (srv.port !== 0) {
1172
+ resolve();
1173
+ return;
1174
+ }
1175
+ srv.server.once("listening", () => resolve());
1176
+ srv.server.once("error", reject);
1177
+ // Edge case where listen was already called but the callback has not run yet
1178
+ setTimeout(() => {
1179
+ if (srv.port !== 0) resolve();
1180
+ }, 50);
1181
+ });
1182
+
1183
+ return { ...srv, ready: true as const };
1184
+ }
1185
+
1186
+ // v2.1.16 dead-code cleanup: getHtmlResponse + escapeHtmlOauth (the polished
1187
+ // callback HTML twins of the live inline responses inside createOAuthServer)
1188
+ // were fully dead — zero callers repo-wide — and were deleted.
1189
+
1190
+ // =============================================================================
1191
+ // TOKEN EXCHANGE & REFRESH
1192
+ // =============================================================================
1193
+
1194
+ /**
1195
+ * Exchanges the authorization code for tokens (access_token + refresh_token).
1196
+ * POST https://oauth2.googleapis.com/token
1197
+ *
1198
+ * Robust error wrapping ported from oauth(2).ts: network failures are wrapped
1199
+ * with `cause`, non-JSON bodies are rejected with a status + body snippet, and
1200
+ * a missing access_token is an explicit error.
1201
+ *
1202
+ * @param code - Received authorization code
1203
+ * @param codeVerifier - Original PKCE verifier
1204
+ * @param redirectUri - Same redirect_uri used in buildAuthUrl
1205
+ * @param options - Optional injected credentials (defaults to GEMINI_OAUTH_CLIENT_ID / GEMINI_OAUTH_CLIENT_SECRET)
1206
+ * @returns TokenResponse with computed expires_at
1207
+ */
1208
+ export async function exchangeCodeForTokens(
1209
+ code: string,
1210
+ codeVerifier: string | null,
1211
+ redirectUri: string,
1212
+ options?: { clientId?: string; clientSecret?: string },
1213
+ ): Promise<TokenResponse> {
1214
+ const clientId = options?.clientId ?? GEMINI_OAUTH_CLIENT_ID;
1215
+ const clientSecret = options?.clientSecret ?? GEMINI_OAUTH_CLIENT_SECRET;
1216
+
1217
+ const body = new URLSearchParams({
1218
+ client_id: clientId,
1219
+ client_secret: clientSecret,
1220
+ code,
1221
+ grant_type: "authorization_code",
1222
+ redirect_uri: redirectUri,
1223
+ });
1224
+
1225
+ // Only sent when PKCE was used in the authorization request.
1226
+ if (codeVerifier) {
1227
+ body.set("code_verifier", codeVerifier);
1228
+ }
1229
+
1230
+ let res: Response;
1231
+ try {
1232
+ res = await fetch(OAUTH_TOKEN_URL, {
1233
+ method: "POST",
1234
+ headers: {
1235
+ "Content-Type": "application/x-www-form-urlencoded",
1236
+ ...getGeminiHeaders(),
1237
+ },
1238
+ body: body.toString(),
1239
+ });
1240
+ } catch (err) {
1241
+ throw new Error(`Network failure while exchanging code for tokens: ${(err as Error).message}`, {
1242
+ cause: err,
1243
+ });
1244
+ }
1245
+
1246
+ const text = await res.text().catch(() => "");
1247
+ let json: any;
1248
+ try {
1249
+ json = JSON.parse(text);
1250
+ } catch {
1251
+ throw new Error(`Non-JSON token response (${res.status}): ${text.slice(0, 500)}`);
1252
+ }
1253
+
1254
+ if (!res.ok) {
1255
+ const detail = json?.error_description ?? json?.error ?? text;
1256
+ throw new Error(`exchangeCodeForTokens failed (${res.status}): ${detail || res.statusText}`);
1257
+ }
1258
+
1259
+ if (!json?.access_token) {
1260
+ throw new Error(`Token response without access_token: ${text.slice(0, 500)}`);
1261
+ }
1262
+
1263
+ return {
1264
+ ...json,
1265
+ expires_at: Date.now() + json.expires_in * 1000,
1266
+ };
1267
+ }
1268
+
1269
+ /**
1270
+ * Renews the access_token using a refresh_token.
1271
+ *
1272
+ * invalid_grant handling ported from oauth(2).ts: when Google answers with
1273
+ * error=invalid_grant an explicit "re-authentication necessary" error is
1274
+ * raised so callers can trigger a fresh login instead of retrying blindly.
1275
+ *
1276
+ * @param refreshToken - Valid refresh token
1277
+ * @param options - Optional injected credentials (defaults to GEMINI_OAUTH_CLIENT_ID / GEMINI_OAUTH_CLIENT_SECRET)
1278
+ * @returns New TokenResponse (may contain a rotated refresh_token; the previous
1279
+ * one is preserved when Google omits it)
1280
+ */
1281
+ export async function refreshAccessToken(
1282
+ refreshToken: string,
1283
+ options?: { clientId?: string; clientSecret?: string },
1284
+ ): Promise<TokenResponse> {
1285
+ const clientId = options?.clientId ?? GEMINI_OAUTH_CLIENT_ID;
1286
+ const clientSecret = options?.clientSecret ?? GEMINI_OAUTH_CLIENT_SECRET;
1287
+
1288
+ const body = new URLSearchParams({
1289
+ client_id: clientId,
1290
+ client_secret: clientSecret,
1291
+ refresh_token: refreshToken,
1292
+ grant_type: "refresh_token",
1293
+ });
1294
+
1295
+ let res: Response;
1296
+ try {
1297
+ res = await fetch(OAUTH_TOKEN_URL, {
1298
+ method: "POST",
1299
+ headers: {
1300
+ "Content-Type": "application/x-www-form-urlencoded",
1301
+ ...getGeminiHeaders(),
1302
+ },
1303
+ body: body.toString(),
1304
+ });
1305
+ } catch (err) {
1306
+ throw new Error(`Network failure while refreshing token: ${(err as Error).message}`, {
1307
+ cause: err,
1308
+ });
1309
+ }
1310
+
1311
+ const text = await res.text().catch(() => "");
1312
+ let json: any;
1313
+ try {
1314
+ json = JSON.parse(text);
1315
+ } catch {
1316
+ throw new Error(`Non-JSON refresh response (${res.status}): ${text.slice(0, 500)}`);
1317
+ }
1318
+
1319
+ if (!res.ok) {
1320
+ const detail = json?.error_description ?? json?.error ?? text;
1321
+ // Specific handling for expired refresh tokens - instruct re-login
1322
+ if (json?.error === "invalid_grant") {
1323
+ throw new Error(`Refresh token invalid/expired - re-authentication necessary: ${detail}`);
1324
+ }
1325
+ throw new Error(`refreshAccessToken failed (${res.status}): ${detail || res.statusText}`);
1326
+ }
1327
+
1328
+ // Google often does NOT return a new refresh_token on refresh - keep the original
1329
+ return {
1330
+ ...(json as Omit<TokenResponse, "expires_at">),
1331
+ refresh_token: (json as any).refresh_token ?? refreshToken,
1332
+ expires_at: Date.now() + (json.expires_in as number) * 1000,
1333
+ };
1334
+ }
1335
+
1336
+ /**
1337
+ * Helper ported from oauth(2).ts: refreshes tokens while preserving the old
1338
+ * refresh_token when Google omits a new one. Library-first pattern.
1339
+ *
1340
+ * @param oldTokens - Previously stored TokenResponse containing a refresh_token
1341
+ * @returns Refreshed TokenResponse guaranteed to carry a usable refresh_token
1342
+ */
1343
+ export async function refreshAndPreserve(oldTokens: TokenResponse): Promise<TokenResponse> {
1344
+ if (!oldTokens.refresh_token) {
1345
+ throw new Error("Previous token has no refresh_token - a new login is required");
1346
+ }
1347
+ const refreshed = await refreshAccessToken(oldTokens.refresh_token);
1348
+ return {
1349
+ ...refreshed,
1350
+ // Preserve the original refresh_token if the endpoint did not return a new one (Google behavior)
1351
+ refresh_token: refreshed.refresh_token ?? oldTokens.refresh_token,
1352
+ };
1353
+ }
1354
+
1355
+ /**
1356
+ * Checks whether a token is expired or about to expire (60s buffer)
1357
+ */
1358
+ export function isTokenExpired(token: TokenResponse, bufferMs = 60_000): boolean {
1359
+ return Date.now() + bufferMs >= token.expires_at;
1360
+ }
1361
+
1362
+ // =============================================================================
1363
+ // USERINFO
1364
+ // =============================================================================
1365
+
1366
+ /**
1367
+ * Retrieves information about the authenticated user.
1368
+ * GET https://www.googleapis.com/oauth2/v2/userinfo
1369
+ *
1370
+ * Robust error wrapping ported from oauth(2).ts: network failures wrapped with
1371
+ * `cause`; non-JSON bodies rejected with a status + body snippet.
1372
+ *
1373
+ * @param accessToken - Valid access token
1374
+ * @returns Normalized UserInfo
1375
+ */
1376
+ export async function getUserInfo(accessToken: string): Promise<UserInfo> {
1377
+ let res: Response;
1378
+ try {
1379
+ res = await fetch(USERINFO_URL, {
1380
+ method: "GET",
1381
+ headers: {
1382
+ Authorization: `Bearer ${accessToken}`,
1383
+ ...getGeminiHeaders(),
1384
+ Accept: "application/json",
1385
+ },
1386
+ });
1387
+ } catch (err) {
1388
+ throw new Error(`Network failure while fetching userinfo: ${(err as Error).message}`, {
1389
+ cause: err,
1390
+ });
1391
+ }
1392
+
1393
+ const text = await res.text().catch(() => "");
1394
+ let data: UserInfo;
1395
+ try {
1396
+ data = JSON.parse(text) as UserInfo;
1397
+ } catch {
1398
+ throw new Error(`Non-JSON userinfo response (${res.status}): ${text.slice(0, 500)}`);
1399
+ }
1400
+
1401
+ if (!res.ok) {
1402
+ throw new Error(
1403
+ `getUserInfo failed (${res.status}): ${(data as any)?.error_description ?? (data as any)?.error ?? (text || res.statusText)}`,
1404
+ );
1405
+ }
1406
+
1407
+ if (!data.email) {
1408
+ throw new Error("getUserInfo: response without e-mail - missing userinfo.email scope?");
1409
+ }
1410
+ return data;
1411
+ }
1412
+
1413
+ // =============================================================================
1414
+ // SECTION D - MINIMAL LEGACY FLOW + ACCOUNT MANAGER + PROJECT/QUOTA HELPERS
1415
+ // (original auth.ts content, kept exactly as it was; runtime-used)
1416
+ // =============================================================================
1417
+ // v2.1.14: CLIENT_ID / CLIENT_SECRET moved to Section A (they are the canonical
1418
+ // Antigravity CLI definitions); USERINFO_URL collapsed into the Section B
1419
+ // declaration (byte-identical value in both former files).
1420
+ // =============================================================================
1421
+
1422
+ // =============================================================================
1423
+ // v2.1.16 dead-code cleanup of Section D: the minimal legacy OAuth flow
1424
+ // (genVerifier/genChallenge/genState/cbres/escapeHtml/cbServer/openBrowser/
1425
+ // AUTH_URL/TOKEN_URL/SCOPES/exchangeCode/userInfo/startOAuth) was a dead twin
1426
+ // of the live Section C primitives (generatePKCE, createOAuthServer,
1427
+ // openBrowserAsync, exchangeCodeForTokens, getUserInfo, startOAuthFlow) —
1428
+ // zero callers repo-wide and in tests. Only the LIVE pieces remain below:
1429
+ // fetchTimeout (now delegating to core.js), refreshToken (the minimal
1430
+ // Antigravity-client refresh used by the plugin runtime) and the v3 account
1431
+ // manager. The token/userinfo URLs come from constants.js (single owner).
1432
+ // =============================================================================
1433
+
1434
+ /** v2.1.16 single-owner fix: delegation to core.js fetchWithTimeout (was a private re-implementation). */
1435
+ export const fetchTimeout = async (url: string, init: RequestInit, ms = 10000): Promise<Response> =>
1436
+ fetchWithTimeout(url, init, ms);
1437
+
1438
+ /** Minimal token-response shape of the Antigravity-client refresh flow (Section D lineage). */
1439
+ export type tokenres = {
1440
+ access_token: string;
1441
+ refresh_token?: string;
1442
+ expires_in?: number;
1443
+ id_token?: string;
1444
+ created_at?: number;
1445
+ };
1446
+
1447
+ export const refreshToken = async (rt: string): Promise<tokenres> => {
1448
+ const b = new URLSearchParams({
1449
+ client_id: CLIENT_ID,
1450
+ client_secret: CLIENT_SECRET,
1451
+ refresh_token: rt,
1452
+ grant_type: "refresh_token",
1453
+ });
1454
+ const r = await fetchTimeout(OAUTH_TOKEN_URL, {
1455
+ method: "POST",
1456
+ headers: { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": ua() },
1457
+ body: b.toString(),
1458
+ });
1459
+ if (!r.ok) throw new Error(await r.text());
1460
+ const j = (await r.json()) as tokenres;
1461
+ j.created_at = Date.now();
1462
+ return j;
1463
+ };
1464
+ // v2.1.15 Phase C: cfgDir moved to config.js (configuration owner).
1465
+ export const accountsPath = (): string => join(cfgDir(), "antigravity-accounts.json");
1466
+ // v2.1.15 Phase C: atomicWrite moved to config.js (configuration owner).
1467
+ // v3 accounts format definitive from researches: version 3, accounts array, activeIndex, activeIndexByFamily, rateLimitResetTimes, addedAt, lastUsed, createdAt, expiry, projectId, managedProjectId
1468
+ export type accountEntry = {
1469
+ email: string;
1470
+ refreshToken: string;
1471
+ accessToken?: string;
1472
+ expiry?: number; // ms timestamp expiration
1473
+ createdAt?: number; // ms timestamp creation
1474
+ addedAt: number; // ms timestamp added (original repo uses addedAt)
1475
+ lastUsed?: number; // ms timestamp last used
1476
+ projectId?: string;
1477
+ managedProjectId?: string;
1478
+ disabled?: boolean;
1479
+ quotaExhaustedUntil?: number;
1480
+ softQuotaUntil?: number;
1481
+ remaining?: number;
1482
+ limit?: number;
1483
+ rateLimitResetTimes?: Record<string, number>; // model -> reset timestamp ms
1484
+ };
1485
+ export type accountsFile = {
1486
+ version: 3;
1487
+ accounts: accountEntry[];
1488
+ activeIndex: number;
1489
+ activeIndexByFamily: { claude: number; gemini: number; [k: string]: number };
1490
+ };
1491
+ export class accountManager {
1492
+ private data: accountsFile = {
1493
+ version: 3,
1494
+ accounts: [],
1495
+ activeIndex: 0,
1496
+ activeIndexByFamily: { claude: 0, gemini: 0 },
1497
+ };
1498
+ private locks = new Map<string, Promise<accountEntry>>();
1499
+ private idx = 0;
1500
+ private sticky: string | null = null;
1501
+ async load(): Promise<void> {
1502
+ try {
1503
+ const p = accountsPath();
1504
+ if (!existsSync(p)) {
1505
+ this.data = { version: 3, accounts: [], activeIndex: 0, activeIndexByFamily: { claude: 0, gemini: 0 } };
1506
+ return;
1507
+ }
1508
+ const raw = readFileSync(p, "utf8");
1509
+ const j = JSON.parse(raw);
1510
+ if (Array.isArray(j)) {
1511
+ // legacy v1 array format -> migrate to v3
1512
+ this.data = {
1513
+ version: 3,
1514
+ accounts: j.map((a: any) => ({
1515
+ email: a.email,
1516
+ refreshToken: a.refresh_token || a.refreshToken,
1517
+ accessToken: a.access_token || a.accessToken,
1518
+ expiry: a.expiry,
1519
+ createdAt: a.created_at || a.createdAt || Date.now(),
1520
+ addedAt: a.addedAt || Date.now(),
1521
+ lastUsed: a.lastUsed,
1522
+ projectId: a.projectId,
1523
+ managedProjectId: a.managedProjectId,
1524
+ disabled: a.disabled,
1525
+ rateLimitResetTimes: a.rateLimitResetTimes || {},
1526
+ })),
1527
+ activeIndex: 0,
1528
+ activeIndexByFamily: { claude: 0, gemini: 0 },
1529
+ };
1530
+ } else if (j.version === 3 && Array.isArray(j.accounts)) {
1531
+ this.data = j as accountsFile;
1532
+ // ensure addedAt, createdAt
1533
+ this.data.accounts = this.data.accounts.map((a) => ({
1534
+ rateLimitResetTimes: {},
1535
+ ...a,
1536
+ addedAt: a.addedAt || a.createdAt || Date.now(),
1537
+ createdAt: a.createdAt || a.addedAt || Date.now(),
1538
+ }));
1539
+ } else if (j.accounts && Array.isArray(j.accounts)) {
1540
+ this.data = {
1541
+ version: 3,
1542
+ accounts: j.accounts.map((a: any) => ({
1543
+ email: a.email,
1544
+ refreshToken: a.refreshToken || a.refresh_token,
1545
+ accessToken: a.accessToken,
1546
+ expiry: a.expiry,
1547
+ createdAt: a.createdAt || Date.now(),
1548
+ addedAt: a.addedAt || Date.now(),
1549
+ lastUsed: a.lastUsed,
1550
+ projectId: a.projectId,
1551
+ managedProjectId: a.managedProjectId,
1552
+ disabled: a.disabled,
1553
+ rateLimitResetTimes: a.rateLimitResetTimes || {},
1554
+ })),
1555
+ activeIndex: j.activeIndex || 0,
1556
+ activeIndexByFamily: j.activeIndexByFamily || { claude: 0, gemini: 0 },
1557
+ };
1558
+ } else {
1559
+ this.data = { version: 3, accounts: [], activeIndex: 0, activeIndexByFamily: { claude: 0, gemini: 0 } };
1560
+ }
1561
+ } catch {
1562
+ this.data = { version: 3, accounts: [], activeIndex: 0, activeIndexByFamily: { claude: 0, gemini: 0 } };
1563
+ }
1564
+ }
1565
+ async save(): Promise<void> {
1566
+ atomicWrite(accountsPath(), JSON.stringify(this.data, null, 2));
1567
+ }
1568
+ list(): accountEntry[] {
1569
+ return this.data.accounts;
1570
+ }
1571
+ getFile(): accountsFile {
1572
+ return this.data;
1573
+ }
1574
+ async add(a: Omit<accountEntry, "addedAt" | "createdAt"> & { addedAt?: number; createdAt?: number }): Promise<void> {
1575
+ const now = Date.now();
1576
+ const entry: accountEntry = {
1577
+ ...a,
1578
+ addedAt: a.addedAt || now,
1579
+ createdAt: a.createdAt || now,
1580
+ lastUsed: now,
1581
+ rateLimitResetTimes: a.rateLimitResetTimes || {},
1582
+ };
1583
+ this.data.accounts = this.data.accounts.filter((x) => x.email !== a.email);
1584
+ this.data.accounts.push(entry);
1585
+ if (this.data.activeIndex >= this.data.accounts.length) this.data.activeIndex = 0;
1586
+ await this.save();
1587
+ }
1588
+ async remove(email: string): Promise<void> {
1589
+ this.data.accounts = this.data.accounts.filter((x) => x.email !== email);
1590
+ if (this.data.activeIndex >= this.data.accounts.length) this.data.activeIndex = 0;
1591
+ await this.save();
1592
+ }
1593
+ async enable(email: string, en = true): Promise<void> {
1594
+ const a = this.data.accounts.find((x) => x.email === email);
1595
+ if (a) {
1596
+ a.disabled = !en;
1597
+ await this.save();
1598
+ }
1599
+ }
1600
+ // robin hood with activeIndex + sticky + soft quota + rateLimitResetTimes
1601
+ getNext(strategy: "round-robin" | "sticky" = "round-robin", softThreshold = 90): accountEntry | null {
1602
+ const now = Date.now();
1603
+ const active = this.data.accounts.filter(
1604
+ (a) =>
1605
+ !a.disabled &&
1606
+ (!a.quotaExhaustedUntil || now > a.quotaExhaustedUntil) &&
1607
+ (!a.softQuotaUntil || now > a.softQuotaUntil),
1608
+ );
1609
+ if (active.length === 0) return null;
1610
+ // filter rateLimitResetTimes
1611
+ const notRateLimited = active.filter((a) => {
1612
+ if (!a.rateLimitResetTimes) return true;
1613
+ const resets = Object.values(a.rateLimitResetTimes);
1614
+ return resets.every((ts) => now > ts);
1615
+ });
1616
+ const pool = notRateLimited.length > 0 ? notRateLimited : active;
1617
+ // soft quota
1618
+ const filtered = pool.filter((a) => {
1619
+ if (!a.remaining || !a.limit) return true;
1620
+ const usedPct = ((a.limit - a.remaining) / a.limit) * 100;
1621
+ return usedPct < softThreshold;
1622
+ });
1623
+ const finalPool = filtered.length > 0 ? filtered : pool;
1624
+ if (strategy === "sticky" && this.sticky) {
1625
+ const f = finalPool.find((a) => a.email === this.sticky);
1626
+ if (f) {
1627
+ this.data.activeIndex = finalPool.indexOf(f);
1628
+ return f;
1629
+ }
1630
+ }
1631
+ const acc = finalPool[this.idx % finalPool.length]!;
1632
+ this.idx = (this.idx + 1) % finalPool.length;
1633
+ this.data.activeIndex = this.data.accounts.indexOf(acc);
1634
+ this.sticky = acc.email;
1635
+ // update family index
1636
+ if (acc.email.toLowerCase().includes("claude") || true) {
1637
+ /* generic */
1638
+ }
1639
+ return acc;
1640
+ }
1641
+ setRateLimit(email: string, modelKey: string, resetMs: number): void {
1642
+ const a = this.data.accounts.find((x) => x.email === email);
1643
+ if (a) {
1644
+ if (!a.rateLimitResetTimes) a.rateLimitResetTimes = {};
1645
+ a.rateLimitResetTimes[modelKey] = Date.now() + resetMs;
1646
+ this.save().catch(() => {});
1647
+ }
1648
+ }
1649
+ markExhausted(email: string, ms = 3600000): void {
1650
+ const a = this.data.accounts.find((x) => x.email === email);
1651
+ if (a) {
1652
+ a.quotaExhaustedUntil = Date.now() + ms;
1653
+ this.save().catch(() => {});
1654
+ }
1655
+ }
1656
+ markSoftQuota(email: string, ms = 900000): void {
1657
+ const a = this.data.accounts.find((x) => x.email === email);
1658
+ if (a) {
1659
+ a.softQuotaUntil = Date.now() + ms;
1660
+ this.save().catch(() => {});
1661
+ }
1662
+ }
1663
+ async refreshIfNeeded(email: string): Promise<string> {
1664
+ const acc = this.data.accounts.find((a) => a.email === email);
1665
+ if (!acc) throw new Error("not found");
1666
+ if (acc.accessToken && acc.expiry && Date.now() < acc.expiry - 300000) return acc.accessToken;
1667
+ if (this.locks.has(email)) return (await this.locks.get(email)!)!.accessToken!;
1668
+ const p = (async () => {
1669
+ const t = await refreshToken(acc.refreshToken);
1670
+ acc.accessToken = t.access_token;
1671
+ acc.expiry = Date.now() + (t.expires_in ?? 3600) * 1000;
1672
+ acc.createdAt = Date.now();
1673
+ acc.lastUsed = Date.now();
1674
+ await this.save();
1675
+ return acc;
1676
+ })();
1677
+ this.locks.set(email, p);
1678
+ try {
1679
+ const r = await p;
1680
+ return r.accessToken!;
1681
+ } finally {
1682
+ this.locks.delete(email);
1683
+ }
1684
+ }
1685
+ async importManager(): Promise<number> {
1686
+ const cands = [
1687
+ join(homedir(), ".config", "antigravity-manager", "accounts.json"),
1688
+ join(homedir(), ".antigravity-manager", "accounts.json"),
1689
+ ];
1690
+ let add = 0;
1691
+ for (const c of cands) {
1692
+ try {
1693
+ if (!existsSync(c)) continue;
1694
+ const raw = readFileSync(c, "utf8");
1695
+ const j = JSON.parse(raw);
1696
+ const arr = Array.isArray(j) ? j : j.accounts || [];
1697
+ for (const x of arr) {
1698
+ const email = x.email;
1699
+ const rt = x.refresh_token || x.refreshToken;
1700
+ if (email && rt && !this.data.accounts.find((a) => a.email === email)) {
1701
+ this.data.accounts.push({
1702
+ email,
1703
+ refreshToken: rt,
1704
+ addedAt: Date.now(),
1705
+ createdAt: Date.now(),
1706
+ lastUsed: Date.now(),
1707
+ rateLimitResetTimes: {},
1708
+ });
1709
+ add++;
1710
+ }
1711
+ }
1712
+ } catch {
1713
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1714
+ }
1715
+ }
1716
+ if (add > 0) await this.save();
1717
+ return add;
1718
+ }
1719
+ }
1720
+ // v2.1.15 Phase C: the ordered quota-cascade host array (daily, autopush,
1721
+ // prod) is derived from the constants.js ENDPOINTS host map — the raw values
1722
+ // have one owner; the cascade order is auth-flow-local.
1723
+ const QUOTA_CASCADE_HOSTS = [
1724
+ "https://daily-cloudcode-pa.googleapis.com",
1725
+ "https://autopush-cloudcode-pa.sandbox.googleapis.com",
1726
+ "https://cloudcode-pa.googleapis.com",
1727
+ ] as const;
1728
+ // v2.1.15 Phase B: PROJECT_FALLBACK alias deleted; constants.js PROJECT_FALLBACK is the owner.
1729
+ // v2.1.15 Phase B: isRetryable moved to core.js (generic utility owner).
1730
+ // v2.1.15 Phase A: the auth-local project-discovery helpers (loadCodeAssist,
1731
+ // loadCodeAssistGeminiCLI, onboardUser, resolveProjectId) were dead legacy
1732
+ // duplicates of the canonical project.ts implementations and were deleted.
1733
+ // Project discovery lives ONLY in project.ts.
1734
+ export const retrieveQuota = async (
1735
+ at: string,
1736
+ pid = PROJECT_FALLBACK,
1737
+ ): Promise<{ remaining: number; limit: number; used: number } | null> => {
1738
+ for (const base of QUOTA_CASCADE_HOSTS) {
1739
+ try {
1740
+ const r = await fetchTimeout(
1741
+ `${base}/v1internal:retrieveUserQuotaSummary`,
1742
+ {
1743
+ method: "POST",
1744
+ headers: {
1745
+ Authorization: `Bearer ${at}`,
1746
+ "Content-Type": "application/json",
1747
+ "User-Agent": ua(),
1748
+ "X-Goog-Api-Client": apiClient(),
1749
+ },
1750
+ body: JSON.stringify({ project: `projects/${pid}` }),
1751
+ },
1752
+ 15000,
1753
+ );
1754
+ if (!r.ok) {
1755
+ if (isRetryable(r.status)) continue;
1756
+ return null;
1757
+ }
1758
+ const j: any = await r.json();
1759
+ return {
1760
+ remaining: Number(j.remainingQuota ?? j.remaining ?? 100),
1761
+ limit: Number(j.limit ?? 1000),
1762
+ used: Number(j.used ?? 0),
1763
+ };
1764
+ } catch {
1765
+ continue;
1766
+ }
1767
+ }
1768
+ return null;
1769
+ };
1770
+ /**
1771
+ * @section Model Group Classification
1772
+ * Ported from auth(1).ts v4: classifies a model identifier into its routing group.
1773
+ * "gemini-cli" when the model contains "preview" or starts with a gemini-3.x
1774
+ * prefix (3, 3.1, 3.5, 3.6, 3.7); otherwise "antigravity".
1775
+ */
1776
+ // v2.1.15 Phase A: mapModelToGroup moved to models.ts (canonical merged
1777
+ // implementation of the auth.ts and plugin.ts variants) — re-exported here.
1778
+ export { mapModelToGroup } from "./models.js";
1779
+ // v2.1.16 dead-code cleanup: the Section D startOAuth orchestrator (dead twin
1780
+ // of the live authenticate/startOAuthFlow Section E flow) was deleted here.
1781
+
1782
+ // =============================================================================
1783
+ // SECTION E - ORCHESTRATORS + VALIDATION + MODEL HELPERS (former oauth.ts)
1784
+ // =============================================================================
1785
+
1786
+ // =============================================================================
1787
+ // COMPLETE ORCHESTRATOR - AUTHENTICATE (full featured)
1788
+ // =============================================================================
1789
+
1790
+ /**
1791
+ * Full OAuth flow: PKCE + Server + Browser + Exchange + UserInfo.
1792
+ * Supports:
1793
+ * - WSL/SSH detection -> does not try to open a browser when there is no DISPLAY
1794
+ * - --no-browser flag via AuthOptions.noBrowser or env OPENCODE_NO_BROWSER=1 or args
1795
+ * - 30s timeout fallback to manual URL/code input
1796
+ *
1797
+ * @param opts - AuthOptions
1798
+ * @returns object with tokens and userinfo
1799
+ */
1800
+ export async function authenticate(
1801
+ opts: AuthOptions & {
1802
+ existingPKCE?: PKCEPair;
1803
+ } = {},
1804
+ ): Promise<{
1805
+ tokens: TokenResponse;
1806
+ userInfo: UserInfo;
1807
+ pkce: PKCEPair | null;
1808
+ callbackUrl: string;
1809
+ }> {
1810
+ const log =
1811
+ opts.onLog ??
1812
+ ((level, msg) => {
1813
+ const prefix = level === "error" ? "[m[devthink][ERR]" : level === "warn" ? "[m[devthink][WARN]" : "[m[devthink]";
1814
+ console.log(`${prefix} ${msg}`);
1815
+ });
1816
+
1817
+ const callbackPath = opts.callbackPath ?? "/oauth2callback";
1818
+ const timeoutMs = opts.callbackTimeoutMs ?? 5 * 60 * 1000;
1819
+
1820
+ const noBrowserFlag =
1821
+ opts.noBrowser ||
1822
+ process.env.OPENCODE_NO_BROWSER === "1" ||
1823
+ process.argv.includes("--no-browser") ||
1824
+ process.env.NO_BROWSER === "1";
1825
+
1826
+ const pkce = opts.existingPKCE ?? (opts.identity?.usesPKCE ? generatePKCE() : null);
1827
+ const state = crypto.randomBytes(32).toString("hex");
1828
+
1829
+ const port = await getAvailablePort();
1830
+ const redirectUri = `http://127.0.0.1:${port}${callbackPath}`;
1831
+ log(
1832
+ "info",
1833
+ `Starting local OAuth server on 127.0.0.1:${port}${process.env.OAUTH_CALLBACK_HOST ? " (custom OAUTH_CALLBACK_HOST)" : ""} ...`,
1834
+ );
1835
+ log("info", `Callback URL: ${redirectUri}`);
1836
+
1837
+ let oauthSrv: OAuthServerResult | null = null;
1838
+ if (process.env.OAUTH_CALLBACK_PORT) {
1839
+ oauthSrv = createOAuthServer({ callbackPath, onLog: log, expectedState: state });
1840
+ let attempts = 0;
1841
+ while (oauthSrv.port === 0 && attempts < 50) {
1842
+ await new Promise((r) => setTimeout(r, 20));
1843
+ attempts++;
1844
+ }
1845
+ if (oauthSrv.port === 0)
1846
+ await new Promise<void>((resolve, reject) => {
1847
+ oauthSrv!.server.once("listening", resolve);
1848
+ oauthSrv!.server.once("error", reject);
1849
+ });
1850
+ } else {
1851
+ const prev = process.env.OAUTH_CALLBACK_PORT;
1852
+ process.env.OAUTH_CALLBACK_PORT = String(port);
1853
+ oauthSrv = createOAuthServer({ callbackPath, onLog: log, expectedState: state });
1854
+ let attempts = 0;
1855
+ while (oauthSrv.port === 0 && attempts < 50) {
1856
+ await new Promise((r) => setTimeout(r, 20));
1857
+ attempts++;
1858
+ }
1859
+ if (oauthSrv.port === 0)
1860
+ await new Promise<void>((resolve, reject) => {
1861
+ oauthSrv!.server.once("listening", resolve);
1862
+ oauthSrv!.server.once("error", reject);
1863
+ });
1864
+ if (prev === undefined) delete (process.env as any).OAUTH_CALLBACK_PORT;
1865
+ else process.env.OAUTH_CALLBACK_PORT = prev;
1866
+ }
1867
+
1868
+ const authUrl = buildAuthUrl(pkce, redirectUri, {
1869
+ state,
1870
+ accessType: "offline",
1871
+ scopes: opts.identity?.scopesStr ?? GEMINI_CLI_OAUTH_SCOPE_STR,
1872
+ ...(opts.identity?.clientId ? { clientId: opts.identity.clientId } : {}),
1873
+ ...(opts.identity?.usesPKCE ? { prompt: "consent" as const } : {}),
1874
+ });
1875
+
1876
+ let browserOpened = false;
1877
+ const shouldAttemptBrowser = (!noBrowserFlag && hasDisplay() && !isSSH()) || (isWSL() && !noBrowserFlag);
1878
+
1879
+ if (shouldAttemptBrowser) {
1880
+ log("info", "Trying to open the default browser...");
1881
+ try {
1882
+ browserOpened = await openBrowserAsync(authUrl);
1883
+ if (browserOpened) log("info", "Browser opened. Waiting for authorization in the browser...");
1884
+ else log("warn", "Could not open the browser automatically.");
1885
+ } catch (e) {
1886
+ log("warn", `openBrowser failed: ${(e as Error).message}`);
1887
+ }
1888
+ } else {
1889
+ if (noBrowserFlag) log("info", "--no-browser flag detected. Skipping automatic opening.");
1890
+ else if (isSSH()) log("info", "SSH session detected - no local display.");
1891
+ else if (!hasDisplay()) log("info", "No display detected (DISPLAY/WAYLAND_DISPLAY missing).");
1892
+ }
1893
+
1894
+ if (!browserOpened) {
1895
+ log("info", "Open the URL below manually in the browser:\n\n" + authUrl + "\n");
1896
+ console.log("\n\x1b[1m\x1b[36mTo authenticate, open this URL in your browser:\x1b[0m\n");
1897
+ console.log(`\x1b[4m${authUrl}\x1b[0m\n`);
1898
+ } else {
1899
+ console.log(`\nAttempting to open authentication page in your browser.\nOtherwise navigate to:\n\n${authUrl}\n\n`);
1900
+ }
1901
+
1902
+ let code: string;
1903
+ try {
1904
+ const codePromise = oauthSrv!.waitForCode();
1905
+ const timeoutPromise = new Promise<never>((_, reject) => {
1906
+ setTimeout(() => reject(new Error("TIMEOUT")), timeoutMs);
1907
+ });
1908
+ let sigIntHandler: (() => void) | undefined;
1909
+ let stdinHandler: ((data: Buffer) => void) | undefined;
1910
+ const cancellationPromise = new Promise<never>((_, reject) => {
1911
+ sigIntHandler = () => reject(new Error("Authentication cancelled by user (SIGINT)"));
1912
+ process.on("SIGINT", sigIntHandler);
1913
+ stdinHandler = (data: Buffer) => {
1914
+ if (data.length === 1 && data[0] === 0x03) reject(new Error("Authentication cancelled by user (Ctrl+C)"));
1915
+ };
1916
+ try {
1917
+ process.stdin.on("data", stdinHandler);
1918
+ } catch {
1919
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1920
+ }
1921
+ });
1922
+ try {
1923
+ code = await Promise.race([codePromise, timeoutPromise, cancellationPromise]);
1924
+ } catch (err) {
1925
+ if ((err as Error).message === "TIMEOUT") {
1926
+ log("warn", `${timeoutMs / 1000}s timeout waiting for callback - falling back to manual input.`);
1927
+ console.log("\n\x1b[33mTimeout waiting for automatic callback.\x1b[0m");
1928
+ console.log("Paste below the full URL the browser redirected to (with ?code=) or just the code:\n");
1929
+ try {
1930
+ code = await askManualInput("Callback code/URL: ");
1931
+ log("info", "Code received via manual input.");
1932
+ } catch (inputErr) {
1933
+ await oauthSrv!.close().catch(() => {});
1934
+ throw inputErr;
1935
+ }
1936
+ } else {
1937
+ throw err;
1938
+ }
1939
+ } finally {
1940
+ if (sigIntHandler)
1941
+ try {
1942
+ process.removeListener("SIGINT", sigIntHandler);
1943
+ } catch {
1944
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1945
+ }
1946
+ if (stdinHandler)
1947
+ try {
1948
+ process.stdin.removeListener("data", stdinHandler);
1949
+ } catch {
1950
+ /* the guarded best-effort operation falls through: the outer flow owns the failure */
1951
+ }
1952
+ }
1953
+ } finally {
1954
+ await oauthSrv!.close().catch(() => {});
1955
+ }
1956
+
1957
+ log("info", `Code obtained. Exchanging for tokens at ${OAUTH_TOKEN_URL}...`);
1958
+ const tokens = await exchangeCodeForTokens(code, pkce?.verifier ?? null, redirectUri, {
1959
+ ...(opts.identity ? { clientId: opts.identity.clientId, clientSecret: opts.identity.clientSecret } : {}),
1960
+ });
1961
+ log("info", `Tokens obtained. Expires in ${tokens.expires_in}s`);
1962
+ log("info", "Fetching user information...");
1963
+ const userInfo = await getUserInfo(tokens.access_token);
1964
+ log("info", `Authenticated as ${userInfo.email} (${userInfo.name})`);
1965
+ return { tokens, userInfo, pkce, callbackUrl: redirectUri };
1966
+ }
1967
+
1968
+ // =============================================================================
1969
+ // DIRECT ORCHESTRATOR - START OAUTH FLOW (injectable, ported from oauth(2).ts)
1970
+ // =============================================================================
1971
+
1972
+ /**
1973
+ * Direct PKCE orchestrator ported from oauth(2).ts and adapted onto the local
1974
+ * server infrastructure above (single server implementation, multi-path
1975
+ * callback, scope capture, CSRF state validation).
1976
+ *
1977
+ * Steps:
1978
+ * 1. generatePKCE (verifier + S256 challenge)
1979
+ * 2. local server 127.0.0.1 on a locked random port
1980
+ * 3. auth URL with code_challenge and state
1981
+ * 4. browser opening via injectable openBrowserFn (manual fallback: URL logged)
1982
+ * 5. waits for callback with total timeout
1983
+ * 6. exchanges code for tokens at POST https://oauth2.googleapis.com/token
1984
+ * 7. fetches userinfo e-mail
1985
+ *
1986
+ * @param options - StartOAuthFlowOptions (all injectable for tests)
1987
+ * @returns OAuthResult with tokens + userInfo + validated state
1988
+ */
1989
+ export async function startOAuthFlow(options: StartOAuthFlowOptions = {}): Promise<OAuthResult> {
1990
+ const clientId = options.clientId ?? GEMINI_OAUTH_CLIENT_ID;
1991
+ const clientSecret = options.clientSecret ?? GEMINI_OAUTH_CLIENT_SECRET;
1992
+ const scopes = options.scopes ?? GOOGLE_OAUTH_SCOPES;
1993
+ const callbackPath = options.callbackPath ?? "/callback";
1994
+ const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;
1995
+ const opener =
1996
+ options.openBrowserFn ??
1997
+ ((url: string) => {
1998
+ void openBrowserAsync(url);
1999
+ });
2000
+
2001
+ // 1. PKCE
2002
+ const pkce = generatePKCE();
2003
+ const state = base64urlEncode(crypto.randomBytes(32));
2004
+
2005
+ // 2. local locked server 127.0.0.1 random port (multi-path + scope capture)
2006
+ const srv = await createOAuthServerAsync({
2007
+ callbackPath,
2008
+ expectedState: state,
2009
+ });
2010
+
2011
+ const redirectUri = srv.callbackUrl;
2012
+
2013
+ // 3. Google authorization URL
2014
+ const authParams = new URLSearchParams({
2015
+ client_id: clientId,
2016
+ redirect_uri: redirectUri,
2017
+ response_type: "code",
2018
+ scope: scopes,
2019
+ code_challenge: pkce.challenge,
2020
+ code_challenge_method: "S256",
2021
+ state,
2022
+ access_type: "offline",
2023
+ prompt: "consent", // forces refresh_token every time
2024
+ });
2025
+
2026
+ const authUrl = `${OAUTH_AUTHORIZE_URL}?${authParams.toString()}`;
2027
+
2028
+ // 4. open browser with manual fallback (URL always logged)
2029
+ console.log(
2030
+ `\n[m[devthink] Opening browser for authentication...\n` +
2031
+ `If it does not open automatically, copy and paste into the browser:\n\n${authUrl}\n`,
2032
+ );
2033
+ try {
2034
+ opener(authUrl);
2035
+ } catch (err) {
2036
+ console.log(`[m[devthink] openBrowserFn failed, manual fallback: ${authUrl}`);
2037
+ }
2038
+
2039
+ // 5. wait for callback (validates state against CSRF) with total timeout
2040
+ let callbackResult: OAuthCallbackResult;
2041
+ try {
2042
+ const timeoutPromise = new Promise<never>((_, reject) => {
2043
+ setTimeout(
2044
+ () => reject(new Error(`OAuth timeout after ${timeoutMs / 1000}s - user did not complete login`)),
2045
+ timeoutMs,
2046
+ );
2047
+ });
2048
+ callbackResult = await Promise.race([srv.waitForCallback(), timeoutPromise]);
2049
+
2050
+ if (callbackResult.state !== state) {
2051
+ throw new Error(`State mismatch - possible CSRF. Expected ${state} received ${callbackResult.state}`);
2052
+ }
2053
+ } catch (err) {
2054
+ await srv.close().catch(() => {});
2055
+ throw err;
2056
+ }
2057
+
2058
+ // 6. exchange code for tokens
2059
+ let tokens: TokenResponse;
2060
+ try {
2061
+ tokens = await exchangeCodeForTokens(callbackResult.code, pkce.verifier, redirectUri, {
2062
+ clientId,
2063
+ clientSecret,
2064
+ });
2065
+ } catch (err) {
2066
+ await srv.close().catch(() => {});
2067
+ throw err;
2068
+ }
2069
+
2070
+ // 7. userinfo e-mail
2071
+ let userInfo: UserInfo;
2072
+ try {
2073
+ userInfo = await getUserInfo(tokens.access_token);
2074
+ } catch (err) {
2075
+ await srv.close().catch(() => {});
2076
+ throw new Error(`Failed to obtain e-mail after token exchange: ${(err as Error).message}`, {
2077
+ cause: err,
2078
+ });
2079
+ }
2080
+
2081
+ // 8. shut the server down
2082
+ await srv.close();
2083
+
2084
+ console.log(
2085
+ `\n[m[devthink] Authenticated as ${userInfo.email} - ready models: ${SUPPORTED_MODELS_2026.join(", ")}\n`,
2086
+ );
2087
+
2088
+ return { tokens, userInfo, state };
2089
+ }
2090
+
2091
+ // =============================================================================
2092
+ // ADDITIONAL HELPERS - STORAGE & VALIDATION
2093
+ // =============================================================================
2094
+
2095
+ /**
2096
+ * Validates the TokenResponse shape (useful when loading from disk)
2097
+ */
2098
+ export function isValidTokenResponse(obj: any): obj is TokenResponse {
2099
+ return (
2100
+ obj &&
2101
+ typeof obj.access_token === "string" &&
2102
+ typeof obj.expires_at === "number" &&
2103
+ typeof obj.expires_in === "number"
2104
+ );
2105
+ }
2106
+
2107
+ /**
2108
+ * Extracts the code from a callback URL (public helper for manual paste)
2109
+ */
2110
+ export function extractCodeFromUrl(input: string): string | null {
2111
+ const trimmed = input.trim();
2112
+ if (!trimmed) return null;
2113
+ try {
2114
+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
2115
+ const u = new URL(trimmed);
2116
+ return u.searchParams.get("code");
2117
+ }
2118
+ } catch {
2119
+ // ignore
2120
+ }
2121
+ // Tries code= regex
2122
+ const m = trimmed.match(/[?&]code=([^&]+)/);
2123
+ if (m) return decodeURIComponent(m[1]!);
2124
+ // Looks like a bare code (no spaces, reasonable length)
2125
+ if (/^[A-Za-z0-9\-_]+$/.test(trimmed) && trimmed.length > 10) return trimmed;
2126
+ return null;
2127
+ }
2128
+
2129
+ // =============================================================================
2130
+ // MODEL HELPERS - READY TO USE FOR CLOUDCODE REQUESTS
2131
+ // =============================================================================
2132
+
2133
+ /**
2134
+ * Returns the list of available models (the folded 2026 tuple).
2135
+ * Helper for client-side validation before calling fetchAvailableModels.
2136
+ */
2137
+ export function getAllModels(): readonly string[] {
2138
+ return SUPPORTED_MODELS_2026;
2139
+ }
2140
+
2141
+ export function isAntigravityModel(model: string): boolean {
2142
+ return model.startsWith("antigravity-");
2143
+ }
2144
+ /**
2145
+ * Default export for CJS/ESM interop. v2.1.14: preserved from the former
2146
+ * oauth.ts - every key keeps its legacy oauth.js VALUE (Gemini CLI client),
2147
+ * so `default ?? namespace` interop consumers (the cli.ts pattern) keep
2148
+ * observing the gemini credentials even though the bare named exports
2149
+ * CLIENT_ID / CLIENT_SECRET now carry the Antigravity CLI client. The
2150
+ * v2.1.14-renamed symbols are wired back under their legacy keys.
2151
+ */
2152
+ const oauth = {
2153
+ CLIENT_ID: GEMINI_OAUTH_CLIENT_ID,
2154
+ CLIENT_SECRET: GEMINI_OAUTH_CLIENT_SECRET,
2155
+ CLIENT_SECRET_ALTERNATIVE: GEMINI_OAUTH_CLIENT_SECRET_ALTERNATIVE,
2156
+ GEMINI_OAUTH_CLIENT_ID,
2157
+ GEMINI_OAUTH_CLIENT_SECRET,
2158
+ SCOPES: GEMINI_OAUTH_SCOPES,
2159
+ GOOGLE_OAUTH_SCOPES,
2160
+ OAUTH_AUTHORIZE_URL,
2161
+ OAUTH_TOKEN_URL,
2162
+ USERINFO_URL,
2163
+ GOOGLE_AUTH_URL,
2164
+ GOOGLE_TOKEN_URL,
2165
+ GOOGLE_USERINFO_URL,
2166
+ CLOUDCODE_BASE,
2167
+ CLOUDCODE_API_BASE,
2168
+ CLOUDCODE_ORIGIN,
2169
+ ENDPOINTS: CLOUDCODE_ENDPOINTS,
2170
+ PROJECT_FALLBACK,
2171
+ MODELS_2026: SUPPORTED_MODELS_2026,
2172
+ SUPPORTED_MODELS_2026,
2173
+ GEMINI_UA_BASE,
2174
+ ANTIGRAVITY_USER_AGENT,
2175
+ // funcs
2176
+ generatePKCE,
2177
+ buildAuthUrl,
2178
+ createOAuthServer,
2179
+ createOAuthServerAsync,
2180
+ openBrowser: openBrowserAsync,
2181
+ exchangeCodeForTokens,
2182
+ refreshAccessToken,
2183
+ refreshAndPreserve,
2184
+ startOAuthFlow,
2185
+ getUserInfo,
2186
+ authenticate,
2187
+ isTokenExpired,
2188
+ isValidTokenResponse,
2189
+ extractCodeFromUrl,
2190
+ isWSL,
2191
+ isSSH,
2192
+ hasDisplay,
2193
+ buildGeminiUserAgent,
2194
+ getGeminiHeaders,
2195
+ getAllModels,
2196
+ isAntigravityModel,
2197
+ base64urlEncode,
2198
+ base64urlDecode,
2199
+ };
2200
+
2201
+ export default oauth;