swayrouter 1.0.0

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 (643) hide show
  1. package/.env.example +43 -0
  2. package/CHANGELOG.md +132 -0
  3. package/LICENSE +30 -0
  4. package/README.id.md +633 -0
  5. package/README.md +628 -0
  6. package/cli/cli.js +388 -0
  7. package/cli/package.json +4 -0
  8. package/cli/src/cli/commands/xaiVideo.js +280 -0
  9. package/cli/src/cli/tray/SwayAvatar.svg +20 -0
  10. package/cli/src/cli/tray/autostart.js +351 -0
  11. package/cli/src/cli/tray/icon.ico +0 -0
  12. package/cli/src/cli/tray/icon.png +0 -0
  13. package/cli/src/cli/tray/tray.js +258 -0
  14. package/cli/src/cli/tray/tray.ps1 +129 -0
  15. package/cli/src/cli/tray/trayHost.js +157 -0
  16. package/cli/src/cli/tray/trayWin.js +83 -0
  17. package/cli/src/cli/utils/display.js +123 -0
  18. package/cli/src/cli/utils/input.js +138 -0
  19. package/cli/src/runtime/discover.js +153 -0
  20. package/cli/src/runtime/lifecycle.js +333 -0
  21. package/cli/src/runtime/runMenu.js +250 -0
  22. package/cli/src/runtime/uiAdapters.js +12 -0
  23. package/cli/src/runtime/update.js +130 -0
  24. package/dashboard/dist/assets/CliTools-Ch3gKuNw.js +24 -0
  25. package/dashboard/dist/assets/Combo-BBCldjWi.js +1 -0
  26. package/dashboard/dist/assets/ConsoleLog-wywAYcPT.js +6 -0
  27. package/dashboard/dist/assets/Dashboard-DxzyF41b.js +1 -0
  28. package/dashboard/dist/assets/Header-C_9Su9BF.js +1 -0
  29. package/dashboard/dist/assets/Keys-D0ufgcsc.js +1 -0
  30. package/dashboard/dist/assets/Login-BeKpipS_.js +1 -0
  31. package/dashboard/dist/assets/ManageApiKey-CVXsmW2B.js +1 -0
  32. package/dashboard/dist/assets/OAuthCallback-D_UZYcF6.js +1 -0
  33. package/dashboard/dist/assets/Provider-BU7JfTqm.js +4 -0
  34. package/dashboard/dist/assets/ProviderModelAccordion-BAifkfVR.js +1 -0
  35. package/dashboard/dist/assets/Proxy-CU15VJ--.js +1 -0
  36. package/dashboard/dist/assets/QuotaMonitor-HzGK7bcc.js +1 -0
  37. package/dashboard/dist/assets/Settings-Dt4y2dC0.js +1 -0
  38. package/dashboard/dist/assets/Setup-DSDUwU7N.js +1 -0
  39. package/dashboard/dist/assets/StatusBadge-1nAOyHU2.js +1 -0
  40. package/dashboard/dist/assets/SwayChat-Bup7up6D.js +10 -0
  41. package/dashboard/dist/assets/Usage-eWnrPQ_v.js +4 -0
  42. package/dashboard/dist/assets/accordion-DOOPDDgt.js +1 -0
  43. package/dashboard/dist/assets/admin-extras-api-CCdu5TFM.js +1 -0
  44. package/dashboard/dist/assets/api-keys-api-ifAC2Ok3.js +1 -0
  45. package/dashboard/dist/assets/card-CC0Omjcv.js +1 -0
  46. package/dashboard/dist/assets/chatStudio-C0zPz_Z_.js +2 -0
  47. package/dashboard/dist/assets/checkbox-7SZBrmbN.js +1 -0
  48. package/dashboard/dist/assets/connections-api-_N54UD3S.js +1 -0
  49. package/dashboard/dist/assets/copy-button-qBvM6H9z.js +1 -0
  50. package/dashboard/dist/assets/currency-api-SV9CBf5e.js +1 -0
  51. package/dashboard/dist/assets/flip-button-BGgkjtl0.js +1 -0
  52. package/dashboard/dist/assets/frame-cUiti6Lq.js +1 -0
  53. package/dashboard/dist/assets/icons-vendor-CUx7SB5V.js +541 -0
  54. package/dashboard/dist/assets/index-B6j-9zHy.js +10 -0
  55. package/dashboard/dist/assets/index-C-_l0yYz.css +1 -0
  56. package/dashboard/dist/assets/live-mode-CHShLY4E.js +1 -0
  57. package/dashboard/dist/assets/markdown-vendor-BY8e1gQ8.js +29 -0
  58. package/dashboard/dist/assets/motion-vendor-g5fpGzmJ.js +9 -0
  59. package/dashboard/dist/assets/oauth-callback-CqYQzyd7.js +1 -0
  60. package/dashboard/dist/assets/query-vendor-DVevaSVS.js +1 -0
  61. package/dashboard/dist/assets/react-vendor-xnYrwzsL.js +61 -0
  62. package/dashboard/dist/assets/ripple-button-l8aMiVVG.js +1 -0
  63. package/dashboard/dist/assets/segmented-CqmEnQjZ.js +1 -0
  64. package/dashboard/dist/assets/select-D8pUtMXp.js +1 -0
  65. package/dashboard/dist/assets/skeleton-7uJDiIXe.js +1 -0
  66. package/dashboard/dist/assets/table-D0M60Tu1.js +1 -0
  67. package/dashboard/dist/assets/tabs-C6YkuulG.js +1 -0
  68. package/dashboard/dist/assets/tunnel-api-DDPsBaDV.js +1 -0
  69. package/dashboard/dist/assets/ui-vendor-BuM9f2NY.js +17 -0
  70. package/dashboard/dist/image2/SwayAvatar.svg +20 -0
  71. package/dashboard/dist/index.html +32 -0
  72. package/dashboard/dist/logo/avatar.svg +1 -0
  73. package/dashboard/dist/logo/sway.svg +20 -0
  74. package/dashboard/dist/logo/swaychat.svg +20 -0
  75. package/dashboard/dist/providers/SwayCustom.svg +19 -0
  76. package/dashboard/dist/providers/alicode.svg +12 -0
  77. package/dashboard/dist/providers/anthropic.svg +11 -0
  78. package/dashboard/dist/providers/antigravity.svg +3 -0
  79. package/dashboard/dist/providers/azure.svg +5 -0
  80. package/dashboard/dist/providers/baidu.svg +3 -0
  81. package/dashboard/dist/providers/blackbox.svg +5 -0
  82. package/dashboard/dist/providers/byteplus.svg +3 -0
  83. package/dashboard/dist/providers/cerebras.svg +4 -0
  84. package/dashboard/dist/providers/chutes.svg +4 -0
  85. package/dashboard/dist/providers/claude.svg +3 -0
  86. package/dashboard/dist/providers/cline.svg +11 -0
  87. package/dashboard/dist/providers/cloudflare-ai.svg +4 -0
  88. package/dashboard/dist/providers/codebuddy.svg +11 -0
  89. package/dashboard/dist/providers/codex.svg +10 -0
  90. package/dashboard/dist/providers/commandcode.svg +3 -0
  91. package/dashboard/dist/providers/cursor.svg +3 -0
  92. package/dashboard/dist/providers/deepseek.svg +10 -0
  93. package/dashboard/dist/providers/featherless.svg +3 -0
  94. package/dashboard/dist/providers/fireworks.svg +3 -0
  95. package/dashboard/dist/providers/gemini.svg +3 -0
  96. package/dashboard/dist/providers/geminicli.svg +11 -0
  97. package/dashboard/dist/providers/github.svg +3 -0
  98. package/dashboard/dist/providers/grok.svg +3 -0
  99. package/dashboard/dist/providers/groq.svg +3 -0
  100. package/dashboard/dist/providers/hermesagent.svg +1 -0
  101. package/dashboard/dist/providers/kilocode.svg +15 -0
  102. package/dashboard/dist/providers/kimchi.svg +3 -0
  103. package/dashboard/dist/providers/kimi.svg +4 -0
  104. package/dashboard/dist/providers/kiro.svg +10 -0
  105. package/dashboard/dist/providers/meta.svg +3 -0
  106. package/dashboard/dist/providers/mimo.svg +10 -0
  107. package/dashboard/dist/providers/minimax.svg +3 -0
  108. package/dashboard/dist/providers/mistral.svg +3 -0
  109. package/dashboard/dist/providers/morph.svg +3 -0
  110. package/dashboard/dist/providers/nebius.svg +4 -0
  111. package/dashboard/dist/providers/nvidia.svg +3 -0
  112. package/dashboard/dist/providers/ollama.svg +3 -0
  113. package/dashboard/dist/providers/omp.svg +5 -0
  114. package/dashboard/dist/providers/openai.svg +3 -0
  115. package/dashboard/dist/providers/opencode.svg +3 -0
  116. package/dashboard/dist/providers/openrouter.svg +3 -0
  117. package/dashboard/dist/providers/perplexity.svg +3 -0
  118. package/dashboard/dist/providers/poolside.svg +36 -0
  119. package/dashboard/dist/providers/qoder.svg +11 -0
  120. package/dashboard/dist/providers/sumopod.svg +3 -0
  121. package/dashboard/dist/providers/tencent.svg +5 -0
  122. package/dashboard/dist/providers/together.svg +12 -0
  123. package/dashboard/dist/providers/trae.svg +3 -0
  124. package/dashboard/dist/providers/venice.svg +4 -0
  125. package/dashboard/dist/providers/vercel.svg +3 -0
  126. package/dashboard/dist/providers/vertex.svg +17 -0
  127. package/dashboard/dist/providers/windsurf.svg +10 -0
  128. package/dashboard/dist/providers/zai.svg +3 -0
  129. package/dashboard/tsconfig.json +13 -0
  130. package/package.json +87 -0
  131. package/src/config/appConstants.js +153 -0
  132. package/src/config/defaultThinkingSignature.js +7 -0
  133. package/src/config/errorConfig.js +117 -0
  134. package/src/config/grokCli.js +9 -0
  135. package/src/config/kiroConstants.js +235 -0
  136. package/src/config/mediaConfig.js +20 -0
  137. package/src/config/ollamaModels.js +18 -0
  138. package/src/config/providerModels.js +109 -0
  139. package/src/config/providers.js +17 -0
  140. package/src/config/runtimeConfig.js +84 -0
  141. package/src/dashboardGuard.js +254 -0
  142. package/src/executors/antigravity.js +389 -0
  143. package/src/executors/azure.js +49 -0
  144. package/src/executors/base.js +225 -0
  145. package/src/executors/codebuddy-cn.js +23 -0
  146. package/src/executors/codebuddy-intl.js +60 -0
  147. package/src/executors/codex.js +436 -0
  148. package/src/executors/commandcode.js +83 -0
  149. package/src/executors/cursor.js +1075 -0
  150. package/src/executors/default.js +294 -0
  151. package/src/executors/gemini-cli.js +88 -0
  152. package/src/executors/github.js +393 -0
  153. package/src/executors/grok-cli.js +510 -0
  154. package/src/executors/grok-web.js +342 -0
  155. package/src/executors/index.js +86 -0
  156. package/src/executors/kimchi.js +116 -0
  157. package/src/executors/kiro.js +1155 -0
  158. package/src/executors/ollama-local.js +14 -0
  159. package/src/executors/opencode-go.js +47 -0
  160. package/src/executors/opencode.js +31 -0
  161. package/src/executors/qoder.js +433 -0
  162. package/src/executors/trae.js +318 -0
  163. package/src/executors/vertex.js +151 -0
  164. package/src/executors/windsurf.js +555 -0
  165. package/src/executors/xiaomi-tokenplan.js +16 -0
  166. package/src/handlers/chatCore/nonStreamingHandler.js +370 -0
  167. package/src/handlers/chatCore/requestDetail.js +130 -0
  168. package/src/handlers/chatCore/sseToJsonHandler.js +318 -0
  169. package/src/handlers/chatCore/streamingHandler.js +250 -0
  170. package/src/handlers/chatCore.js +652 -0
  171. package/src/lib/auth/dashboardSession.js +83 -0
  172. package/src/lib/auth/loginLimiter.js +99 -0
  173. package/src/lib/cache/ttlCache.js +153 -0
  174. package/src/lib/consoleLogBuffer.js +127 -0
  175. package/src/lib/dataDir.js +45 -0
  176. package/src/lib/db/adapters/betterSqliteAdapter.js +36 -0
  177. package/src/lib/db/adapters/bunSqliteAdapter.js +47 -0
  178. package/src/lib/db/adapters/nodeSqliteAdapter.js +65 -0
  179. package/src/lib/db/adapters/runtimeHelpers.js +23 -0
  180. package/src/lib/db/adapters/sqljsAdapter.js +103 -0
  181. package/src/lib/db/backup.js +75 -0
  182. package/src/lib/db/driver.js +110 -0
  183. package/src/lib/db/helpers/jsonCol.js +18 -0
  184. package/src/lib/db/helpers/kvStore.js +48 -0
  185. package/src/lib/db/helpers/metaStore.js +32 -0
  186. package/src/lib/db/index.js +473 -0
  187. package/src/lib/db/migrate.js +267 -0
  188. package/src/lib/db/migrations/001-initial.js +12 -0
  189. package/src/lib/db/migrations/002-prune-headroom-pxpipe-settings.js +32 -0
  190. package/src/lib/db/migrations/004-request-details-trace-id.js +12 -0
  191. package/src/lib/db/migrations/005-request-details-payload-capture.js +11 -0
  192. package/src/lib/db/migrations/007-headroom-readd-settings.js +35 -0
  193. package/src/lib/db/migrations/008-account-model-locks.js +22 -0
  194. package/src/lib/db/migrations/009-warp-pool-lifecycle.js +5 -0
  195. package/src/lib/db/migrations/010-api-key-file-permissions.js +7 -0
  196. package/src/lib/db/migrations/011-remove-upstream-user-agent-profile.js +41 -0
  197. package/src/lib/db/migrations/012-remove-headroom-settings.js +33 -0
  198. package/src/lib/db/migrations/013-default-fill-first-routing.js +20 -0
  199. package/src/lib/db/migrations/014-normalize-fill-first-routing.js +37 -0
  200. package/src/lib/db/migrations/015-remove-ip-ban-tables.js +8 -0
  201. package/src/lib/db/migrations/016-prune-legacy-codebuddy-intl-models.js +25 -0
  202. package/src/lib/db/migrations/index.js +20 -0
  203. package/src/lib/db/nineRouterMigration.js +785 -0
  204. package/src/lib/db/paths.js +23 -0
  205. package/src/lib/db/repos/accountModelLocksRepo.js +74 -0
  206. package/src/lib/db/repos/aliasRepo.js +108 -0
  207. package/src/lib/db/repos/apiKeysRepo.js +204 -0
  208. package/src/lib/db/repos/combosRepo.js +85 -0
  209. package/src/lib/db/repos/connectionsRepo.js +522 -0
  210. package/src/lib/db/repos/disabledModelsRepo.js +63 -0
  211. package/src/lib/db/repos/nodesRepo.js +127 -0
  212. package/src/lib/db/repos/pricingRepo.js +108 -0
  213. package/src/lib/db/repos/proxyPoolsRepo.js +104 -0
  214. package/src/lib/db/repos/requestDetailsRepo.js +345 -0
  215. package/src/lib/db/repos/settingsRepo.js +135 -0
  216. package/src/lib/db/repos/usageRepo.js +1335 -0
  217. package/src/lib/db/schema.js +179 -0
  218. package/src/lib/db/version.js +32 -0
  219. package/src/lib/db/writeBehind.js +174 -0
  220. package/src/lib/disabledModelsDb.js +3 -0
  221. package/src/lib/env.ts +175 -0
  222. package/src/lib/errors/publicError.js +18 -0
  223. package/src/lib/grokBuildConfig.js +243 -0
  224. package/src/lib/guardRequest.js +51 -0
  225. package/src/lib/localDb.js +21 -0
  226. package/src/lib/mcp/stdioSseBridge.js +174 -0
  227. package/src/lib/network/connectionProxy.js +200 -0
  228. package/src/lib/network/proxyTest.js +158 -0
  229. package/src/lib/network/proxyUrl.js +76 -0
  230. package/src/lib/network/relay.js +71 -0
  231. package/src/lib/oauth/constants/oauth.js +152 -0
  232. package/src/lib/oauth/constants/xai.js +43 -0
  233. package/src/lib/oauth/kiroExternalIdp.js +167 -0
  234. package/src/lib/oauth/providerHelpers.js +90 -0
  235. package/src/lib/oauth/providers/_shared.js +12 -0
  236. package/src/lib/oauth/providers/antigravity.js +126 -0
  237. package/src/lib/oauth/providers/claude.js +60 -0
  238. package/src/lib/oauth/providers/cline.js +62 -0
  239. package/src/lib/oauth/providers/clinepass.js +62 -0
  240. package/src/lib/oauth/providers/codebuddy-cn.js +75 -0
  241. package/src/lib/oauth/providers/codebuddy-intl.js +73 -0
  242. package/src/lib/oauth/providers/codex.js +72 -0
  243. package/src/lib/oauth/providers/cursor.js +18 -0
  244. package/src/lib/oauth/providers/gemini-cli.js +84 -0
  245. package/src/lib/oauth/providers/github.js +96 -0
  246. package/src/lib/oauth/providers/grok-cli.js +123 -0
  247. package/src/lib/oauth/providers/index.js +233 -0
  248. package/src/lib/oauth/providers/kilocode.js +60 -0
  249. package/src/lib/oauth/providers/kimchi.js +79 -0
  250. package/src/lib/oauth/providers/kimi.js +79 -0
  251. package/src/lib/oauth/providers/kiro.js +147 -0
  252. package/src/lib/oauth/providers/qoder.js +90 -0
  253. package/src/lib/oauth/providers/trae.js +244 -0
  254. package/src/lib/oauth/providers/windsurf.js +123 -0
  255. package/src/lib/oauth/providers/xai.js +95 -0
  256. package/src/lib/oauth/providers.js +16 -0
  257. package/src/lib/oauth/services/cursor.js +132 -0
  258. package/src/lib/oauth/services/kiro.js +351 -0
  259. package/src/lib/oauth/services/oauth.js +135 -0
  260. package/src/lib/oauth/services/qoder.js +151 -0
  261. package/src/lib/oauth/services/xai.js +204 -0
  262. package/src/lib/oauth/utils/ideDetect.js +55 -0
  263. package/src/lib/oauth/utils/pkce.js +25 -0
  264. package/src/lib/oauth/utils/server.js +732 -0
  265. package/src/lib/oauth/utils/ui.js +43 -0
  266. package/src/lib/providerNormalization.js +40 -0
  267. package/src/lib/qoder/constants.js +1 -0
  268. package/src/lib/requestDetailsDb.js +3 -0
  269. package/src/lib/resourceProfile.ts +124 -0
  270. package/src/lib/runtimeSecrets.ts +130 -0
  271. package/src/lib/security/payloadCapture.js +87 -0
  272. package/src/lib/tunnel/cloudflare/cloudflared.js +436 -0
  273. package/src/lib/tunnel/cloudflare/config.js +8 -0
  274. package/src/lib/tunnel/cloudflare/healthCheck.js +37 -0
  275. package/src/lib/tunnel/cloudflare/manager.js +149 -0
  276. package/src/lib/tunnel/cloudflare/pid.js +31 -0
  277. package/src/lib/tunnel/cloudflare/publicUrl.js +41 -0
  278. package/src/lib/tunnel/cloudflare/requirements.js +12 -0
  279. package/src/lib/tunnel/index.js +26 -0
  280. package/src/lib/tunnel/shared/dnsResolver.js +16 -0
  281. package/src/lib/tunnel/shared/internetCheck.js +30 -0
  282. package/src/lib/tunnel/shared/state.js +45 -0
  283. package/src/lib/tunnel/shared/watchdogConfig.js +6 -0
  284. package/src/lib/update/installer.js +52 -0
  285. package/src/lib/update/version.js +116 -0
  286. package/src/lib/usageDb.js +6 -0
  287. package/src/lib/usageRefresh.js +88 -0
  288. package/src/lifecycle/appLifecycle.ts +99 -0
  289. package/src/models.js +36 -0
  290. package/src/next/headers.js +12 -0
  291. package/src/next/server.js +74 -0
  292. package/src/observability/metrics.js +439 -0
  293. package/src/observability/tracing.js +107 -0
  294. package/src/open-sse-index.js +70 -0
  295. package/src/providers/capabilities.js +299 -0
  296. package/src/providers/display.ts +142 -0
  297. package/src/providers/index.js +27 -0
  298. package/src/providers/models/helpers.js +19 -0
  299. package/src/providers/models/namePatterns.js +27 -0
  300. package/src/providers/models/schema.js +32 -0
  301. package/src/providers/pricing.js +248 -0
  302. package/src/providers/registry/agentrouter.js +52 -0
  303. package/src/providers/registry/alicode-intl.js +32 -0
  304. package/src/providers/registry/alicode.js +33 -0
  305. package/src/providers/registry/alims-intl.js +30 -0
  306. package/src/providers/registry/anthropic.js +29 -0
  307. package/src/providers/registry/antigravity.js +139 -0
  308. package/src/providers/registry/azure.js +23 -0
  309. package/src/providers/registry/baidu.js +35 -0
  310. package/src/providers/registry/blackbox.js +41 -0
  311. package/src/providers/registry/byteplus.js +36 -0
  312. package/src/providers/registry/cerebras.js +33 -0
  313. package/src/providers/registry/chutes.js +26 -0
  314. package/src/providers/registry/claude.js +80 -0
  315. package/src/providers/registry/cline.js +53 -0
  316. package/src/providers/registry/clinepass.js +62 -0
  317. package/src/providers/registry/cloudflare-ai.js +84 -0
  318. package/src/providers/registry/codebuddy-cn.js +95 -0
  319. package/src/providers/registry/codebuddy-intl.js +91 -0
  320. package/src/providers/registry/codex.js +145 -0
  321. package/src/providers/registry/commandcode.js +45 -0
  322. package/src/providers/registry/cursor.js +61 -0
  323. package/src/providers/registry/deepseek.js +55 -0
  324. package/src/providers/registry/featherless.js +36 -0
  325. package/src/providers/registry/fireworks.js +34 -0
  326. package/src/providers/registry/gemini-cli.js +59 -0
  327. package/src/providers/registry/gemini.js +76 -0
  328. package/src/providers/registry/github.js +131 -0
  329. package/src/providers/registry/glm-cn.js +35 -0
  330. package/src/providers/registry/glm.js +58 -0
  331. package/src/providers/registry/grok-cli.js +87 -0
  332. package/src/providers/registry/grok-web.js +41 -0
  333. package/src/providers/registry/groq.js +38 -0
  334. package/src/providers/registry/index.js +77 -0
  335. package/src/providers/registry/kilo-gateway.js +34 -0
  336. package/src/providers/registry/kilocode.js +48 -0
  337. package/src/providers/registry/kimchi.js +49 -0
  338. package/src/providers/registry/kimi.js +82 -0
  339. package/src/providers/registry/kiro.js +132 -0
  340. package/src/providers/registry/meta.js +34 -0
  341. package/src/providers/registry/minimax-cn.js +90 -0
  342. package/src/providers/registry/minimax.js +90 -0
  343. package/src/providers/registry/mistral.js +36 -0
  344. package/src/providers/registry/morph.js +31 -0
  345. package/src/providers/registry/nebius.js +26 -0
  346. package/src/providers/registry/nvidia.js +55 -0
  347. package/src/providers/registry/ollama-local.js +18 -0
  348. package/src/providers/registry/ollama.js +38 -0
  349. package/src/providers/registry/openai.js +114 -0
  350. package/src/providers/registry/opencode-go.js +41 -0
  351. package/src/providers/registry/opencode.js +26 -0
  352. package/src/providers/registry/openrouter.js +36 -0
  353. package/src/providers/registry/perplexity.js +56 -0
  354. package/src/providers/registry/poolside.js +30 -0
  355. package/src/providers/registry/qoder.js +58 -0
  356. package/src/providers/registry/sumopod.js +84 -0
  357. package/src/providers/registry/tencent.js +29 -0
  358. package/src/providers/registry/together.js +38 -0
  359. package/src/providers/registry/trae.js +71 -0
  360. package/src/providers/registry/venice.js +69 -0
  361. package/src/providers/registry/vercel-ai-gateway.js +37 -0
  362. package/src/providers/registry/vertex-partner.js +31 -0
  363. package/src/providers/registry/vertex.js +33 -0
  364. package/src/providers/registry/windsurf.js +129 -0
  365. package/src/providers/registry/xai.js +46 -0
  366. package/src/providers/registry/xiaomi-mimo.js +66 -0
  367. package/src/providers/registry/xiaomi-tokenplan.js +58 -0
  368. package/src/providers/registryEntry.js +3 -0
  369. package/src/providers/schema.js +33 -0
  370. package/src/providers/shared.js +114 -0
  371. package/src/providers/thinkingLevels.js +49 -0
  372. package/src/routes/api/auth/login/route.js +82 -0
  373. package/src/routes/api/auth/logout/route.js +9 -0
  374. package/src/routes/api/auth/reset-password/route.js +12 -0
  375. package/src/routes/api/auth/status/route.js +33 -0
  376. package/src/routes/api/auth/verify-password/route.js +39 -0
  377. package/src/routes/api/chat/tools/curl/route.js +100 -0
  378. package/src/routes/api/chat/tools/router/route.js +215 -0
  379. package/src/routes/api/chat/tools/search/route.js +362 -0
  380. package/src/routes/api/chat/tools/shell/route.js +228 -0
  381. package/src/routes/api/cli-tools/all-statuses/route.js +37 -0
  382. package/src/routes/api/cli-tools/claude-settings/route.js +261 -0
  383. package/src/routes/api/cli-tools/codex-settings/route.js +220 -0
  384. package/src/routes/api/cli-tools/cowork-mcp-registry/route.js +80 -0
  385. package/src/routes/api/cli-tools/cowork-mcp-tools/route.js +96 -0
  386. package/src/routes/api/cli-tools/cowork-settings/route.js +380 -0
  387. package/src/routes/api/cli-tools/grok-build-settings/route.js +152 -0
  388. package/src/routes/api/cli-tools/hermes-settings/route.js +169 -0
  389. package/src/routes/api/cli-tools/kilo-settings/route.js +131 -0
  390. package/src/routes/api/cli-tools/model-mappings/route.js +43 -0
  391. package/src/routes/api/cli-tools/omp-settings/route.js +266 -0
  392. package/src/routes/api/cli-tools/opencode-settings/route.js +243 -0
  393. package/src/routes/api/combos/[id]/route.js +73 -0
  394. package/src/routes/api/combos/route.js +43 -0
  395. package/src/routes/api/health/live/route.js +7 -0
  396. package/src/routes/api/health/ready/route.js +19 -0
  397. package/src/routes/api/health/route.js +17 -0
  398. package/src/routes/api/inflight/stream/route.js +24 -0
  399. package/src/routes/api/init/route.js +3 -0
  400. package/src/routes/api/keys/[id]/route.js +71 -0
  401. package/src/routes/api/keys/route.js +41 -0
  402. package/src/routes/api/logs/route.js +19 -0
  403. package/src/routes/api/mcp/[plugin]/message/route.js +23 -0
  404. package/src/routes/api/mcp/[plugin]/sse/route.js +35 -0
  405. package/src/routes/api/models/availability/route.js +104 -0
  406. package/src/routes/api/models/custom/route.js +58 -0
  407. package/src/routes/api/models/disabled/route.js +47 -0
  408. package/src/routes/api/models/route.js +64 -0
  409. package/src/routes/api/models/test/ping.js +236 -0
  410. package/src/routes/api/models/test/route.js +14 -0
  411. package/src/routes/api/oauth/[provider]/[action]/route.js +491 -0
  412. package/src/routes/api/oauth/codex/bulk-import/route.js +105 -0
  413. package/src/routes/api/oauth/codex/import-token/route.js +82 -0
  414. package/src/routes/api/oauth/cursor/auto-import/route.js +250 -0
  415. package/src/routes/api/oauth/cursor/import/route.js +86 -0
  416. package/src/routes/api/oauth/kiro/api-key/route.js +60 -0
  417. package/src/routes/api/oauth/kiro/auto-import/route.js +120 -0
  418. package/src/routes/api/oauth/kiro/import/route.js +72 -0
  419. package/src/routes/api/oauth/kiro/import-cli-proxy/route.js +42 -0
  420. package/src/routes/api/oauth/kiro/social-authorize/route.js +40 -0
  421. package/src/routes/api/oauth/kiro/social-exchange/route.js +62 -0
  422. package/src/routes/api/pricing/route.js +96 -0
  423. package/src/routes/api/provider-nodes/[id]/route.js +106 -0
  424. package/src/routes/api/provider-nodes/route.js +110 -0
  425. package/src/routes/api/provider-nodes/validate/route.js +197 -0
  426. package/src/routes/api/providers/[id]/models/route.js +716 -0
  427. package/src/routes/api/providers/[id]/route.js +195 -0
  428. package/src/routes/api/providers/[id]/test/route.js +27 -0
  429. package/src/routes/api/providers/[id]/test/testUtils.js +912 -0
  430. package/src/routes/api/providers/[id]/test-models/route.js +211 -0
  431. package/src/routes/api/providers/catalog/route.js +58 -0
  432. package/src/routes/api/providers/client/route.js +133 -0
  433. package/src/routes/api/providers/counts/route.js +43 -0
  434. package/src/routes/api/providers/kilo/free-models/route.js +58 -0
  435. package/src/routes/api/providers/route.js +361 -0
  436. package/src/routes/api/providers/suggested-models/filters.js +24 -0
  437. package/src/routes/api/providers/suggested-models/route.js +34 -0
  438. package/src/routes/api/providers/test-batch/route.js +145 -0
  439. package/src/routes/api/providers/validate/route.js +633 -0
  440. package/src/routes/api/proxy-pools/[id]/route.js +129 -0
  441. package/src/routes/api/proxy-pools/[id]/test/route.js +64 -0
  442. package/src/routes/api/proxy-pools/cloudflare-deploy/route.js +183 -0
  443. package/src/routes/api/proxy-pools/route.js +85 -0
  444. package/src/routes/api/proxy-pools/vercel-deploy/route.js +181 -0
  445. package/src/routes/api/settings/currency/route.js +29 -0
  446. package/src/routes/api/settings/database/path/route.js +8 -0
  447. package/src/routes/api/settings/database/route.js +89 -0
  448. package/src/routes/api/settings/migrate-9router/route.js +81 -0
  449. package/src/routes/api/settings/require-login/route.js +14 -0
  450. package/src/routes/api/settings/route.js +186 -0
  451. package/src/routes/api/shutdown/route.js +25 -0
  452. package/src/routes/api/tags/route.js +17 -0
  453. package/src/routes/api/translator/console-logs/route.js +28 -0
  454. package/src/routes/api/translator/console-logs/stream/route.js +95 -0
  455. package/src/routes/api/tunnel/disable/route.js +18 -0
  456. package/src/routes/api/tunnel/enable/route.js +32 -0
  457. package/src/routes/api/tunnel/status/route.js +23 -0
  458. package/src/routes/api/update/route.js +42 -0
  459. package/src/routes/api/usage/[connectionId]/codex-reset-credits/route.js +169 -0
  460. package/src/routes/api/usage/[connectionId]/route.js +222 -0
  461. package/src/routes/api/usage/chart/route.js +27 -0
  462. package/src/routes/api/usage/history/route.js +94 -0
  463. package/src/routes/api/usage/logs/route.js +14 -0
  464. package/src/routes/api/usage/providers/route.js +36 -0
  465. package/src/routes/api/usage/request-details/route.js +61 -0
  466. package/src/routes/api/usage/request-logs/route.js +15 -0
  467. package/src/routes/api/usage/stats/route.js +23 -0
  468. package/src/routes/api/usage/stream/route.js +78 -0
  469. package/src/routes/api/v1/api/chat/route.js +36 -0
  470. package/src/routes/api/v1/chat/completions/route.js +28 -0
  471. package/src/routes/api/v1/images/edits/route.js +70 -0
  472. package/src/routes/api/v1/images/generations/route.js +50 -0
  473. package/src/routes/api/v1/images/imageValidation.js +45 -0
  474. package/src/routes/api/v1/messages/count_tokens/route.js +87 -0
  475. package/src/routes/api/v1/messages/route.js +26 -0
  476. package/src/routes/api/v1/models/route.js +440 -0
  477. package/src/routes/api/v1/responses/compact/route.js +34 -0
  478. package/src/routes/api/v1/responses/route.js +26 -0
  479. package/src/routes/api/v1/route.js +1 -0
  480. package/src/routes/api/version/route.js +11 -0
  481. package/src/routes/table.js +1141 -0
  482. package/src/rtk/applyFilter.js +13 -0
  483. package/src/rtk/autodetect.js +104 -0
  484. package/src/rtk/caveman.js +6 -0
  485. package/src/rtk/cavemanPrompts.js +107 -0
  486. package/src/rtk/constants.js +51 -0
  487. package/src/rtk/filters/buildOutput.js +120 -0
  488. package/src/rtk/filters/dedupLog.js +43 -0
  489. package/src/rtk/filters/find.js +47 -0
  490. package/src/rtk/filters/gitDiff.js +90 -0
  491. package/src/rtk/filters/gitLog.js +88 -0
  492. package/src/rtk/filters/gitStatus.js +101 -0
  493. package/src/rtk/filters/grep.js +45 -0
  494. package/src/rtk/filters/ls.js +73 -0
  495. package/src/rtk/filters/readNumbered.js +22 -0
  496. package/src/rtk/filters/searchList.js +49 -0
  497. package/src/rtk/filters/smartTruncate.js +13 -0
  498. package/src/rtk/filters/tree.js +28 -0
  499. package/src/rtk/index.js +143 -0
  500. package/src/rtk/ponytail.js +6 -0
  501. package/src/rtk/ponytailPrompt.js +49 -0
  502. package/src/rtk/systemInject.js +89 -0
  503. package/src/server.ts +474 -0
  504. package/src/services/accountFallback.js +241 -0
  505. package/src/services/accountPool.js +389 -0
  506. package/src/services/capacityAdapter.js +140 -0
  507. package/src/services/cliModelMapping.js +84 -0
  508. package/src/services/clinepassModels.js +60 -0
  509. package/src/services/codebuddyModels.js +250 -0
  510. package/src/services/combo.js +482 -0
  511. package/src/services/copilotModels.js +126 -0
  512. package/src/services/currencyRate.js +56 -0
  513. package/src/services/cursorModels.js +197 -0
  514. package/src/services/grokCliModels.js +130 -0
  515. package/src/services/kimchiModels.js +175 -0
  516. package/src/services/kiroModels.js +246 -0
  517. package/src/services/model.js +83 -0
  518. package/src/services/oauthCredentialManager.js +153 -0
  519. package/src/services/projectId.js +240 -0
  520. package/src/services/provider.js +145 -0
  521. package/src/services/qoderModels.js +274 -0
  522. package/src/services/tokenRefresh/dedup.js +70 -0
  523. package/src/services/tokenRefresh/providers.js +626 -0
  524. package/src/services/tokenRefresh.js +274 -0
  525. package/src/services/usage/claude.js +134 -0
  526. package/src/services/usage/codebuddy-cn.js +212 -0
  527. package/src/services/usage/codex.js +193 -0
  528. package/src/services/usage/deepseek.js +103 -0
  529. package/src/services/usage/github.js +94 -0
  530. package/src/services/usage/google.js +218 -0
  531. package/src/services/usage/grok-cli.js +368 -0
  532. package/src/services/usage/grokCliQuotaFrame.js +170 -0
  533. package/src/services/usage/kimi.js +185 -0
  534. package/src/services/usage/kiro.js +172 -0
  535. package/src/services/usage/minimax.js +215 -0
  536. package/src/services/usage/misc.js +264 -0
  537. package/src/services/usage/shared.js +59 -0
  538. package/src/services/usage.js +56 -0
  539. package/src/shared/clineAuth.js +37 -0
  540. package/src/shared/constants/config.js +80 -0
  541. package/src/shared/constants/coworkPlugins.js +69 -0
  542. package/src/shared/constants/models.js +41 -0
  543. package/src/shared/constants/providers.js +128 -0
  544. package/src/shared/constants/providersDisplay.js +1 -0
  545. package/src/shared/qoder/constants.js +50 -0
  546. package/src/shared/qoder/cosy.js +134 -0
  547. package/src/shared/qoder/encoding.js +36 -0
  548. package/src/shared/services/initializeApp.js +226 -0
  549. package/src/shared/services/quotaAutoPing.js +310 -0
  550. package/src/shared/utils/apiKey.js +65 -0
  551. package/src/shared/utils/clineAuth.js +1 -0
  552. package/src/shared/utils/index.js +3 -0
  553. package/src/shared/utils/machineId.js +60 -0
  554. package/src/shared/utils/ssrfGuard.js +280 -0
  555. package/src/sse/handlers/chat.js +426 -0
  556. package/src/sse/oauthLease.js +32 -0
  557. package/src/sse/recovery.js +235 -0
  558. package/src/sse/services/auth.js +489 -0
  559. package/src/sse/services/backgroundTokenRefresh.js +173 -0
  560. package/src/sse/services/model.js +129 -0
  561. package/src/sse/services/requestCancellation.js +4 -0
  562. package/src/sse/services/tokenRefresh.js +264 -0
  563. package/src/sse/utils/logger.js +142 -0
  564. package/src/staticServe.ts +95 -0
  565. package/src/transformer/streamToJsonConverter.js +87 -0
  566. package/src/translator/canonical.js +81 -0
  567. package/src/translator/concerns/chunk.js +9 -0
  568. package/src/translator/concerns/compatFallback.js +147 -0
  569. package/src/translator/concerns/finishReason.js +59 -0
  570. package/src/translator/concerns/image.js +105 -0
  571. package/src/translator/concerns/json.js +4 -0
  572. package/src/translator/concerns/kiroConversation.js +428 -0
  573. package/src/translator/concerns/message.js +5 -0
  574. package/src/translator/concerns/modality.js +134 -0
  575. package/src/translator/concerns/paramSupport.js +97 -0
  576. package/src/translator/concerns/prefetch.js +86 -0
  577. package/src/translator/concerns/reasoning.js +18 -0
  578. package/src/translator/concerns/thinking.js +40 -0
  579. package/src/translator/concerns/thinkingUnified.js +319 -0
  580. package/src/translator/concerns/toolCall.js +134 -0
  581. package/src/translator/concerns/usage.js +61 -0
  582. package/src/translator/detection.js +42 -0
  583. package/src/translator/formats/claude.js +323 -0
  584. package/src/translator/formats/gemini.js +366 -0
  585. package/src/translator/formats/maxTokens.js +19 -0
  586. package/src/translator/formats/openai.js +116 -0
  587. package/src/translator/formats/responsesApi.js +117 -0
  588. package/src/translator/formats.js +28 -0
  589. package/src/translator/index.js +237 -0
  590. package/src/translator/request/antigravity-to-openai.js +217 -0
  591. package/src/translator/request/claude-to-kiro.js +288 -0
  592. package/src/translator/request/claude-to-openai.js +199 -0
  593. package/src/translator/request/gemini-to-openai.js +142 -0
  594. package/src/translator/request/openai-responses.js +373 -0
  595. package/src/translator/request/openai-to-claude.js +260 -0
  596. package/src/translator/request/openai-to-commandcode.js +161 -0
  597. package/src/translator/request/openai-to-cursor.js +175 -0
  598. package/src/translator/request/openai-to-gemini.js +422 -0
  599. package/src/translator/request/openai-to-kiro.js +360 -0
  600. package/src/translator/request/openai-to-ollama.js +152 -0
  601. package/src/translator/request/openai-to-vertex.js +36 -0
  602. package/src/translator/response/claude-to-openai.js +185 -0
  603. package/src/translator/response/commandcode-to-openai.js +164 -0
  604. package/src/translator/response/cursor-to-openai.js +18 -0
  605. package/src/translator/response/gemini-to-openai.js +127 -0
  606. package/src/translator/response/kiro-to-claude.js +230 -0
  607. package/src/translator/response/kiro-to-openai.js +136 -0
  608. package/src/translator/response/ollama-to-openai.js +106 -0
  609. package/src/translator/response/openai-responses.js +534 -0
  610. package/src/translator/response/openai-to-antigravity.js +107 -0
  611. package/src/translator/response/openai-to-claude.js +231 -0
  612. package/src/translator/schema/blocks.js +40 -0
  613. package/src/translator/schema/defaults.js +3 -0
  614. package/src/translator/schema/finishReasons.js +22 -0
  615. package/src/translator/schema/index.js +7 -0
  616. package/src/translator/schema/roles.js +12 -0
  617. package/src/transport/requestBoundary.ts +223 -0
  618. package/src/transport/routerAdmission.ts +380 -0
  619. package/src/types/provider.ts +59 -0
  620. package/src/utils/bypassHandler.js +272 -0
  621. package/src/utils/claudeCloaking.js +10 -0
  622. package/src/utils/claudeSignature.js +35 -0
  623. package/src/utils/clientDetector.js +183 -0
  624. package/src/utils/cursorChecksum.js +104 -0
  625. package/src/utils/cursorProtobuf.js +801 -0
  626. package/src/utils/debugLog.js +12 -0
  627. package/src/utils/error.js +120 -0
  628. package/src/utils/inflight.js +127 -0
  629. package/src/utils/kiroSessionReplay.js +139 -0
  630. package/src/utils/ollamaTransform.js +83 -0
  631. package/src/utils/proxyFetch.js +308 -0
  632. package/src/utils/reasoningContentInjector.js +71 -0
  633. package/src/utils/requestLogger.js +272 -0
  634. package/src/utils/responsesStreamHelpers.js +46 -0
  635. package/src/utils/sessionManager.js +205 -0
  636. package/src/utils/sse.js +13 -0
  637. package/src/utils/sseConstants.js +21 -0
  638. package/src/utils/stream.js +511 -0
  639. package/src/utils/streamHandler.js +256 -0
  640. package/src/utils/streamHelpers.js +113 -0
  641. package/src/utils/toolDeduper.js +44 -0
  642. package/src/utils/usageTracking.js +329 -0
  643. package/tsconfig.json +45 -0
