@wenathlan/devthink 2.0.13 → 2.0.15

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