@@ -0,0 +1,912 @@
1
+ import { getProviderConnectionById, updateProviderConnection } from "@/lib/localDb";
2
+ import { resolveConnectionProxyConfig } from "@/lib/network/connectionProxy";
3
+ import { testProxyUrl } from "@/lib/network/proxyTest";
4
+ import { isOpenAICompatibleProvider, isAnthropicCompatibleProvider } from "@/shared/constants/providers";
5
+ import { getDefaultModel } from "open-sse/config/providerModels.js";
6
+ import { resolveOllamaLocalHost, PROVIDERS } from "open-sse/config/providers.js";
7
+ import {
8
+ refreshProviderCredentials,
9
+ shouldRefreshCredentials,
10
+ } from "open-sse/services/oauthCredentialManager.js";
11
+ import {
12
+ refreshCodebuddyToken,
13
+ refreshCodebuddyIntlToken,
14
+ } from "@/services/tokenRefresh/providers.js";
15
+ import {
16
+ GEMINI_CONFIG,
17
+ ANTIGRAVITY_CONFIG,
18
+ KIRO_CONFIG,
19
+ CLAUDE_CONFIG,
20
+ CLINE_CONFIG,
21
+ KILOCODE_CONFIG,
22
+ KIMCHI_CONFIG,
23
+ } from "@/lib/oauth/constants/oauth";
24
+ import { buildClineHeaders } from "@/shared/utils/clineAuth";
25
+ import { AGENTROUTER_MODELS_URL, AGENTROUTER_OPENAI_HEADERS } from "open-sse/providers/shared.js";
26
+ import { buildCodeBuddyModelHeaders } from "@/services/codebuddyModels.js";
27
+
28
+ const OAUTH_TEST_CONFIG = {
29
+ claude: { checkExpiry: true, refreshable: true },
30
+ codex: {
31
+ url: "https://chatgpt.com/backend-api/codex/responses",
32
+ method: "POST",
33
+ authHeader: "Authorization",
34
+ authPrefix: "Bearer ",
35
+ extraHeaders: { "Content-Type": "application/json", "originator": "codex_cli_rs", "User-Agent": "codex_cli_rs/0.136.0" },
36
+
37
+ body: JSON.stringify({ model: "gpt-5.3-codex", input: [], stream: false, store: false }),
38
+
39
+ acceptStatuses: [400],
40
+ refreshable: true,
41
+ },
42
+ "gemini-cli": {
43
+ url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
44
+ method: "GET",
45
+ authHeader: "Authorization",
46
+ authPrefix: "Bearer ",
47
+ refreshable: true,
48
+ },
49
+ antigravity: {
50
+ url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
51
+ method: "GET",
52
+ authHeader: "Authorization",
53
+ authPrefix: "Bearer ",
54
+ refreshable: true,
55
+ },
56
+ github: {
57
+ url: "https://api.github.com/user",
58
+ method: "GET",
59
+ authHeader: "Authorization",
60
+ authPrefix: "Bearer ",
61
+ extraHeaders: { "User-Agent": "SwayRouter", "Accept": "application/vnd.github+json" },
62
+ },
63
+ kiro: { checkExpiry: true, refreshable: true },
64
+ qoder: {
65
+
66
+ url: "https://openapi.qoder.sh/api/v1/userinfo",
67
+ method: "GET",
68
+ authHeader: "Authorization",
69
+ authPrefix: "Bearer ",
70
+ refreshable: false,
71
+ },
72
+ kimi: { checkExpiry: true, refreshable: true },
73
+ "kimi-coding": { checkExpiry: true, refreshable: true },
74
+ cursor: { tokenExists: true },
75
+ kilocode: {
76
+ url: `${KILOCODE_CONFIG.apiBaseUrl}/api/profile`,
77
+ method: "GET",
78
+ authHeader: "Authorization",
79
+ authPrefix: "Bearer ",
80
+ },
81
+ cline: { refreshable: true },
82
+ gitlab: {
83
+
84
+ url: "https://gitlab.com/api/v4/user",
85
+ method: "GET",
86
+ authHeader: "Authorization",
87
+ authPrefix: "Bearer ",
88
+ },
89
+ "codebuddy-cn": {
90
+ url: "https://copilot.tencent.com/v3/config",
91
+ method: "GET",
92
+ buildHeaders: (accessToken) => buildCodeBuddyModelHeaders("codebuddy-cn", accessToken),
93
+ refreshable: true,
94
+ },
95
+ "codebuddy-intl": {
96
+ url: "https://www.codebuddy.ai/v3/config",
97
+ method: "GET",
98
+ buildHeaders: (accessToken) => buildCodeBuddyModelHeaders("codebuddy-intl", accessToken),
99
+ refreshable: true,
100
+ },
101
+ kimchi: {
102
+ url: KIMCHI_CONFIG.validationUrl || "https://api.cast.ai/v1/llm/openai/supported-providers",
103
+ method: "GET",
104
+ authHeader: "Authorization",
105
+ authPrefix: "Bearer ",
106
+ extraHeaders: {
107
+ Accept: "application/json",
108
+ "User-Agent": "kimchi/0.1.40",
109
+ },
110
+ refreshable: false,
111
+ },
112
+
113
+ "grok-cli": {
114
+ url: PROVIDERS["grok-cli"]?.userUrl || "https://cli-chat-proxy.grok.com/v1/user",
115
+ method: "GET",
116
+ authHeader: "Authorization",
117
+ authPrefix: "Bearer ",
118
+ extraHeaders: {
119
+ Accept: "application/json",
120
+ ...(PROVIDERS["grok-cli"]?.headers || {
121
+ "User-Agent": "grok-pager/0.2.93 grok-shell/0.2.93 (linux; x86_64)",
122
+ "x-xai-token-auth": "xai-grok-cli",
123
+ "x-grok-client-identifier": "grok-pager",
124
+ "x-grok-client-version": "0.2.93",
125
+ }),
126
+ },
127
+ refreshable: true,
128
+
129
+ acceptStatuses: [402],
130
+ softFailMessage: {
131
+ 402: "Connected, but Grok Build credits are exhausted (spending limit). Add credits or upgrade SuperGrok.",
132
+ },
133
+ },
134
+ };
135
+
136
+ export function classifyOAuthProbeResult(res, config, bodyText = "") {
137
+ if (!res) return { valid: false, error: "No response", soft: false };
138
+ const status = res.status;
139
+ const accepted = res.ok || (config?.acceptStatuses && config.acceptStatuses.includes(status));
140
+ if (!accepted) {
141
+ if (status === 401) return { valid: false, error: "Token invalid or revoked", soft: false };
142
+ if (status === 403) return { valid: false, error: "Access denied", soft: false };
143
+ return { valid: false, error: `API returned ${status}`, soft: false };
144
+ }
145
+
146
+ if (!res.ok && config?.acceptStatuses?.includes(status)) {
147
+ const softMap = config.softFailMessage || {};
148
+ if (softMap[status]) {
149
+ return { valid: true, error: softMap[status], soft: true };
150
+ }
151
+ return { valid: true, error: null, soft: false };
152
+ }
153
+
154
+ return { valid: true, error: null, soft: false };
155
+ }
156
+
157
+ async function probeClineAccessToken(accessToken) {
158
+ const res = await fetch("https://api.cline.bot/api/v1/users/me", {
159
+ method: "GET",
160
+ headers: buildClineHeaders(accessToken, {
161
+ Accept: "application/json",
162
+ }),
163
+ });
164
+
165
+ return res;
166
+ }
167
+
168
+ const CLOUD_CODE_ASSIST_TEST_URL = "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist";
169
+ const CLOUD_CODE_ASSIST_TEST_BODY = JSON.stringify({
170
+ metadata: {
171
+ ideType: "IDE_UNSPECIFIED",
172
+ platform: "PLATFORM_UNSPECIFIED",
173
+ pluginType: "GEMINI",
174
+ },
175
+ });
176
+
177
+ function parseProviderErrorMessage(bodyText, fallback) {
178
+
179
+ return fallback;
180
+ }
181
+
182
+ async function probeCloudCodeAssistAccess(connection, accessToken, effectiveProxy = null) {
183
+ const userAgent = connection.provider === "antigravity"
184
+ ? "google-api-nodejs-client/9.15.1 vscode-antigravity/1.107.0"
185
+ : "google-api-nodejs-client/9.15.1 gemini-cli/0.34.0";
186
+
187
+ const res = await fetchWithConnectionProxy(CLOUD_CODE_ASSIST_TEST_URL, {
188
+ method: "POST",
189
+ headers: {
190
+ "Authorization": `Bearer ${accessToken}`,
191
+ "Content-Type": "application/json",
192
+ "User-Agent": userAgent,
193
+ },
194
+ body: CLOUD_CODE_ASSIST_TEST_BODY,
195
+ }, effectiveProxy);
196
+
197
+ if (res.ok) return { valid: true, error: null };
198
+
199
+ const bodyText = await res.text().catch(() => "");
200
+ return {
201
+ valid: false,
202
+ error: parseProviderErrorMessage(bodyText, `API returned ${res.status}`),
203
+ status: res.status,
204
+ };
205
+ }
206
+
207
+ async function refreshOAuthToken(connection) {
208
+ const provider = connection.provider;
209
+ const refreshToken = connection.refreshToken;
210
+ if (!refreshToken) return null;
211
+
212
+ try {
213
+ if (provider === "gemini-cli" || provider === "antigravity") {
214
+ const config = provider === "gemini-cli" ? GEMINI_CONFIG : ANTIGRAVITY_CONFIG;
215
+ const response = await fetch("https://oauth2.googleapis.com/token", {
216
+ method: "POST",
217
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
218
+ body: new URLSearchParams({
219
+ client_id: config.clientId,
220
+ client_secret: config.clientSecret,
221
+ grant_type: "refresh_token",
222
+ refresh_token: refreshToken,
223
+ }),
224
+ });
225
+ if (!response.ok) return null;
226
+ const data = await response.json();
227
+ return { accessToken: data.access_token, expiresIn: data.expires_in, refreshToken: data.refresh_token || refreshToken };
228
+ }
229
+
230
+ if (provider === "codex" || provider === "grok-cli" || provider === "xai") {
231
+ return await refreshProviderCredentials(provider, connection, console);
232
+ }
233
+
234
+ if (provider === "codebuddy-cn" || provider === "codebuddy-intl") {
235
+ const refreshFn = provider === "codebuddy-cn"
236
+ ? refreshCodebuddyToken
237
+ : refreshCodebuddyIntlToken;
238
+ return await refreshFn(refreshToken, console);
239
+ }
240
+
241
+ if (provider === "claude") {
242
+ const response = await fetch(CLAUDE_CONFIG.tokenUrl, {
243
+ method: "POST",
244
+ headers: { "Content-Type": "application/json", "Accept": "application/json" },
245
+ body: JSON.stringify({
246
+ grant_type: "refresh_token",
247
+ refresh_token: refreshToken,
248
+ client_id: CLAUDE_CONFIG.clientId,
249
+ }),
250
+ });
251
+ if (!response.ok) return null;
252
+ const data = await response.json();
253
+ return { accessToken: data.access_token, expiresIn: data.expires_in, refreshToken: data.refresh_token || refreshToken };
254
+ }
255
+
256
+ if (provider === "kiro") {
257
+ const psd = connection.providerSpecificData || {};
258
+ const clientId = psd.clientId || connection.clientId;
259
+ const clientSecret = psd.clientSecret || connection.clientSecret;
260
+ const region = psd.region || connection.region;
261
+ if (clientId && clientSecret) {
262
+ const endpoint = `https://oidc.${region || "us-east-1"}.amazonaws.com/token`;
263
+ const response = await fetch(endpoint, {
264
+ method: "POST",
265
+ headers: { "Content-Type": "application/json" },
266
+ body: JSON.stringify({ clientId, clientSecret, refreshToken, grantType: "refresh_token" }),
267
+ });
268
+ if (!response.ok) return null;
269
+ const data = await response.json();
270
+ return { accessToken: data.accessToken, expiresIn: data.expiresIn || 3600, refreshToken: data.refreshToken || refreshToken };
271
+ }
272
+ const response = await fetch(KIRO_CONFIG.socialRefreshUrl, {
273
+ method: "POST",
274
+ headers: { "Content-Type": "application/json", "User-Agent": "kiro-cli/1.0.0" },
275
+ body: JSON.stringify({ refreshToken }),
276
+ });
277
+ if (!response.ok) return null;
278
+ const data = await response.json();
279
+ return { accessToken: data.accessToken, expiresIn: data.expiresIn || 3600, refreshToken: data.refreshToken || refreshToken };
280
+ }
281
+
282
+ if (provider === "cline") {
283
+ const response = await fetch(CLINE_CONFIG.refreshUrl, {
284
+ method: "POST",
285
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
286
+ body: JSON.stringify({
287
+ refreshToken,
288
+ grantType: "refresh_token",
289
+ clientType: "extension",
290
+ }),
291
+ });
292
+ if (!response.ok) return null;
293
+ const payload = await response.json();
294
+ const data = payload?.data || payload;
295
+ const expiresIn = data?.expiresAt
296
+ ? Math.max(1, Math.floor((new Date(data.expiresAt).getTime() - Date.now()) / 1000))
297
+ : 3600;
298
+ return {
299
+ accessToken: data?.accessToken,
300
+ expiresIn,
301
+ refreshToken: data?.refreshToken || refreshToken,
302
+ };
303
+ }
304
+
305
+ return null;
306
+ } catch (err) {
307
+ console.log(`Error refreshing ${provider} token:`, err.message);
308
+ return null;
309
+ }
310
+ }
311
+
312
+ function isTokenExpired(connection) {
313
+ return shouldRefreshCredentials(connection.provider, connection);
314
+ }
315
+
316
+ async function testOAuthConnection(connection, effectiveProxy = null) {
317
+ const config = OAUTH_TEST_CONFIG[connection.provider];
318
+ if (!config) return { valid: false, error: "Provider test not supported", refreshed: false };
319
+ if (!connection.accessToken) return { valid: false, error: "No access token", refreshed: false };
320
+
321
+ if (config.tokenExists) {
322
+ return { valid: true, error: null, refreshed: false, newTokens: null };
323
+ }
324
+
325
+ let accessToken = connection.accessToken;
326
+ let refreshed = false;
327
+ let newTokens = null;
328
+
329
+ const tokenExpired = isTokenExpired(connection);
330
+ if (config.refreshable && tokenExpired && connection.refreshToken) {
331
+ const tokens = await refreshOAuthToken(connection);
332
+ if (tokens) {
333
+ accessToken = tokens.accessToken;
334
+ refreshed = true;
335
+ newTokens = tokens;
336
+ } else {
337
+ return { valid: false, error: "Token expired and refresh failed", refreshed: false };
338
+ }
339
+ }
340
+
341
+ if (config.checkExpiry) {
342
+ if (refreshed) return { valid: true, error: null, refreshed, newTokens };
343
+ if (tokenExpired) return { valid: false, error: "Token expired", refreshed: false };
344
+ return { valid: true, error: null, refreshed: false, newTokens: null };
345
+ }
346
+
347
+ if (connection.provider === "gemini-cli" || connection.provider === "antigravity") {
348
+ const initial = await probeCloudCodeAssistAccess(connection, accessToken, effectiveProxy);
349
+ if (initial.valid) return { valid: true, error: null, refreshed, newTokens };
350
+
351
+ if (initial.status === 401 && config.refreshable && !refreshed && connection.refreshToken) {
352
+ const tokens = await refreshOAuthToken(connection);
353
+ if (tokens?.accessToken) {
354
+ const retry = await probeCloudCodeAssistAccess(connection, tokens.accessToken, effectiveProxy);
355
+ if (retry.valid) return { valid: true, error: null, refreshed: true, newTokens: tokens };
356
+ return { valid: false, error: retry.error, refreshed: true, newTokens: tokens };
357
+ }
358
+ return { valid: false, error: "Token invalid or revoked", refreshed: false };
359
+ }
360
+
361
+ return { valid: false, error: initial.error, refreshed };
362
+ }
363
+
364
+ if (connection.provider === "cline") {
365
+ const tryProbe = async (token) => {
366
+ const res = await probeClineAccessToken(token);
367
+ if (res.ok) return { valid: true, error: null, refreshed, newTokens };
368
+ if (res.status === 401) return { valid: false, error: "Token invalid or revoked", refreshed };
369
+ if (res.status === 403) return { valid: false, error: "Access denied", refreshed };
370
+ return { valid: false, error: `API returned ${res.status}`, refreshed };
371
+ };
372
+
373
+ const initial = await tryProbe(accessToken);
374
+ if (initial.valid || initial.error !== "Token invalid or revoked" || !connection.refreshToken) {
375
+ return initial;
376
+ }
377
+
378
+ const tokens = await refreshOAuthToken(connection);
379
+ if (!tokens?.accessToken) {
380
+ return { valid: false, error: "Token invalid or revoked", refreshed: false };
381
+ }
382
+
383
+ refreshed = true;
384
+ newTokens = tokens;
385
+ accessToken = tokens.accessToken;
386
+ return await tryProbe(accessToken);
387
+ }
388
+
389
+ try {
390
+ const testUrl = config.buildUrl ? config.buildUrl(accessToken) : config.url;
391
+ const headers = config.buildHeaders
392
+ ? config.buildHeaders(accessToken)
393
+ : config.noAuth
394
+ ? { ...config.extraHeaders }
395
+ : { [config.authHeader]: `${config.authPrefix}${accessToken}`, ...config.extraHeaders };
396
+ const fetchOpts = { method: config.method, headers };
397
+ if (config.body) fetchOpts.body = config.body;
398
+ const res = await fetchWithConnectionProxy(testUrl, fetchOpts, effectiveProxy);
399
+ const bodyText = !res.ok ? await res.text().catch(() => "") : "";
400
+
401
+ const classified = classifyOAuthProbeResult(res, config, bodyText);
402
+ if (classified.valid) {
403
+ return {
404
+ valid: true,
405
+
406
+ error: classified.soft ? classified.error : null,
407
+ warning: classified.soft ? classified.error : null,
408
+ refreshed,
409
+ newTokens,
410
+ };
411
+ }
412
+
413
+ if (res.status === 401 && config.refreshable && !refreshed && connection.refreshToken) {
414
+ const tokens = await refreshOAuthToken(connection);
415
+ if (tokens) {
416
+ const retryUrl = config.buildUrl ? config.buildUrl(tokens.accessToken) : testUrl;
417
+ const retryHeaders = config.buildHeaders
418
+ ? config.buildHeaders(tokens.accessToken)
419
+ : config.noAuth
420
+ ? { ...config.extraHeaders }
421
+ : { [config.authHeader]: `${config.authPrefix}${tokens.accessToken}`, ...config.extraHeaders };
422
+ const retryOpts = { method: config.method, headers: retryHeaders };
423
+ if (config.body) retryOpts.body = config.body;
424
+ const retryRes = await fetchWithConnectionProxy(retryUrl, retryOpts, effectiveProxy);
425
+ const retryBody = !retryRes.ok ? await retryRes.text().catch(() => "") : "";
426
+ const retryClassified = classifyOAuthProbeResult(retryRes, config, retryBody);
427
+ if (retryClassified.valid) {
428
+ return {
429
+ valid: true,
430
+ error: retryClassified.soft ? retryClassified.error : null,
431
+ warning: retryClassified.soft ? retryClassified.error : null,
432
+ refreshed: true,
433
+ newTokens: tokens,
434
+ };
435
+ }
436
+ }
437
+ return { valid: false, error: "Token invalid or revoked", refreshed: false };
438
+ }
439
+
440
+ return { valid: false, error: classified.error, refreshed };
441
+ } catch (err) {
442
+ console.error("[ProviderConnectionTest] OAuth probe failed:", err);
443
+ return { valid: false, error: "Provider connection test failed", refreshed };
444
+ }
445
+ }
446
+
447
+ async function fetchWithConnectionProxy(url, options = {}, effectiveProxy = null) {
448
+
449
+ if (effectiveProxy?.relayUrl || effectiveProxy?.vercelRelayUrl) {
450
+ const { proxyAwareFetch } = await import("open-sse/utils/proxyFetch.js");
451
+ return proxyAwareFetch(url, options, {
452
+ relayUrl: effectiveProxy.relayUrl || "",
453
+ relayToken: effectiveProxy.relayToken || "",
454
+ vercelRelayUrl: effectiveProxy.vercelRelayUrl,
455
+ connectionNoProxy: effectiveProxy.connectionNoProxy || "",
456
+ strictProxy: effectiveProxy.strictProxy === true,
457
+ proxyPoolUnavailable: effectiveProxy.proxyPoolUnavailable === true,
458
+ proxyPoolError: effectiveProxy.proxyPoolError || "",
459
+ });
460
+ }
461
+
462
+ if (
463
+ (!effectiveProxy?.connectionProxyEnabled || !effectiveProxy?.connectionProxyUrl) &&
464
+ !(effectiveProxy?.proxyPoolUnavailable && effectiveProxy?.strictProxy)
465
+ ) {
466
+ return fetch(url, options);
467
+ }
468
+
469
+ const { proxyAwareFetch } = await import("open-sse/utils/proxyFetch.js");
470
+ return proxyAwareFetch(url, options, {
471
+ connectionProxyEnabled: true,
472
+ connectionProxyUrl: effectiveProxy.connectionProxyUrl,
473
+ connectionNoProxy: effectiveProxy.connectionNoProxy || "",
474
+ strictProxy: effectiveProxy.strictProxy === true,
475
+ proxyPoolUnavailable: effectiveProxy.proxyPoolUnavailable === true,
476
+ proxyPoolError: effectiveProxy.proxyPoolError || "",
477
+ });
478
+ }
479
+
480
+ async function testApiKeyConnection(connection, effectiveProxy = null) {
481
+ if (connection.provider === "agentrouter") {
482
+ try {
483
+ const res = await fetchWithConnectionProxy(AGENTROUTER_MODELS_URL, {
484
+ headers: {
485
+ ...AGENTROUTER_OPENAI_HEADERS,
486
+ "Authorization": `Bearer ${connection.apiKey}`,
487
+ },
488
+ }, effectiveProxy);
489
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
490
+ } catch (err) {
491
+ console.error("[ProviderConnectionTest] AgentRouter probe failed:", err);
492
+ return { valid: false, error: "Provider connection test failed" };
493
+ }
494
+ }
495
+
496
+ if (isOpenAICompatibleProvider(connection.provider)) {
497
+ const modelsBase = connection.providerSpecificData?.baseUrl
498
+ || PROVIDERS[connection.provider]?.baseUrl?.replace(/\/chat\/completions\/?$/i, "");
499
+ if (!modelsBase) return { valid: false, error: "Missing base URL" };
500
+ try {
501
+ const res = await fetchWithConnectionProxy(`${modelsBase.replace(/\/$/, "")}/models`, {
502
+ headers: { "Authorization": `Bearer ${connection.apiKey}` },
503
+ }, effectiveProxy);
504
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key or base URL" };
505
+ } catch (err) {
506
+ console.error("[ProviderConnectionTest] OpenAI-compatible probe failed:", err);
507
+ return { valid: false, error: "Provider connection test failed" };
508
+ }
509
+ }
510
+
511
+ if (isAnthropicCompatibleProvider(connection.provider)) {
512
+ let modelsBase = connection.providerSpecificData?.baseUrl;
513
+ if (!modelsBase) return { valid: false, error: "Missing base URL" };
514
+ try {
515
+ modelsBase = modelsBase.replace(/\/$/, "");
516
+ if (modelsBase.endsWith("/messages")) modelsBase = modelsBase.slice(0, -9);
517
+ const messagesUrl = `${modelsBase}/v1/messages`;
518
+ const model = connection.defaultModel || "claude-3-haiku-20240307";
519
+ const res = await fetchWithConnectionProxy(messagesUrl, {
520
+ method: "POST",
521
+ headers: {
522
+ "x-api-key": connection.apiKey,
523
+ "anthropic-version": "2023-06-01",
524
+ "content-type": "application/json",
525
+ "Authorization": `Bearer ${connection.apiKey}`,
526
+ },
527
+ body: JSON.stringify({
528
+ model,
529
+ max_tokens: 1,
530
+ messages: [{ role: "user", content: "test" }],
531
+ }),
532
+ }, effectiveProxy);
533
+
534
+ const valid = res.status !== 401 && res.status !== 403;
535
+ return { valid, error: valid ? null : "Invalid API key or base URL" };
536
+ } catch (err) {
537
+ console.error("[ProviderConnectionTest] Anthropic-compatible probe failed:", err);
538
+ return { valid: false, error: "Provider connection test failed" };
539
+ }
540
+ }
541
+
542
+ try {
543
+ switch (connection.provider) {
544
+ case "clinepass": {
545
+ const headers = {
546
+ Accept: "application/json",
547
+ Authorization: `Bearer ${connection.apiKey}`,
548
+ };
549
+ const modelsRes = await fetchWithConnectionProxy(
550
+ "https://api.cline.bot/api/v1/models",
551
+ { method: "GET", headers },
552
+ effectiveProxy
553
+ );
554
+ if (modelsRes.ok) {
555
+ return { valid: true, error: null };
556
+ }
557
+
558
+ const chatRes = await fetchWithConnectionProxy(
559
+ "https://api.cline.bot/api/v1/chat/completions",
560
+ {
561
+ method: "POST",
562
+ headers: { ...headers, "Content-Type": "application/json" },
563
+ body: JSON.stringify({
564
+ model: "cline-pass/glm-5.2",
565
+ messages: [{ role: "user", content: "ping" }],
566
+ max_tokens: 1,
567
+ stream: false,
568
+ }),
569
+ },
570
+ effectiveProxy
571
+ );
572
+ const valid = chatRes.status !== 401 && chatRes.status !== 403;
573
+ return {
574
+ valid,
575
+ error: valid ? null : "Invalid ClinePass API key",
576
+ };
577
+ }
578
+ case "cloudflare-ai": {
579
+ const psd = connection.providerSpecificData || {};
580
+ const accountId = psd.accountId;
581
+ if (!accountId) return { valid: false, error: "Missing Account ID" };
582
+ const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/v1/chat/completions`;
583
+ const res = await fetchWithConnectionProxy(url, {
584
+ method: "POST",
585
+ headers: { "Authorization": `Bearer ${connection.apiKey}`, "Content-Type": "application/json" },
586
+ body: JSON.stringify({ model: getDefaultModel("cloudflare-ai"), messages: [{ role: "user", content: "test" }], max_tokens: 1 }),
587
+ }, effectiveProxy);
588
+ const valid = res.status !== 401 && res.status !== 403 && res.status !== 404;
589
+ return { valid, error: valid ? null : "Invalid API token or Account ID" };
590
+ }
591
+ case "azure": {
592
+ const psd = connection.providerSpecificData || {};
593
+ const endpoint = (psd.azureEndpoint || "").replace(/\/$/, "");
594
+ const deployment = psd.deployment || "gpt-4";
595
+ const apiVersion = psd.apiVersion || "2024-10-01-preview";
596
+ const url = `${endpoint}/openai/deployments/${deployment}/chat/completions?api-version=${apiVersion}`;
597
+ const headers = { "api-key": connection.apiKey, "Content-Type": "application/json" };
598
+ if (psd.organization) headers["OpenAI-Organization"] = psd.organization;
599
+ const res = await fetchWithConnectionProxy(url, {
600
+ method: "POST", headers,
601
+ body: JSON.stringify({ messages: [{ role: "user", content: "test" }], max_completion_tokens: 1 }),
602
+ }, effectiveProxy);
603
+ const valid = res.status !== 401 && res.status !== 403;
604
+ return { valid, error: valid ? null : "Invalid API key or Azure configuration" };
605
+ }
606
+ case "openai": {
607
+ const res = await fetchWithConnectionProxy("https://api.openai.com/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
608
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
609
+ }
610
+ case "vercel-ai-gateway": {
611
+ const res = await fetchWithConnectionProxy("https://ai-gateway.vercel.sh/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
612
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
613
+ }
614
+ case "anthropic": {
615
+ const res = await fetchWithConnectionProxy("https://api.anthropic.com/v1/messages", {
616
+ method: "POST",
617
+ headers: { "x-api-key": connection.apiKey, "anthropic-version": "2023-06-01", "content-type": "application/json" },
618
+ body: JSON.stringify({ model: "claude-3-haiku-20240307", max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
619
+ }, effectiveProxy);
620
+ const valid = res.status !== 401;
621
+ return { valid, error: valid ? null : "Invalid API key" };
622
+ }
623
+ case "gemini": {
624
+ const res = await fetchWithConnectionProxy(`https://generativelanguage.googleapis.com/v1/models?key=${connection.apiKey}`, {}, effectiveProxy);
625
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
626
+ }
627
+ case "openrouter": {
628
+ const res = await fetchWithConnectionProxy("https://openrouter.ai/api/v1/auth/key", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
629
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
630
+ }
631
+ case "glm": {
632
+ const res = await fetchWithConnectionProxy("https://api.z.ai/api/anthropic/v1/messages", {
633
+ method: "POST",
634
+ headers: { "x-api-key": connection.apiKey, "anthropic-version": "2023-06-01", "content-type": "application/json" },
635
+ body: JSON.stringify({ model: "glm-4.7", max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
636
+ }, effectiveProxy);
637
+ const valid = res.status !== 401 && res.status !== 403;
638
+ return { valid, error: valid ? null : "Invalid API key" };
639
+ }
640
+ case "glm-cn": {
641
+ const res = await fetchWithConnectionProxy("https://open.bigmodel.cn/api/coding/paas/v4/chat/completions", {
642
+ method: "POST",
643
+ headers: { "Authorization": `Bearer ${connection.apiKey}`, "content-type": "application/json" },
644
+ body: JSON.stringify({ model: "glm-4.7", max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
645
+ }, effectiveProxy);
646
+ const valid = res.status !== 401 && res.status !== 403;
647
+ return { valid, error: valid ? null : "Invalid API key" };
648
+ }
649
+ case "minimax":
650
+ case "minimax-cn": {
651
+ const endpoints = { minimax: "https://api.minimax.io/anthropic/v1/messages", "minimax-cn": "https://api.minimaxi.com/anthropic/v1/messages" };
652
+ const res = await fetchWithConnectionProxy(endpoints[connection.provider], {
653
+ method: "POST",
654
+ headers: { "x-api-key": connection.apiKey, "anthropic-version": "2023-06-01", "content-type": "application/json" },
655
+ body: JSON.stringify({ model: "minimax-m2", max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
656
+ }, effectiveProxy);
657
+ const valid = res.status !== 401 && res.status !== 403;
658
+ return { valid, error: valid ? null : "Invalid API key" };
659
+ }
660
+ case "kimi": {
661
+ const res = await fetchWithConnectionProxy("https://api.kimi.com/coding/v1/messages", {
662
+ method: "POST",
663
+ headers: { "x-api-key": connection.apiKey, "anthropic-version": "2023-06-01", "content-type": "application/json" },
664
+ body: JSON.stringify({ model: "kimi-latest", max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
665
+ }, effectiveProxy);
666
+ const valid = res.status !== 401 && res.status !== 403;
667
+ return { valid, error: valid ? null : "Invalid API key" };
668
+ }
669
+ case "alicode":
670
+ case "alicode-intl":
671
+ case "alims-intl": {
672
+
673
+ const aliBaseUrl = connection.provider === "alicode-intl"
674
+ ? "https://coding-intl.dashscope.aliyuncs.com/v1/chat/completions"
675
+ : connection.provider === "alims-intl"
676
+ ? "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions"
677
+ : "https://coding.dashscope.aliyuncs.com/v1/chat/completions";
678
+ const res = await fetchWithConnectionProxy(aliBaseUrl, {
679
+ method: "POST",
680
+ headers: { "Authorization": `Bearer ${connection.apiKey}`, "content-type": "application/json" },
681
+ body: JSON.stringify({ model: getDefaultModel(connection.provider), max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
682
+ }, effectiveProxy);
683
+ const valid = res.status !== 401 && res.status !== 403;
684
+ return { valid, error: valid ? null : "Invalid API key" };
685
+ }
686
+ case "byteplus": {
687
+ const res = await fetchWithConnectionProxy(PROVIDERS[connection.provider]?.baseUrl, {
688
+ method: "POST",
689
+ headers: { "Authorization": `Bearer ${connection.apiKey}`, "content-type": "application/json" },
690
+ body: JSON.stringify({ model: getDefaultModel(connection.provider), max_tokens: 1, messages: [{ role: "user", content: "test" }] }),
691
+ }, effectiveProxy);
692
+ const valid = res.status !== 401 && res.status !== 403;
693
+ return { valid, error: valid ? null : "Invalid API key" };
694
+ }
695
+ case "deepseek": {
696
+ const res = await fetchWithConnectionProxy("https://api.deepseek.com/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
697
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
698
+ }
699
+ case "groq": {
700
+ const res = await fetchWithConnectionProxy("https://api.groq.com/openai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
701
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
702
+ }
703
+ case "mistral": {
704
+ const res = await fetchWithConnectionProxy("https://api.mistral.ai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
705
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
706
+ }
707
+ case "xai": {
708
+ const res = await fetchWithConnectionProxy("https://api.x.ai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
709
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
710
+ }
711
+ case "nvidia": {
712
+ const res = await fetchWithConnectionProxy("https://integrate.api.nvidia.com/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
713
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
714
+ }
715
+ case "perplexity": {
716
+ const res = await fetchWithConnectionProxy("https://api.perplexity.ai/router/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
717
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
718
+ }
719
+ case "together": {
720
+ const res = await fetchWithConnectionProxy("https://api.together.xyz/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
721
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
722
+ }
723
+ case "fireworks": {
724
+ const res = await fetchWithConnectionProxy("https://api.fireworks.ai/inference/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
725
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
726
+ }
727
+ case "cerebras": {
728
+ const res = await fetchWithConnectionProxy("https://api.cerebras.ai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
729
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
730
+ }
731
+ case "nebius": {
732
+ const res = await fetchWithConnectionProxy("https://api.studio.nebius.ai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
733
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
734
+ }
735
+ case "ollama": {
736
+ const res = await fetch("https://ollama.com/api/tags", { headers: { Authorization: `Bearer ${connection.apiKey}` } });
737
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
738
+ }
739
+ case "ollama-local": {
740
+ const host = resolveOllamaLocalHost(connection);
741
+ const res = await fetch(`${host}/api/tags`);
742
+ return { valid: res.ok, error: res.ok ? null : `Ollama not reachable at ${host}` };
743
+ }
744
+ case "chutes": {
745
+ const res = await fetchWithConnectionProxy("https://llm.chutes.ai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
746
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
747
+ }
748
+ case "grok-web": {
749
+ const token = connection.apiKey.startsWith("sso=") ? connection.apiKey.slice(4) : connection.apiKey;
750
+ const randomHex = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => b.toString(16).padStart(2, "0")).join("");
751
+ const statsigId = Buffer.from("e:TypeError: Cannot read properties of null (reading 'children')").toString("base64");
752
+ const res = await fetchWithConnectionProxy("https://grok.com/rest/app-chat/conversations/new", {
753
+ method: "POST",
754
+ headers: {
755
+ Accept: "*/*", "Content-Type": "application/json",
756
+ Cookie: `sso=${token}`, Origin: "https://grok.com", Referer: "https://grok.com/",
757
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
758
+ "x-statsig-id": statsigId, "x-xai-request-id": crypto.randomUUID(),
759
+ traceparent: `00-${randomHex(16)}-${randomHex(8)}-00`,
760
+ },
761
+ body: JSON.stringify({ temporary: true, modelName: "grok-4", message: "ping", fileAttachments: [], imageAttachments: [], disableSearch: false, enableImageGeneration: false, sendFinalMetadata: true }),
762
+ }, effectiveProxy);
763
+ const valid = res.status !== 401 && res.status !== 403;
764
+ return { valid, error: valid ? null : "Invalid SSO cookie" };
765
+ }
766
+ case "opencode-go": {
767
+ const res = await fetchWithConnectionProxy("https://opencode.ai/zen/go/v1/chat/completions", {
768
+ method: "POST",
769
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${connection.apiKey}` },
770
+ body: JSON.stringify({ model: getDefaultModel("opencode-go"), messages: [{ role: "user", content: "ping" }], max_tokens: 1, stream: false }),
771
+ }, effectiveProxy);
772
+ const valid = res.status !== 401 && res.status !== 403;
773
+ return { valid, error: valid ? null : "Invalid API key" };
774
+ }
775
+ case "xiaomi-mimo":
776
+ case "xiaomi-tokenplan": {
777
+ const baseUrls = { "xiaomi-mimo": "https://api.xiaomimimo.com/v1", "xiaomi-tokenplan": "https://token-plan-sgp.xiaomimimo.com/v1" };
778
+ const res = await fetchWithConnectionProxy(`${baseUrls[connection.provider]}/models`, {
779
+ headers: { Authorization: `Bearer ${connection.apiKey}` },
780
+ }, effectiveProxy);
781
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
782
+ }
783
+ case "blackbox": {
784
+ const baseUrl = PROVIDERS["blackbox"]?.baseUrl?.replace(/\/chat\/completions$/, "") || "https://api.blackbox.ai/v1";
785
+ const res = await fetchWithConnectionProxy(`${baseUrl}/models`, {
786
+ headers: { Authorization: `Bearer ${connection.apiKey}` },
787
+ }, effectiveProxy);
788
+ return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
789
+ }
790
+ case "qoder": {
791
+
792
+ const raw = connection.apiKey || "";
793
+ const pat = raw.startsWith("pt-") ? raw : `pt-${raw}`;
794
+ const exRes = await fetchWithConnectionProxy(
795
+ "https://openapi.qoder.sh/api/v1/jobToken/exchange",
796
+ {
797
+ method: "POST",
798
+ headers: {
799
+ "Content-Type": "application/json",
800
+ Accept: "application/json",
801
+ "Cosy-Version": "1.0.1",
802
+ "Cosy-ClientType": "5",
803
+ },
804
+ body: JSON.stringify({ personal_token: pat }),
805
+ },
806
+ effectiveProxy,
807
+ );
808
+ return { valid: exRes.ok, error: exRes.ok ? null : "Invalid Personal Access Token" };
809
+ }
810
+ default:
811
+ return { valid: false, error: "Provider test not supported" };
812
+ }
813
+ } catch (err) {
814
+ console.error("[ProviderConnectionTest] API-key probe failed:", err);
815
+ return { valid: false, error: "Provider connection test failed" };
816
+ }
817
+ }
818
+
819
+ export async function testSingleConnection(id) {
820
+ const connection = await getProviderConnectionById(id);
821
+ if (!connection) return { valid: false, error: "Connection not found", latencyMs: 0, testedAt: new Date().toISOString() };
822
+
823
+ const effectiveProxy = await resolveConnectionProxyConfig(connection.providerSpecificData || {});
824
+
825
+ if (effectiveProxy.proxyPoolUnavailable && effectiveProxy.strictProxy) {
826
+ const testedAt = new Date().toISOString();
827
+ const error = effectiveProxy.proxyPoolError || "Assigned proxy pool is unavailable";
828
+ await updateProviderConnection(id, {
829
+ testStatus: "error",
830
+ lastTested: testedAt,
831
+ lastError: error,
832
+ lastErrorAt: testedAt,
833
+ healthStatus: "error",
834
+ healthError: error,
835
+ healthLatencyMs: 0,
836
+ });
837
+ return {
838
+ valid: false,
839
+ error,
840
+ latencyMs: 0,
841
+ testedAt,
842
+ };
843
+ }
844
+
845
+ if (effectiveProxy.connectionProxyEnabled && effectiveProxy.connectionProxyUrl && !effectiveProxy.relayUrl && !effectiveProxy.vercelRelayUrl) {
846
+ const proxyResult = await testProxyUrl({ proxyUrl: effectiveProxy.connectionProxyUrl });
847
+ if (!proxyResult.ok) {
848
+ const proxyError = proxyResult.error || `Proxy test failed with status ${proxyResult.status}`;
849
+ const testedAt = new Date().toISOString();
850
+ await updateProviderConnection(id, {
851
+ testStatus: "error",
852
+ lastTested: testedAt,
853
+ lastError: proxyError,
854
+ lastErrorAt: testedAt,
855
+ healthStatus: "error",
856
+ healthError: proxyError,
857
+ healthLatencyMs: 0,
858
+ });
859
+ return { valid: false, error: proxyError, latencyMs: 0, testedAt };
860
+ }
861
+ }
862
+
863
+ const start = Date.now();
864
+ let result;
865
+
866
+ if (connection.authType === "apikey" || connection.authType === "cookie") {
867
+ result = await testApiKeyConnection(connection, effectiveProxy);
868
+ } else {
869
+ result = await testOAuthConnection(connection, effectiveProxy);
870
+ }
871
+
872
+ const latencyMs = Date.now() - start;
873
+ const testedAt = new Date().toISOString();
874
+
875
+ const softWarning = result.valid && (result.warning || result.error);
876
+ const updateData = {
877
+ testStatus: result.valid ? "active" : "error",
878
+ lastTested: testedAt,
879
+ lastError: result.valid ? (softWarning || null) : result.error,
880
+ lastErrorAt: result.valid
881
+ ? softWarning
882
+ ? testedAt
883
+ : null
884
+ : testedAt,
885
+ healthStatus: result.valid ? "healthy" : "error",
886
+ healthError: result.valid ? (softWarning || null) : (result.error || "Connection test failed"),
887
+ healthLatencyMs: latencyMs,
888
+ };
889
+
890
+ if (result.refreshed && result.newTokens) {
891
+ if (result.newTokens.accessToken) updateData.accessToken = result.newTokens.accessToken;
892
+ if (result.newTokens.refreshToken) updateData.refreshToken = result.newTokens.refreshToken;
893
+ if (result.newTokens.idToken) updateData.idToken = result.newTokens.idToken;
894
+ if (result.newTokens.lastRefreshAt) updateData.lastRefreshAt = result.newTokens.lastRefreshAt;
895
+ if (result.newTokens.expiresIn) updateData.expiresIn = result.newTokens.expiresIn;
896
+ if (result.newTokens.expiresIn) {
897
+ updateData.expiresAt = new Date(Date.now() + result.newTokens.expiresIn * 1000).toISOString();
898
+ } else if (result.newTokens.expiresAt) {
899
+ updateData.expiresAt = result.newTokens.expiresAt;
900
+ }
901
+ if (result.newTokens.providerSpecificData) {
902
+ updateData.providerSpecificData = {
903
+ ...(connection.providerSpecificData || {}),
904
+ ...result.newTokens.providerSpecificData,
905
+ };
906
+ }
907
+ }
908
+
909
+ await updateProviderConnection(id, updateData);
910
+
911
+ return { valid: result.valid, error: result.error, refreshed: !!result.refreshed, latencyMs, testedAt };
912
+ }